GenericAsyncTaskLib

In most of the android applications it is essential that app may need to connect to internet and make some HTTP requests. In this article i’ll be demonstrating about making simple HTTP Requests in android.

GenericAsyncTaskLib (also known as Generic AsyncTask Llibrary) is a Java library to make asynchronous HTTP call throughtout application .It can also be used to convert a JSON string to an equivalent Java object.It can perform variation operation as GET,POST,PUT,DELETE,File Download & File Upload to server.


Creating HTTP Client and HTTP Post :

MethodType : GET

String urlGET = “http://jsonplaceholder.typicode.com/comments”

CustomAsyncTask mAsyncTask = new CustomAsyncTask(MainActivity.this,urlGET, “GET”);

mAsyncTask.execute();

 MethodType : POST

Login mLogin = new Login();
mLogin.setUserName(“abc”);
mLogin.setPassWord(“abc123”);

/* Create Object & pass to create JSONObject */
String jsonObject = ServiceCall.createRequest(mLogin);
String urlPOST = “http://192.168.10.100:8080/api/login”;
CustomAsyncTask mAsyncTask = new CustomAsyncTask(MainActivity.this,urlPOST, “POST” ,jsonObject);
mAsyncTask.execute();

But if Request is NameValuePair :

// Building post parameters, key and value pair
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);
nameValuePair.add(new BasicNameValuePair("email", "user@gmail.com"));
nameValuePair.add(new BasicNameValuePair("password", "encrypted_password"));

File Download :

String urlDOWNLOAD = “http://api.androidhive.info/progressdialog/hive.jpg&#8221;;

String pathToSaveFile = “/sdcard/test.jpg”;

CustomAsyncTask mAsyncTask = new CustomAsyncTask(MainActivity.this,urlDOWNLOAD,pathToSaveFile,”DOWNLOAD”);

mAsyncTask.execute();

File Upload:

String urlUPLOAD = “http://192.168.56.1:8080/api/uploadImager&#8221;;

String uploadedFilePath = “Uploded File path”;

CustomAsyncTask mAsyncTask = new CustomAsyncTask(MainActivity.this, urlUPLOAD,uploadedFilePath,”UPLOAD”);

mAsyncTask.execute();

Progress Dialog :

Progress Dialog can be shown using ProgressDialog class. It is a subclass of normal AlertDialog class. So add an alert method in your main activity class.

private ProgressDialog pDialog;
public static final int progress_bar_type = 0;
progressDialog(progress_bar_type);

private void progressDialog(int progress_bar_type){

switch (progress_bar_type) {
case 0:
pDialog = new ProgressDialog(this);
pDialog.setMessage(“Please wait…”);
pDialog.setCancelable(false);
pDialog.show();
break;
case 1:
pDialog = new ProgressDialog(this);
pDialog.setMessage(“Downloading file. Please wait…”);
pDialog.setIndeterminate(false);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(true);
pDialog.show();
break;
case 2:
pDialog = new ProgressDialog(this);
pDialog.setMessage(“Uploading file. Please wait…”);
pDialog.setIndeterminate(false);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(true);
pDialog.show();
break;

default:
break;
}
}

to stop progress dialog :

@Override
public void onTaskComplete(String result) {
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
pDialog.dismiss();
}

To show Progress on Percentage :

@Override
public void onProgressUpdate(Integer progress) {
pDialog.setProgress(progress);
}

Response after execution :

“implements AsyncTaskCompleteListener” .to get response.

Ex.

@Override
public void onTaskComplete(String result) {
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
pDialog.dismiss();
}

@Override
public void onProgressUpdate(Integer progress) {
pDialog.setProgress(progress);
}

Finally Convert result String to java Object.

Ex.It can be list or object.

List<Response> list = ServiceCall.getResponse(result, Login.class);

Response  response = ServiceCall.getResponse(result, Login.class);

Open your AndroidManifest.xml file and add internet connect permission and writing to sdcard permission.

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

DownLoad Link : https://github.com/Sabinash/GenericAsyncLib

Advertisements

Different Images with Different text In Android ListView(Part Two)

Let’s get start by creating a project in Android ADT.

1. Create a new project by going to File ⇒ New Android Application. Fill all the details  As Application Name:DifferentIconListView,Project Name:DifferentIconListView,Package Name:com.Test.differenticonlistview  and click on Next button to finish .

2 .Once the project is created open your activity_main.xml (res/layout) and paste the following code.

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

<ListView
android:id=”@+id/list”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
/>
</LinearLayout>

Create another layout under under res/layout as row.xml.

<?xml version=”1.0″ encoding=”utf-8″?>
<RelativeLayout xmlns:android=”http://schemas.android.com/apk/res/android&#8221;
xmlns:tools=”http://schemas.android.com/tools&#8221;
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
tools:ignore=”SpUsage,HardcodedText” >

<ImageView
android:id=”@+id/icon”
android:layout_width=”80dp”
android:layout_height=”80dp”
android:contentDescription=”image”
android:paddingLeft=”10dp”
android:paddingRight=”10dp” />

<TextView
android:id=”@+id/title”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_toRightOf=”@+id/icon”
android:paddingBottom=”10dp”
android:textColor=”#CC0033″
android:textSize=”16dp” />

<TextView
android:id=”@+id/desc”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_below=”@+id/title”
android:layout_toRightOf=”@+id/icon”
android:paddingLeft=”10dp”
android:textColor=”#3399FF”
android:textSize=”14dp” />

</RelativeLayout>

3.Open MainActivity.java class and paste following code.

package com.Test.differenticonlistview ;

import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends Activity implements
OnItemClickListener {

public static final String[] titles = new String[] { “Sunday”,
“Monday”, “Tuseday”, “Thursday”,”Friday”,”Satday” };

public static final String[] descriptions = new String[] {
“Today is Sunday”,
“Today is Monday”, “Today is Tuseday”,
“Today is Thursday”,”Today is Friday”,”Today is Satday” };

public static final Integer[] images = { R.drawable.icon_add,
R.drawable.ic_launcher, R.drawable.icon_add, R.drawable.ic_launcher,R.drawable.icon_add,R.drawable.ic_launcher };

ListView listView;
List<RowItem> rowItems;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

rowItems = new ArrayList<RowItem>();
for (int i = 0; i < titles.length; i++) {

RowItem item = new RowItem(images[i], titles[i], descriptions[i]);
rowItems.add(item);
}

listView = (ListView) findViewById(R.id.list);
MySimpleArrayAdapter adapter = new MySimpleArrayAdapter(this,
R.layout.row, rowItems);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
}

@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Toast toast = Toast.makeText(getApplicationContext(),
“Item ” + (position + 1) + “: ” + rowItems.get(position),
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
}
}

4.Create a MyPerformanceArrayAdapter.java class and paste following code.

Here we are creating our own adapter class by simply extending this class to ArrayAdapter.

package com.Test.differenticonlistview;

import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class MySimpleArrayAdapter extends ArrayAdapter<RowItem> {

Context context;
List<RowItem> items;

public MySimpleArrayAdapter(Context context, int resourceId,
List<RowItem> items) {
super(context, resourceId, items);
this.context = context;
this.items = items;
}

public View getView(int position, View convertView, ViewGroup parent) {

RowItem rowItem = getItem(position);

LayoutInflater inflater = ((Activity) context).getLayoutInflater();
convertView = inflater.inflate(R.layout.row, null);
TextView   txtDesc = (TextView) convertView.findViewById(R.id.desc);
TextView   txtTitle = (TextView) convertView.findViewById(R.id.title);
ImageView imageView = (ImageView) convertView.findViewById(R.id.icon);

txtDesc.setText(rowItem.getDesc());
txtTitle.setText(rowItem.getTitle());
imageView.setImageResource(rowItem.getImageId());

return convertView;
}
}

5. Creat a RowItem.class and paste following code .

package com.Test.differenticonlistview;

public class RowItem {

private int imageId;
private String title;
private String desc;

public RowItem(int imageId, String title, String desc) {
this.imageId = imageId;
this.title = title;
this.desc = desc;
}
public int getImageId() {
return imageId;
}
public void setImageId(int imageId) {
this.imageId = imageId;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
@Override
public String toString() {
return title + “\n” + desc;
}

}

6.Finally run your project by right clicking on your project folder ⇒ Run As ⇒ 1 Android Application.

2013-07-24_19-30-38

 

 

Different Images with Different text In Android ListView(Part One)

Let’s get start by creating a project in Android ADT.

1. Create a new project by going to File ⇒ New Android Application. Fill all the details  As Application Name:DifferentIconListView,Project Name:DifferentIconListView,Package Name:com.Test.differenticonlistview  and click on Next button to finish .

2 .Once the project is created open your activity_main.xml (res/layout) and paste the following code.

<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android&#8221;
xmlns:tools=”http://schemas.android.com/tools&#8221;
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
tools:ignore=”InefficientWeight” >

<ListView
android:id=”@+id/listView1″
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:layout_weight=”1″ >
</ListView>

</LinearLayout>

3.Open MainActivity.java class and paste following code.

package com.Test.differenticonlistview;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;

public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

ListView listView = (ListView) findViewById(R.id.listView1);

String[] values = new String[] { “Sunday”, “Monday”, “Tuseday”,
“Wednessday”, “Thursday”, “Friday”, “Satday” };

MyPerformanceArrayAdapter adapter = new MyPerformanceArrayAdapter(this,
values);
listView.setAdapter(adapter);

}
}

3.Create a MyPerformanceArrayAdapter.java class and paste following code.

Here we are creating our own adapter class by simply extending this class to ArrayAdapter.

package com.Test.differenticonlistview;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class MyPerformanceArrayAdapter extends ArrayAdapter<String>{

Activity context;
String[] values;

public MyPerformanceArrayAdapter(Activity context, String[] values) {
// TODO Auto-generated constructor stub

super(context, R.layout.activity_main,values);
this.context = context;
this.values = values;
}

public View getView(int position,View view,ViewGroup parent){

LayoutInflater inflater = context.getLayoutInflater();
view= inflater.inflate(R.layout.row, null);

TextView textView = (TextView)view.findViewById(R.id.title);
ImageView imageView = (ImageView)view.findViewById(R.id.icon);

String s = values[position];
textView.setText(s);
if (s.startsWith(“Sunday”) || s.startsWith(“Thursday”)
|| s.startsWith(“Satday”)) {
imageView.setImageResource(R.drawable.ic_launcher);
} else {
imageView.setImageResource(R.drawable.icon_add);
}

return view;

}

}

Here need to create another layout under res/layout as row.xml.   

<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android&#8221;
xmlns:tools=”http://schemas.android.com/tools&#8221;
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
android:orientation=”horizontal”
tools:ignore=”UseCompoundDrawables,HardcodedText,ContentDescription” >

<ImageView
android:id=”@+id/icon”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:src=”@drawable/ic_launcher” />

<TextView
android:id=”@+id/title”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_marginTop=”17dp”
android:text=”TextView” />

</LinearLayout>

5. Finally run your project by right clicking on your project folder ⇒ Run As ⇒ 1 Android Application.

2013-07-24_18-49-55

How to Create a ListView with Same Image icon but Different text in each row in Android

Let’s get start by creating a project in Android ADT.

1. Create a new project by going to File ⇒ New Android Application. Fill all the details  As Application Name:SameIconsListView,Project Name:SameIconsListView,Package Name:com.test.sameiconslistview  and click on Next button to finish .

2 .Once the project is created open your activity_main.xml (res/layout) and paste the following code.

<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android&#8221;
xmlns:tools=”http://schemas.android.com/tools&#8221;
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
tools:ignore=”InefficientWeight” >

<ListView
android:id=”@+id/listView1″
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:layout_weight=”1″ >
</ListView>

</LinearLayout>

  • Create another xml under res/layout as row.xml.

<?xml version=”1.0″ encoding=”utf-8″?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android&#8221;
xmlns:tools=”http://schemas.android.com/tools&#8221;
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:orientation=”horizontal”
tools:ignore=”UseCompoundDrawables,HardcodedText,ContentDescription” >

<ImageView
android:id=”@+id/imageView1″
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:src=”@drawable/ic_launcher” />

<TextView
android:id=”@+id/textView1″
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”TextView”
android:layout_marginTop=”17dp”/>

</LinearLayout>

3.Open MainActivity.java class and paste following code.

package com.test.sameiconslistview;

import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends Activity {

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

ListView listView = (ListView) findViewById(R.id.listView1);
String[] items = new String[] { “sunday”, “monaday”, “tuesday”,
“wednesday”, “thrusday”, “friday”, “saturday” };

final ArrayAdapter<String> adapter = new ArrayAdapter<String>(
getApplicationContext(), R.layout.row, R.id.textView1, items);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
// ListView Clicked item value

String filename = adapter.getItem(position).toString();

Toast.makeText(
getApplicationContext(),
“Slected File=” + filename + “;”
+ ” Selected Position=” + position,
Toast.LENGTH_LONG).show();

}
});

}

}
4. Finally run your project by right clicking on your project folder ⇒ Run As ⇒ 1 Android Application.

listwithicon listwithicon

 

 

 

Simple ListView without using android layout

1. Create a new project by going to File ⇒ New Android Application. Fill all the details  As Application Name:SimpleListView,Project Name:SimpleListView,Package Name:com.test.simplelistview  and click on Next button to finish .

2.Open MainActivity.java class and paste following code.

import android.os.Bundle;
import android.app.ListActivity;
import android.content.Intent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends ListActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

String[] items=new String[] {“sunday”,”monaday”,”tuesday”,”wednesday”,”thrusday”,”friday”,”saturday”};

final ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item_1,items);

setListAdapter(adapter);

ListView listView = getListView();

listView.setOnItemClickListener(new OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub

String filename = adapter.getItem(position).toString();

// ListView Clicked item value

//   String  filename= (String) listView.getItemAtPosition(position);
//   remove final from ArrayAdapter to use.

Toast.makeText(getApplicationContext(), “Slected File=” + filename+”;”+ ” Selected Position=”+position, Toast.LENGTH_LONG).show();
}
});
}

}

3. Finally run your project by right clicking on your project folder ⇒ Run As ⇒ 1 Android Application.

ListViewListView