How to use mobile internet in PC with USB Tethering

Go to settings

Click on more networks

 

13662478_10154260946798363_1840651716_o

 

click on tethering and wifi hotspot..

 

13639537_10154260947348363_2031455470_o

 

connect the usb cable with your phone and Computer..
then Check USB Tethering..

 

13646754_10154260947738363_1391461354_o

 

then you will see notification like this

 

13663499_10154260948923363_885594616_o

 

Few Computers may complain – unidentified network.. no network access.. If you are using Intel motherboard, install this https://software.intel.com/en-us/android/articles/intel-usb-driver-for-android-devices

Further Read:

What App Developers Need to Know About the Android N

While the Android Marshmallow (version 6) hasn’t completely convinced every user, talks about the upcoming Android N are now creating a buzz online. The third developer preview of the OS was released in mid-May and experts predict that the consumer version will be out later this year.

However, Google is struggling to garner enough sales with their current mobile OS. According to recent research, the Android M only received 1.2% downloads four months after its official release in February. So, is Google planning to make the version 6 OS obsolete? Will it have the same fate as its predecessor?

The problem with the current Android version is that not all newly released handsets come with the aforementioned mobile OS. Many low- to mid-range mobile devices were initially equipped with the version 5 system (Lollipop), such as the Galaxy J5 which O2 states was only released in April. It would have helped Google widen the user scope of their Marshmallow OS if all devices released after February were already running the new Android system.

The third developer preview of the next Google mobile OS has given selected users a sneak peek at Android 7.0 — its upgraded features and new functionalities. Although the developer preview often contains features that do not appear on the final version, and there are plenty of exciting upgrades and functionalities that Google already confirmed for their next Android series. Below are some notable features that will be present on the Android N:

New Doze Mode
The popular Doze Mode feature of the Marshmallow was enhanced on the new Android by using a Two-Tier system. The initial tier works when the user isn’t using the device, as it will automatically place the handset on ‘Sleep Mode’ when it is in their pocket or backpack. The second tier works similarly to the current ‘Doze Mode’ with some slight improvements, as it places the handset in a deep hibernation mode when not in use that defers any connection before it goes to sleep. The sleep mode promises users a better quality of battery on the device.

Enhanced settings menu
A particular feature that Google enhanced on the next mobile OS is the settings menu that now comes with a Suggestions drop-down section. They also eliminated the individual section dividers to enter and exit the Settings page using only one button.

At the top-level section of the settings menu, users can now efficiently get the basic details about each section. So, there’s no need to enter the Wi-Fi section like before to see which network you are connected to, as you can now view it from the top part of the Settings page.

Sounds and Notifications are now separated and given their own dedicated sections.

In case, users need to escape the main settings, they just need to click the hamburger menu and it’ll return the user to the home page, which makes things easier in general.

Other previously featured functionalities
Here are other long-awaited features that were previously seen in the first two developer preview series that you need to know about:
• Change display size
• Faster app optimization
• Quick reply on notification through the lock screen
• New data server
• New built-in apps
• Unicode 9.0 emoji support
• Option to move Java APIs to OpenJDK

Latest Update
The 3rd installment of the developer preview received a “beta-quality candidate” status, where apps can now be tested by installing the newest preview version. It currently supports selected Google handsets, such as Nexus 5X and above, Nexus Player, Pixel C, and the General Mobile 4G.

In its last preview before its release, the company highlighted big features, including the seamless updates similar to the Chrome OS as well as its virtual reality mode.

The company said the team “worked at all levels of the Android stack in N — from how the operating system reads sensor data to how it sends pixels to the display — to make it especially built to provide high quality mobile VR experiences.”

Google confirmed that the new Android OS would be released in the third quarter of the year, which gives developers until the end of September to fix any issues before its official launch.

How to deal with cookies from iframe in IE?

Problem:

We are unable to deal with cookies in IE from iFrame which leads to inconsistent authentication.

Reason :

 As it is, Internet Explorer gives lower level of trust to iframe content and blocks third-party content. If the page inside the iframe doesn’t have a Privacy Policy, its cookies are blocked. if the inner page sends a P3P header with a privacy policy that is acceptable to IE, the cookies will be accepted.

What we have done:

 As IE wants you to define a P3P header if you are using cookies. So we declare our p3p policies as follows from the server side :

response.setHeader(“P3P”,”CP=’PUT WHATEVER CONTENT YOU WANT’”)

We have used some arbitrary data in the P3P header. But a P3P statement is a legal declaration of how your cookie will be used. So we shouldn’t just throw some arbitrary data into a P3P header which may lead to violation of privacy laws.

I found following resources useful for better understanding of the issue and P3P policy creation:

 https://blogs.msdn.microsoft.com/ieinternals/2013/09/17/a-quick-look-at-p3p/
http://stackoverflow.com/questions/389456/cookie-blocked-not-saved-in-iframe-in-internet-explorer
https://www.w3.org/P3P/
https://msdn.microsoft.com/en-us/library/aa920127.aspx
http://www.techrepublic.com/blog/software-engineer/craft-a-p3p-policy-to-make-ie-behave/

How to generate SSH key in windows?

The first step is to check for existing SSH keys on your local computer. Run following command from a command prompt:

cd %userprofile%/.ssh

If output shows as “No such file or directory” that means you do not have any existing keys in your machine. Otherwise you can check the existing SSH keys using following command:

dir id_*

The second step is to create set of private/public pair on your machine if it doesn’t exist in your machine. ssh-keygen is used to generate the key pair as follows:

ssh-keygen -t rsa

The above command initiated the creation of the key pair and -t option specifies the type of key to create. You will get a few more questions:

Enter file in which to save the key (<your user profile directory>/.ssh/id_rsa):   
Enter passphrase (empty for no passphrase):
Enter same passphrase again:

You can press enter to store the key in your user profile directory and avoid passphrase by pressing enter key. The private key was saved in .ssh/id_rsa and the public key was saved in .ssh/id_rsa.pub. Now copy the public key file to your clipboard by running:

cd %userprofile%/.ssh
clip < id_rsa.pub

Now the public key is then used onto a remote systems. And you can now SSH to the remote system’s account without the use of a password.

What is SSH Key?

ssh-keygen: a more secure way of logging than using a password

SSH can be used to login from one system to another without using passwords. Using SSH is more secure as it is nearly impossible to be cracked while a password can be cracked with a brute force attack. For password less SSH login a number of methods may be used. One of which requires you generate your own personal set of private/public pair. ssh-keygen is used for generating that key pair for you. The public key is then copied onto a remote systems and can be connecting to a client that already has the private key. The private key is used to decrypt all correspondence encrypted with the public key.

 

How to install worklight with IBM eclipse

I have been facing issues installing eclipse luna in my machine which exists with “java was started but returned exit code=13″ error. So using following steps I have installed IBM® Worklight Studio into eclipse luna :

  1. Download IBM eclipse from https://www.ibm.com/developerworks/java/jdk/java8/
  2. Initially the Eclipse marketplace is not available on help menu. So we need to add http://download.eclipse.org/mpc/luna/ as an Eclipse software repository to get the Eclipse marketplace in help menu.
  3. Install IBM MobileFirst Platform Studio.

How to Share Flickr Album Photos and access shared photos

Flickr Albums are collections of photos by a single user.. Flickr does not have a concept of Shared Albums Like Facebook. There can not be multiple editors in Flickr Album.. So if multiple users need to share photos in a common place on flickr, Flickr Groups need to be created.

Scenario

my flickr account name is sayan801.. I want to  share our chadar trek photo with my company flickr account technicise and other friends.

Create Group for Sharing

At first create a flickr Group..

Capture-1

Then go to the group..

Sharing with Friends

Now invite your friends from Invite Friends Tab..

Capture

Your friends will receive an email like this..

download (3)

when your friend clicks in this link, it will ask you to join flickr or login with existing account..

Then go to flickr.com..
Click on You –> Groups..

download (5)

Your friend can see the group as below..

download (1)

click on that.. You can access the photos..

Add Photos to Shared Group

Now click on top write cloud shaped upload icon..

download

Select the photos..

download (6)

left hand side you can see “Add to Groups”.. click on that select the Chadar Group..

download (7)

 

select privacy and search options.

download (8)

Now you can click on Upload photo on top right hand side..

Now your photos has been added to the Group.

i must agree flickr has very confusing and hard to use interface.. but their photo quality, 1 TB storage make it worth using..

Note:

if you are adding photos by going to the group itself it allows to add 6 photos at a time.. But if you do a normal upload and and select group, it allows as many as you want.

How i feel about Net Neutrality , Internet.org , Free Basics by Facebook

Today morning i woke up reading a very well written article by Mahesh Murthy (https://www.linkedin.com/pulse/facebook-misleading-indians-its-full-page-ads-free-basics-murthy)…
I could see few of my friends already have fallen for facebook’s free basics/ digital equality/ internet.org trap.. There is no way to undo it..
just imagine facebook is not allowing us to undo its poll , what will happen if we let them implement free basics..

Read this article and if you agree please sign the petition ( http://www.savetheinternet.in/ ) …
We want full and open internet… #openinternet?  #IndiansDontNeedFreeBasics

No its not free internet.. Its free few websites when you buy a paid cellular subscription from their partners( reliance , idea etc) .. i dont have problem with free goodies until its not harmful.. i wont try free cigarettes as it can cause cancer in future.. My problem is with monopoly of facebook who is trying to sidetrack users from very essential websites which wont be available for free..

facebook has provided free or low cost internet to many consumers already.. i have seen such users in nepal, bangladesh who have used their monthly ~5 rupees plan free 100 mb fb and whatsapp.. As a result , internet to them is only fb and whatsapp.. They dont know about email, google and many other essential websites..

And moreover this free basics is for limited period of time, when they gain their target for acquiring users they will stop this campaign… and users will be only used to partial internet..

i am not moral policing .. fb is trying to change the telecommunication/ spectrum laws and policies of India which will effect every Indians in future.. And they are doing it by MISLEADING normal internet users in the name of helping POORs.. I do not want to subscribe to Internet websites like current DTH model.. If we let them do this now, we will see in future monthly packs like DTH TV where you have to buy google search pack for 50 inr by month… Read these blog posts http://blog.savetheinternet.in/

Android Login & Registration Using SQLite

In this tutorial we will look at how SQLite can be used in Android application to persist and retrieve data.

activity_main.xml

<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
xmlns:tools=”http://schemas.android.com/tools”
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:orientation=”vertical”
android:gravity=”center_vertical” >

<Button
android:id=”@+id/buttonSignIN”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”Sign In”
android:onClick=”signIn”
android:clickable=”true”/>

<Button
android:id=”@+id/buttonSignUP”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”Sign Up”
android:onClick=”signUp”
android:clickable=”true”
/>

</LinearLayout>

 

Its Corresponding Java Class

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class MainActivity extends Activity {

 

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}

public void signIn(View i)
{
Intent in = new Intent(getApplicationContext(), SignIn.class);
startActivity(in);

}

public void signUp(View i)
{
Intent in = new Intent(getApplicationContext(), SignUp.class);
startActivity(in);

}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}

return super.onOptionsItemSelected(item);
}
}

 

Created By Amiyo

Created By Amiyo

Now if user click SignUp Button then new activity appear which name is Signup activity .

Here is Signup class

 

public class SignUp extends Activity {

public EditText TextUserName,TextPassword,TextEmail;
public String UserName,UserPassword,UserEmail;

DataBaseHelper dConnector = new DataBaseHelper(this);
Contact form = new Contact();

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);

TextUserName=(EditText)findViewById(R.id.editTextUserName);
TextPassword=(EditText)findViewById(R.id.editTextPassword);
TextEmail=(EditText)findViewById(R.id.editTextEmail);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_sign_up, menu);
return true;
}

public void AccountCreate(View i)
{

UserName=TextUserName.getText().toString().trim();
UserPassword=TextPassword.getText().toString().trim();
UserEmail=TextEmail.getText().toString().trim();

if(UserName != null && !UserName.isEmpty() && UserPassword !=null && !UserPassword.isEmpty()) {

form.setEmail(UserEmail);
form.setUsername(UserName);
form.setPassword(UserPassword);

dConnector.addRecord(form.getEmail(),form.getUsername(),form.getPassword());

Toast.makeText(getApplicationContext(), “Account Successfully Created “, Toast.LENGTH_LONG).show();

Intent in = new Intent(getApplicationContext(), MainActivity.class);
startActivity(in);

 

}
else{

Toast.makeText(getApplicationContext(), “Something went wrong “, Toast.LENGTH_LONG).show();

}
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}

return super.onOptionsItemSelected(item);
}
}

 

Here is activity_sign_up.xml

<?xml version=”1.0″ encoding=”utf-8″?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:orientation=”vertical”
android:gravity=”center_vertical” >

<EditText
android:id=”@+id/editTextEmail”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:hint=”Email”
android:inputType=”textEmailAddress” />

<EditText
android:id=”@+id/editTextUserName”
android:hint=”User Name”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
>

<requestFocus />
</EditText>
<EditText
android:id=”@+id/editTextPassword”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:hint=”Password”
android:inputType=”textPassword” />

 

<Button
android:id=”@+id/buttonCreateAccount”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”Create Account”
android:clickable=”true”
android:onClick=”AccountCreate”
android:layout_marginBottom=”60dp” />

</LinearLayout>

Here is Contact class

public class Contact {

private String email;
private String username;
private String password;
public String getEmail() {

return email;

}

public void setEmail(String email) {

this.email = email;

}
public String getUsername() {

return username;

}

public void setUsername(String username) {

this.username = username;

}

public String getPassword() {

return password;

}

public void setPassword(String password) {

this.password = password;

}

}

A model Class with getters and setters for form elements and DataBaseHelper Class which takes care of creating database, table, inserting data into database and retrieving data from the database.

Created By : Amiyo Biswas

Created By : Amiyo Biswas

If user successfully registered then it moved to Main Activity & if User Click Sign In Button then Login Activity appear .

SignIn Activity

 

Here is SignIn Class .

 

public class SignIn extends Activity {

public EditText TextUserNameToLogin,TextPasswordToLogin;
public String UserName,UserPassword;

DataBaseHelper dConnector = new DataBaseHelper(this);

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_in);

TextUserNameToLogin=(EditText)findViewById(R.id.editTextUserNameToLogin);
TextPasswordToLogin=(EditText)findViewById(R.id.editTextPasswordToLogin);

}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_sign_in, menu);
return true;
}

public void SignIn(View i)
{
UserName=TextUserNameToLogin.getText().toString().trim();
UserPassword=TextPasswordToLogin.getText().toString().trim();
// fetch the Password form database for respective user name

 

if(UserName != null && !UserName.isEmpty() && UserPassword !=null && !UserPassword.isEmpty()) {
try {
List<String> userRecord = dConnector.getRecord(UserName,UserPassword);
Log.d(“Login onClick()”, String.valueOf(userRecord));
String Data2=userRecord.get(1);
String Data=userRecord.get(0);
// String Data3=userRecord.get(2);

Toast.makeText(getApplicationContext(), Data+Data2, Toast.LENGTH_SHORT).show();

Intent in = new Intent(getApplicationContext(), UserHome.class);
in.putExtra(“name”, Data);
in.putExtra(“email”,Data2);
startActivity(in);
}

catch (Exception e) {
Toast.makeText(getApplicationContext(), “Login Failed, Record Not Found”, Toast.LENGTH_SHORT).show();
e.printStackTrace();
}

}
else{

Toast.makeText(SignIn.this, “Fill Up”, Toast.LENGTH_LONG).show();
}
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}

return super.onOptionsItemSelected(item);
}
}

 

Here its xml

<?xml version=”1.0″ encoding=”utf-8″?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:orientation=”vertical” >

<EditText
android:id=”@+id/editTextUserNameToLogin”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:hint=”User Name”
android:ems=”10″ >
<requestFocus />
</EditText>
<EditText
android:id=”@+id/editTextPasswordToLogin”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:ems=”10″
android:inputType=”textPassword”
android:hint=”Password” />

<Button
android:id=”@+id/buttonSignIn”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”Sign In”
android:clickable=”true”
android:onClick=”SignIn”/>

</LinearLayout>

 

If User Name & Password match then UserHome Will appear . Here i showing user data.

Here is UserHome class .

 

public class UserHome extends Activity {

public EditText TextUserName,TextEmail;
public String UserName,UserEmail;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_home);

TextUserName=(EditText)findViewById(R.id.editTextUserName);
TextEmail=(EditText)findViewById(R.id.editTextEmail);

UserName=TextUserName.getText().toString().trim();
UserEmail=TextEmail.getText().toString().trim();

ShowInfo();

}

public void ShowInfo(){

Intent in= getIntent();
Bundle b = in.getExtras();
Bundle c = in.getExtras();

if(b!=null && c!=null)
{
String n =(String) b.get(“name”);

String j =(String) b.get(“email”);

TextUserName.setText(n);
TextEmail.setText(j);

}

 

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_user_home, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}

return super.onOptionsItemSelected(item);
}
}

 

Here is activity_user_home.xml

<?xml version=”1.0″ encoding=”utf-8″?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:orientation=”vertical”
android:gravity=”center_vertical” >

<EditText
android:id=”@+id/editTextUserName”
android:hint=”User Name”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
>

<requestFocus />
</EditText>

<EditText
android:id=”@+id/editTextEmail”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:hint=”Password”
android:inputType=”textEmailAddress” />

</LinearLayout>

 

Created By : Amiyo Biswas

Created By : Amiyo Biswas

 

 

 

 

 

 

 

 

 

How to restart Android Phone if phone is hanged

I have installed Android Lollipop on my Nexus 4 yesterday.. Today while chatting , suddenly my phone got hanged.. I have Screen lock set with Pattern.. After few seconds screen got locked.. Whenever i am trying to unlock i see following screen.. None of the buttons were working.. In nexus 4 you cant remove battery very easily and power off button also not working.. It was a complete deadlock..

10833970_760717293966106_1443141527_n

Suddenly i got an Idea.. I connected my nexus to my Laptop using USB cable.. Opened Up Android Studio.. then Opened up Adb Terminal.. Ran Reboot command from Adb shell.. Finally i could reboot my nexus 4..

retrieve

Steps:
1. Open Up Android Studio
2. Click on Tools –> Open Terminal
3. Type “adb shell” in the terminal below and press enter
4. Type “reboot” and press enter

Your device should reboot..

Few Android Apps Which you cant ignore

Android Listview Pagination

In  this is the basic step to implement paging concept in ListView .We can say dynamic loading of element. ListView is very useful and powerful view in android.So this will help you a lot.In this tutorials you see how to parse JSON data from REST API & then showing in ListView dynamically .

Create a blank activity , Java Page Name :MainActivity , XML Page Name :activity_main.

Don’t try to copy & paste code until you understand whats going on .

MainActivity.java

package com.example.androidjsontesting;

import android.app.*;
import android.os.*;
import android.widget.*;
import org.json.*;
import android.content.Context;
import android.util.Log;
import android.view.View;
import java.util.ArrayList;

public class MainActivity extends Activity {

public TextView lPageNavigatorText;
public Context lContext;
public Button lSearchButton ;
public EditText lSearchEdit;
public ListView lItemList;
public ProgressDialog lProgressDia;
public LinearLayout lPageNavLayout;

// contacts JSONArray
JSONArray lJSONArray = null;

int lItemsSize = 0;
int lPagesSize=0;
ContactListAdapter lListAdapter;
ArrayList<Contact> lResultContacts;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

lContext = MainActivity.this;

lSearchButton=(Button)findViewById(R.id.buttonSearch);
lSearchButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View lView)
{
new GetContacts().execute();
}
});

lSearchEdit=(EditText)findViewById(R.id.Searchtext);
lPageNavigatorText = (TextView)findViewById(R.id.title);
lItemList = (ListView)findViewById(R.id.list);
lPageNavLayout = (LinearLayout)findViewById(R.id.btnLay);

lResultContacts = getEmptyContacts();

lListAdapter = new ContactListAdapter(lContext, new ArrayList<Contact>() );
lItemList.setAdapter(lListAdapter);

/* Get Total Size. */
lItemsSize = getItemsSize();

/* Get the pages. */
lPagesSize = calculatePages(lItemsSize, 10);

new GetContacts().execute();
}

@Override
public void onStart()
{
super.onStart();
}

/**
* Get the contacts.
*/
ArrayList<Contact> getEmptyContacts()
{
return new ArrayList<Contact>();
}

/**
* Get the total item size.
*/
public int getItemsSize()
{
return lResultContacts.size();
}

/**
* Get how much pages need to create for the item size.
*/
int calculatePages(int lSize, int lItemsPerPage)
{
int pages = lSize/lItemsPerPage;
if(pages * lItemsPerPage!= lSize)
{
pages ++;
}
return pages;
}

/**
* Draw the pages on screen.
*/
public void drawPages(int lSize)
{
final int lPageNumbers = lSize;
Button lPages[] = new Button[lPageNumbers];
for(int r = 0; r < lPages.length; r++)
{
lPages[r] = new Button(lContext);
lPages[r].setText( ( r + 1) + “”);
lPages[r].setId(r );
lPages[r].setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View lView)
{
manualClick(lView);
}
});
}

/* Add the button at scrollview. */
for(Button lPageButton:lPages)
{
lPageNavLayout.addView(lPageButton);
if(lPageButton.getId() == 0 && !lResultContacts.isEmpty())
{
manualClick(lPageButton);
}
}
}

/**
* Get the url from search edit.
*/
public String goToURL()
{
String ts= lSearchEdit.getText().toString();
String url = “http://latest.bloomapi.com/api/search?limit=50&offset=0&key1=last_name&op1=eq&value1=”+ts;
return url ;
}

public void manualClick(View lView)
{

int lPageNumber = lView.getId();
if(lItemList!=null && lListAdapter!=null)
{
if(!lResultContacts.isEmpty())
{
lListAdapter.lContactsData.clear();

try{
lListAdapter.lContactsData.add(lResultContacts.get(lPageNumber*10));

if(lResultContacts.size() >= ((lPageNumber*10) + 1 ))
{
lListAdapter.lContactsData.add(lResultContacts.get((lPageNumber*10) + 1 ));
}
if(lResultContacts.size() >= ((lPageNumber*10) + 2 ))
{
lListAdapter.lContactsData.add(lResultContacts.get((lPageNumber*10) + 2));
}
if(lResultContacts.size() >= ((lPageNumber*10) + 3 ))
{
lListAdapter.lContactsData.add(lResultContacts.get((lPageNumber*10) + 3));
}
if(lResultContacts.size() >= ((lPageNumber*10) + 4 ))
{
lListAdapter.lContactsData.add(lResultContacts.get((lPageNumber*10) + 4));
}
if(lResultContacts.size() >= ((lPageNumber*10) + 5 ))
{
lListAdapter.lContactsData.add(lResultContacts.get((lPageNumber*10) + 5 ));
}
if(lResultContacts.size() >= ((lPageNumber*10) + 6 ))
{
lListAdapter.lContactsData.add(lResultContacts.get((lPageNumber*10) + 6 ));
}
if(lResultContacts.size() >= ((lPageNumber*10) + 7 ))
{
lListAdapter.lContactsData.add(lResultContacts.get((lPageNumber*10) + 7 ));
}
if(lResultContacts.size() >= ((lPageNumber*10) + 8 ))
{
lListAdapter.lContactsData.add(lResultContacts.get((lPageNumber*10) + 8 ));
}
if(lResultContacts.size() >= ((lPageNumber*10) + 9 ))
{
lListAdapter.lContactsData.add(lResultContacts.get((lPageNumber*10) + 9 ));
}

lPageNavigatorText.setText(((lPageNumber*10)+1) +”-” + (((lPageNumber*10)+9)+1));

}catch(Exception lE){

/* Calculate how much items the page should contains. */
int lItemsShown = (lPagesSize -1)* 10;
/* but */
int lExtraItems = lItemsSize – lItemsShown;
int i = 0;
lListAdapter.lContactsData.clear();
while(i < lExtraItems)
{
lListAdapter.lContactsData.add(lResultContacts.get(lItemsShown + i));
i++;
}
//lPageNavigatorText.setText( (lPageNumber+1) + “” + lItemsSize + ” ” + ((lPageNumber*10)+1) +”-” + lItemsSize + “/” + lItemsSize);
lPageNavigatorText.setText(((lPageNumber*10)+1) +”-” + (((lPageNumber*10)+9)+1));
}
lListAdapter.notifyDataSetChanged();

}
}else{

}
}

/**
* Get private class to load contacts.
*/
private class GetContacts extends AsyncTask<Void, Void, Void> {

ArrayList<Contact> lContactsArray;

@Override
protected void onPreExecute()
{
super.onPreExecute();
lProgressDia = new ProgressDialog(MainActivity.this);
lProgressDia.setMessage(“Please wait…”);
lProgressDia.setCancelable(false);
lProgressDia.show();
lContactsArray = new ArrayList<Contact>();
}

@Override
protected Void doInBackground(Void… arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(goToURL(), ServiceHandler.GET);
Log.d(“Response: “, “> ” + jsonStr);
if (jsonStr != null)
{
try
{
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
lJSONArray = jsonObj.getJSONArray(“result”);
// looping through All Contacts
for (int i = 0; i < lJSONArray.length(); i++) {
Integer a = lJSONArray.length();
Log.d(“loop”, a.toString());
JSONObject c = lJSONArray.getJSONObject(i);

String id = c.getString(“npi”);
String name = c.getString(“first_name”);
String email = c.getString(“last_name”);

Contact lContact = new Contact();
lContact.lName = name;
lContact.lEmail = email;
lContact.lMobile = id;

lContactsArray.add(lContact);

}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.d(“ServiceHandler”, “Couldn’t get any data from the url”);
}
return null;
}

@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (lProgressDia.isShowing())
lProgressDia.dismiss();

lResultContacts = lContactsArray;
/* Clear all views. */
lPageNavLayout.removeAllViewsInLayout();

lItemsSize = getItemsSize();
lPagesSize = calculatePages( lItemsSize, 10);
try
{
drawPages(lPagesSize);
}catch(Exception r){

}
lListAdapter.notifyDataSetChanged();
}

}

}

Here is my activity_xml page :

<?xml version=”1.0″ encoding=”utf-8″?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
android:orientation=”vertical”>

<EditText
android:id=”@+id/Searchtext”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:ems=”10″
android:inputType=”textCapCharacters”
android:textColor=”@android:color/black”
/>

<Button
android:id=”@+id/buttonSearch”
android:layout_width=”125dp”
android:layout_height=”35dp”
android:text=”@string/search”
android:gravity=”center”
android:layout_gravity=”center”
android:background=”@android:color/holo_blue_bright”

/>

<TextView
android:id=”@+id/title”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:textColor=”@android:color/black”
android:gravity=”center”
android:textSize=”16sp”
android:background=”@android:color/darker_gray”
android:padding=”10dp”/>

<ListView
android:id=”@+id/list”
android:divider=”#000″
android:dividerHeight=”1dp”
android:cacheColorHint=”#00000000″
android:layout_width=”fill_parent”
android:layout_height=”0dp”
android:layout_weight=”1″
android:fadingEdge=”none”/>

<HorizontalScrollView
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”>
<LinearLayout
android:id=”@+id/btnLay”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:orientation=”horizontal” >
</LinearLayout>
</HorizontalScrollView>

</LinearLayout>

Create another blank activity ,set xml file name :activity_single_contact.xml & java file name :SingleContactActivity.java

Here is my xml file

<?xml version=”1.0″ encoding=”utf-8″?>
<LinearLayout
xmlns:android=”http://schemas.android.com/apk/res/android”
android:orientation=”vertical”
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:padding=”10dp”>
<!– Name Label –>
<TextView android:id=”@+id/name_label”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:textSize=”25sp”
android:textStyle=”bold”
android:paddingTop=”10dip”
android:paddingBottom=”10dip”
android:textColor=”#43bd00″/>
<!– Email Label –>
<TextView android:id=”@+id/email_label”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:textColor=”#acacac”/>
<!– Mobile Label –>
<TextView android:id=”@+id/mobile_label”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:textStyle=”bold”/>
</LinearLayout>

Here is my java file code .

package com.example.androidjsontesting;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class SingleContactActivity extends Activity {

// JSON node keys
private static final String TAG_NAME = “name”;
private static final String TAG_EMAIL = “email”;
private static final String TAG_PHONE_MOBILE = “mobile”;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single_contact);

// getting intent data
Intent in = getIntent();

// Get JSON values from previous intent
String name = in.getStringExtra(TAG_NAME);
String email = in.getStringExtra(TAG_EMAIL);
String mobile = in.getStringExtra(TAG_PHONE_MOBILE);

// Displaying all values on the screen
TextView lblName = (TextView) findViewById(R.id.name_label);
TextView lblEmail = (TextView) findViewById(R.id.email_label);
TextView lblMobile = (TextView) findViewById(R.id.mobile_label);

lblName.setText(name);
lblEmail.setText(email);
lblMobile.setText(mobile);
}
}

Create list_item.xml which shows users name,email id , mobile number in listview .

<?xml version=”1.0″ encoding=”utf-8″?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:orientation=”vertical”
android:padding=”10dp”
android:paddingLeft=”10dp”
android:paddingRight=”10dp” >

<!– Name Label –>

<TextView
android:id=”@+id/name”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:paddingBottom=”2dip”
android:paddingTop=”6dip”
android:textColor=”#43bd00″
android:textSize=”16sp”
android:textStyle=”bold” />

<!– Email label –>
<TextView
android:id=”@+id/email”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:paddingBottom=”2dip”
android:textColor=”#acacac” />

<!– Mobile number label –>
<TextView
android:id=”@+id/mobile”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:gravity=”left”
android:text=”Mobile: “
android:textColor=”#5d5d5d”
android:textStyle=”bold” />

</LinearLayout>

 Now create ServiceHandler class .

Here is my code :ServiceHandler.java

package com.example.androidjsontesting;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

public class ServiceHandler {

static String response = null;
public final static int GET = 1;
public final static int POST = 2;

public ServiceHandler() {

}

/*
* Making service call
* @url – url to make request
* @method – http request method
* */
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}

/*
* Making service call
* @url – url to make request
* @method – http request method
* @params – http request params
* */
public String makeServiceCall(String url, int method,
List<NameValuePair> params) {
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;

// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}

httpResponse = httpClient.execute(httpPost);

} else if (method == GET) {
// appending params to url
if (params != null) {
String paramString = URLEncodedUtils
.format(params, “utf-8″);
url += “?” + paramString;
}
HttpGet httpGet = new HttpGet(url);

httpResponse = httpClient.execute(httpGet);

}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);

} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

return response;

}
}

Now create ContactListAdapter.java file .This page make a vital role over all project. Before starting this page you take a look about Android BaseAdapter .

Here is my code ContactListAdapter.java

package com.example.androidjsontesting;

import android.view.*;
import android.widget.*;

import android.content.Context;

import com.example.androidjsontesting.R;
import java.io.Serializable;
import java.util.ArrayList;

@SuppressWarnings(“serial”)
public class ContactListAdapter extends BaseAdapter implements Serializable
{

/* Variables. */
public ArrayList<Contact> lContactsData;
private LayoutInflater lInflater;

public ContactListAdapter(Context lContext, ArrayList<Contact> lDataList)
{
lContactsData = lDataList;
lInflater = LayoutInflater.from(lContext);
}

public int getCount(){
return lContactsData.size();
}

public Object getItem( int position) {
return lContactsData.get(position);
}

public String getName(int p){
return lContactsData.get(p).lName;
}

public ArrayList<Contact> getArrayData()
{
return lContactsData;
}

public long getItemId( int position) {
return position;
}

/**
* Get the view by return, List view will shows the views one by one.
*/
public View getView( int lPosition, View lView, ViewGroup lViewGroup)
{
/* Get a empty View Holder.*/
ViewHolder lViewHolder;
if (lView == null )
{
lView = lInflater.inflate(R.layout.list_item, null );
lViewHolder = new ViewHolder();
lViewHolder.lName = (TextView) lView.findViewById(R.id.name);
lViewHolder.lEmail = (TextView) lView.findViewById(R.id.email);
lViewHolder.lMobile = (TextView) lView.findViewById(R.id.mobile);

lView.setTag(lViewHolder);
}
else
{
lViewHolder = (ViewHolder) lView.getTag();
}

lViewHolder.lName.setText(((Contact)this.getItem(lPosition)).lName);
lViewHolder.lEmail.setText(((Contact)this.getItem(lPosition)).lEmail);
lViewHolder.lMobile.setText(((Contact)this.getItem(lPosition)).lMobile);

return lView;
}

/** private static class which hold the web name and thumb */
private static class ViewHolder {
TextView lName, lEmail, lMobile;
@SuppressWarnings(“unused”)
ImageView lThumb;
}
}

Finally i create Contact.java page . Where i initialize users name,email,mobile no.

package com.example.androidjsontesting;

public class Contact

{
public String lName, lEmail, lMobile;
}

If it give error for iamges then use any other images and run application & Add this code in your manifest file

<uses-permission android:name=”android.permission.INTERNET” />

Android Listview Pagination

How to send value from one activity to another in Android

I have explained how to open one activity from another activity on button click in an earlier post. This post is just an extension of that tutorial which shows how to send value from one activity to another activity in Android. As you have seen, we can easily open one activity from another using Android intent. To send some extra message, it again is the Android intent that would help us.

First, take an Android edittext in your layoutOne and get the value to a string variable in the layoutOne’s java page(inside the openNewActivity method of course.). Then add the value to the intent using putExtra method. Now call the second activity.  See the code below:

public void openNewActivity(View view) {

// Do something in response to button
Intent intent = new Intent(this, LayoutTwoActivity.class);

//get the value of the editText, convert it to string and store it in a string variable
EditText editText = (EditText) findViewById(R.id.myEditText);
String message = editText.getText().toString();

intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);

}

You also need to add the definition of the EXTRA_MESSAGE variable at the beginning of the class like,

public final static String EXTRA_MESSAGE = “com.example.buttonclicktutorial.MESSAGE”;

Inside the second layout, take a textview. Now, all you need to do is to get the value from the intent and set the value to the textview. We are going to do it inside the onCreate method of Course. See the code below:

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_two);

//get the intent and take the value to a string message variable
Intent intent = getIntent();
String message = intent.getStringExtra(LayoutOneActivity.EXTRA_MESSAGE);

//set the value of message to the textview
TextView textView = (TextView)findViewById(R.id.myTextView);
textView.setText(message);
}

 

All done. Now run the app and see whether it works like the below screenshots or not:

button click1

 

button click2

 

Download the source code from here.