Learn Python


Click to Learn Python3
Showing posts with label listview. Show all posts
Showing posts with label listview. Show all posts

Friday, September 23, 2011

Image and content is populated from Sqlite in Android

In this below application we had populated the listview's data and image from the sqlite



Here we are using a java class for creating the table


PlaceDataSQL.java
package com.data.pack;

package com.data.pack;

import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

/** Helper to the database, manages versions and creation */
public class PlaceDataSQL extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "sample.db";
private static final int DATABASE_VERSION = 1;

private Context context;

public PlaceDataSQL(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
}

@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE gallery (id varchar(20), image BLOB,caption varchar(160),description varchar(200))");
}

private void versionUpdation(SQLiteDatabase db) {

}

/**
* Check if the database already exist to avoid re-copying the file each
* time you open the application.
*
* @return true if it exists, false if it doesn't
*/
public boolean checkDataBase(String db) {

SQLiteDatabase checkDB = null;

try {
String myPath = "data/data/com.data.pack/databases/" + db;
checkDB = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);

} catch (SQLiteException e) {

// database does't exist yet.

} catch (Exception e) {

}

if (checkDB != null) {

checkDB.close();

}

return checkDB != null ? true : false;
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion >= newVersion)
return;

if (oldVersion == 1) {
Log.d("New Version", "Datas can be upgraded");
}

Log.d("Sample Data", "onUpgrade : " + newVersion);
}

}



Here in the onCreate function the table is created, here for image we are using blog, so that we can insert the image inside the table itself and the onUpgrade function is used to upgrade the table on the next release, for example you had create an application and published it in market and a guy is using your application, now suddenly you like to add another field on your table means you need to change the " DATABASE_VERSION " to 2 and in the onUpgrade funtion you need to write the alter query there. Likewise i had using a funtion checkDataBase(), this is to check whether the database is exist or not.

Then in the main activity we are calling delete to delete the table content, likewise we will be using a function insertData, inside this function we will be inserting data to the table, like that we will be using getDataAndPopulate(), here we will be retrieving data from the table and displaying in the list.

The main thing is we inserting the image to database for this we are using HttpClient and on the retriving time it is very easy to assign the data, so while calling on the next time we can assign and there is no need of url call for showing image.


SqliteDBActivity.java
package com.data.pack;


package com.data.pack;


import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.app.ListActivity;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class SqliteDBActivity extends ListActivity {
private static PlaceDataSQL placeData;
private ArrayList id = new ArrayList();
private ArrayList image = new ArrayList();
private ArrayList caption = new ArrayList();
private ArrayList description = new ArrayList();
private Button populate;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
populate = (Button) findViewById(R.id.populate);
placeData = new PlaceDataSQL(this);

SQLiteDatabase db = placeData.getWritableDatabase();

Cursor cursors = getRawEvents("select * from gallery");

if (cursors.moveToNext()) {
populate.setVisibility(View.GONE);
getDataAndPopulate();
} else {
populate.setVisibility(View.VISIBLE);
}


db.delete("gallery", "id=?", new String[] {
"12" });
populate.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
try {
callInsertion("1","https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjXQTlp6hJ5voBMw9WxJFAFUGW_kUzEeBdoHuRFMkEn8j-mYxrDDmoBizU3Seo1P0BxPre5g2i2JUZi1UpaISGq00rp-h1apLEUxMzVl8WHWQWiZUzhiFRyA63wsvq2tMsN2Ze5LbmhaPk/s1600/twitter_follow.gif","First","This is the first item");
callInsertion("2","https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi6KGi-xGVQybCuzpxCAGMXIKz91RSKaLSCEhUF_yDtzNolI6jAfls0nh_xLEB9wJw0kExxZs0FgRHjxFU2Vm4EDzoFWebBinKNFvi8lc_xhpToMInmiOG71ER8jTSEFySuQ_u1lHgbW6I/s320/seek.JPG","Second","This is the second item");
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

getDataAndPopulate();
}
});

}

private void callInsertion(String id, String url, String caption, String description) throws ClientProtocolException, IOException {
DefaultHttpClient mHttpClient = new DefaultHttpClient();
HttpGet mHttpGet = new HttpGet(url);
HttpResponse mHttpResponse = mHttpClient.execute(mHttpGet);
if (mHttpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity entity = mHttpResponse.getEntity();
if ( entity != null) {
// insert to database
insertData(id,EntityUtils.toByteArray(entity),caption,description);
}
}
}

private void insertData(String id, byte[] image, String caption, String description) {
SQLiteDatabase db = placeData.getWritableDatabase();
ContentValues values;
values = new ContentValues();
values.put("id", id);
values.put("image", image);
values.put("caption", caption);
values.put("description", description);

db.insert("gallery", null, values);
}

private void getDataAndPopulate() {
id = new ArrayList();
image = new ArrayList();
caption = new ArrayList();
description = new ArrayList();
Cursor cursor = getEvents("gallery");
while (cursor.moveToNext()) {
String temp_id = cursor.getString(0);
byte[] temp_image = cursor.getBlob(1);
String temp_caption = cursor.getString(2);
String temp_description = cursor.getString(3);
id.add(temp_id);
image.add(temp_image);
caption.add(temp_caption);
description.add(temp_description);
}
String[] captionArray = (String[]) caption.toArray(
new String[caption.size()]);

ItemsAdapter itemsAdapter = new ItemsAdapter(
SqliteDBActivity.this, R.layout.item,
captionArray);
setListAdapter(itemsAdapter);
populate.setVisibility(View.GONE);
}


private class ItemsAdapter extends BaseAdapter {
String[] items;

public ItemsAdapter(Context context, int textViewResourceId,
String[] items) {
this.items = items;
}

@Override
public View getView(final int POSITION, View convertView,
ViewGroup parent) {
TextView desc;
TextView cap;
View view = convertView;
ImageView img;
if (view == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(R.layout.item, null);

}
img = (ImageView) view.findViewById(R.id.image);
cap = (TextView) view.findViewById(R.id.caption);

desc = (TextView) view.findViewById(R.id.description);

cap.setText(caption.get(POSITION));
desc.setText(description.get(POSITION));
img.setImageBitmap(BitmapFactory.decodeByteArray(image.get(POSITION), 0, image.get(POSITION).length));


return view;
}

public int getCount() {
return items.length;
}

public Object getItem(int position) {
return position;
}

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

private Cursor getRawEvents(String sql) {
SQLiteDatabase db = (placeData).getReadableDatabase();
Cursor cursor = db.rawQuery(sql, null);

startManagingCursor(cursor);
return cursor;
}

private Cursor getEvents(String table) {
SQLiteDatabase db = (placeData).getReadableDatabase();
Cursor cursor = db.query(table, null, null, null, null, null, null);

startManagingCursor(cursor);
return cursor;
}
}


In this example i had wrote two types of retrieving methods from the table, by writing the query and specifying the table name itself.

You can download the full source code


Download source


Have a good day.

Monday, September 19, 2011

Using Sqlite to populate a ListView in Android

In this below application we had populated the listview using the data from the sqlite



Here we are using a java class for creating the table


PlaceDataSQL.java
package com.data.pack;

import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

/** Helper to the database, manages versions and creation */
public class PlaceDataSQL extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "sample.db";
private static final int DATABASE_VERSION = 1;

private Context context;

public PlaceDataSQL(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
}

@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE gallery (id varchar(20), image varchar(2000),caption varchar(160),description varchar(200))");
}

private void versionUpdation(SQLiteDatabase db) {

}

/**
* Check if the database already exist to avoid re-copying the file each
* time you open the application.
*
* @return true if it exists, false if it doesn't
*/
public boolean checkDataBase(String db) {

SQLiteDatabase checkDB = null;

try {
String myPath = "data/data/com.data.pack/databases/" + db;
checkDB = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);

} catch (SQLiteException e) {

// database does't exist yet.

} catch (Exception e) {

}

if (checkDB != null) {

checkDB.close();

}

return checkDB != null ? true : false;
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion >= newVersion)
return;

if (oldVersion == 1) {
Log.d("New Version", "Datas can be upgraded");
}

Log.d("Sample Data", "onUpgrade : " + newVersion);
}

}


Here in the onCreate function the table is created and the onUpgrade function is used to upgrade the table on the next release, for example you had create an application and published it in market and a guy is using your application, now suddenly you like to add another field on your table means you need to change the " DATABASE_VERSION " to 2 and in the onUpgrade funtion you need to write the alter query there. Likewise i had using a funtion checkDataBase(), this is to check whether the database is exist or not.

Then in the main activity we are calling delete to delete the table content, likewise we will be using a function insertData, inside this function we will be inserting data to the table, like that we will be using getDataAndPopulate(), here we will be retrieving data from the table and displaying in the list.



SqliteDBActivity.java
package com.data.pack;


import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import android.app.ListActivity;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class SqliteDBActivity extends ListActivity {
private static PlaceDataSQL placeData;
private ArrayList id = new ArrayList();
private ArrayList image = new ArrayList();
private ArrayList caption = new ArrayList();
private ArrayList description = new ArrayList();
private Button populate;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
populate = (Button) findViewById(R.id.populate);
placeData = new PlaceDataSQL(this);

SQLiteDatabase db = placeData.getWritableDatabase();

Cursor cursors = getRawEvents("select * from gallery");

if (cursors.moveToNext()) {
populate.setVisibility(View.GONE);
getDataAndPopulate();
} else {
populate.setVisibility(View.VISIBLE);
}


db.delete("gallery", "id=?", new String[] {
"12" });
populate.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
insertData("1","https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjXQTlp6hJ5voBMw9WxJFAFUGW_kUzEeBdoHuRFMkEn8j-mYxrDDmoBizU3Seo1P0BxPre5g2i2JUZi1UpaISGq00rp-h1apLEUxMzVl8WHWQWiZUzhiFRyA63wsvq2tMsN2Ze5LbmhaPk/s1600/twitter_follow.gif","First","This is the first item");
insertData("2","https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi6KGi-xGVQybCuzpxCAGMXIKz91RSKaLSCEhUF_yDtzNolI6jAfls0nh_xLEB9wJw0kExxZs0FgRHjxFU2Vm4EDzoFWebBinKNFvi8lc_xhpToMInmiOG71ER8jTSEFySuQ_u1lHgbW6I/s320/seek.JPG","Second","This is the second item");
getDataAndPopulate();
}
});

}

private void insertData(String id, String image, String caption, String description) {
SQLiteDatabase db = placeData.getWritableDatabase();
ContentValues values;
values = new ContentValues();
values.put("id", id);
values.put("image", image);
values.put("caption", caption);
values.put("description", description);

db.insert("gallery", null, values);
}

private void getDataAndPopulate() {
id = new ArrayList();
image = new ArrayList();
caption = new ArrayList();
description = new ArrayList();
Cursor cursor = getEvents("gallery");
while (cursor.moveToNext()) {
String temp_id = cursor.getString(0);
String temp_image = cursor.getString(1);
String temp_caption = cursor.getString(2);
String temp_description = cursor.getString(3);
id.add(temp_id);
image.add(temp_image);
caption.add(temp_caption);
description.add(temp_description);
}
String[] captionArray = (String[]) caption.toArray(
new String[caption.size()]);

ItemsAdapter itemsAdapter = new ItemsAdapter(
SqliteDBActivity.this, R.layout.item,
captionArray);
setListAdapter(itemsAdapter);
populate.setVisibility(View.GONE);
}


private class ItemsAdapter extends BaseAdapter {
String[] items;

public ItemsAdapter(Context context, int textViewResourceId,
String[] items) {
this.items = items;
}

@Override
public View getView(final int POSITION, View convertView,
ViewGroup parent) {
TextView desc;
TextView cap;
View view = convertView;
ImageView img;
if (view == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(R.layout.item, null);

}
img = (ImageView) view.findViewById(R.id.image);
cap = (TextView) view.findViewById(R.id.caption);

desc = (TextView) view.findViewById(R.id.description);

cap.setText(caption.get(POSITION));
desc.setText(description.get(POSITION));
try {
URL url = new URL(image.get(POSITION));
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
BitmapFactory.Options bfOptions = new BitmapFactory.Options();
bfOptions.inDither = false; // Disable Dithering
// mode
bfOptions.inPurgeable = true; // Tell to gc that
// whether it needs
// free memory, the
// Bitmap can be
// cleared
bfOptions.inInputShareable = true; // Which kind of
// reference
// will be used
// to recover
// the Bitmap
// data after
// being clear,
// when it will
// be used in
// the future
bfOptions.inTempStorage = new byte[16 * 1024];
Bitmap bmp = null;
bmp = BitmapFactory.decodeStream(input, null,
bfOptions);
img.setImageBitmap(bmp);
connection.disconnect();
input.close();

} catch (MalformedURLException e) {
} catch (IOException e) {
} catch (IllegalAccessError e) {
} catch (NullPointerException e) {
}

return view;
}

public int getCount() {
return items.length;
}

public Object getItem(int position) {
return position;
}

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

private Cursor getRawEvents(String sql) {
SQLiteDatabase db = (placeData).getReadableDatabase();
Cursor cursor = db.rawQuery(sql, null);

startManagingCursor(cursor);
return cursor;
}

private Cursor getEvents(String table) {
SQLiteDatabase db = (placeData).getReadableDatabase();
Cursor cursor = db.query(table, null, null, null, null, null, null);

startManagingCursor(cursor);
return cursor;
}
}


In this example i had wrote two types of retrieving methods from the table, by writing the query and specifying the table name itself.

You can download the full source code


Download source


Have a good day.

Wednesday, March 23, 2011

Customized ListView item's selection color can be changed on touching or selecting the item in the list

On selection, on focus, on touch of the items we can change the color of the item, by default android will show a color, we can change it as we like. For that we need this xml to be stored inside the color folder, here only we need mention the colors for each listeners




list_bg.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_selected="false"
android:state_pressed="false"
android:drawable="@color/grey" />
<item android:state_pressed="true"
android:drawable="@color/blue" />
<item android:state_selected="true"
android:state_pressed="false"
android:drawable="@color/blue" />
</selector>



That list_bg.xml will be called in the customized list xml as background


list.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:layout_margin="2dp" android:background="@color/list_bg">

<TextView android:id="@+id/post" android:gravity="center_vertical"
android:layout_width="wrap_content" android:layout_height="50dp"
android:textSize="20sp" android:textColor="#D0640D"
android:layout_toRightOf="@+id/bite_image" />

</RelativeLayout>


This one is the main xml for the Lister.java


main.xml

<?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">

<ListView android:id="@android:id/list" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:smoothScrollbar="true"
android:background="#fff" android:cacheColorHint="#fff"
android:fastScrollEnabled="false" android:clickable="true"
android:layout_marginBottom="36dp" />

</LinearLayout>



The Lister.java will be like this, the main thing is the list_bg.xml only


Lister.java

package com.list.viewer;

import android.app.ListActivity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class Lister extends ListActivity{

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String[] captionArray = { "USA","India","England","Russia","Europe","Canada","Srilanka","Singapore","Thailand","Australia"};
ItemsAdapter ItemsAdapter = new ItemsAdapter(
Lister.this, R.layout.list,
captionArray);
setListAdapter(ItemsAdapter);
}


private class ItemsAdapter extends BaseAdapter {
String[] items;

public ItemsAdapter(Context context, int textViewResourceId,
String[] items) {
// super(context, textViewResourceId, items);
this.items = items;
}

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

View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.list, null);
}
TextView post = (TextView) v
.findViewById(R.id.post);
post.setText(items[position]);

return v;
}

public int getCount() {
return items.length;
}

public Object getItem(int position) {
return position;
}

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





The full source code

Download source


Have a good day.

Monday, March 21, 2011

Multiple ListView and custom listview example with click listener functions

Multiple listview can be placed inside a Activity. Here i am having two listviews



As shown in the above image, the left side displaying list view is customized listview, it that listview we will be showing a imageview and a textview, On clicking the item of that listview, the second listview will be generated.

The xml layout for that page will be like this


main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent" android:gravity="center"
android:layout_height="fill_parent" android:background="#cccccc">
<TextView android:layout_width="fill_parent" android:textColor="#000"
android:layout_height="wrap_content" android:text="Multiple ListView Example" />
<LinearLayout android:orientation="horizontal" android:layout_marginTop="10dp" android:gravity="center_horizontal"
android:layout_width="fill_parent" android:layout_height="wrap_content">
<ListView android:id="@+id/ListView1" android:layout_width="130dp"
android:background="#fff" android:cacheColorHint="#fff"
android:layout_height="wrap_content" />
<TextView android:text="==>" android:layout_height="wrap_content" android:textColor="#000"
android:layout_width="wrap_content"></TextView>
<ListView android:id="@+id/ListView2" android:layout_width="130dp"
android:background="#4c6f7e" android:cacheColorHint="#4c6f7e"
android:layout_height="wrap_content" />
</LinearLayout>

</LinearLayout>


For the customized listview the coding will be like this, it will show the customized listview with a imageview and textview for each item


Java

private String[] list1 = {"Icon", "Icon Creator", "Image", "Image Creator"};
private ListView lister1;
lister1=(ListView)findViewById(R.id.ListView1);
ItemsAdapter itemsAdapter = new ItemsAdapter(
ListViewExample.this, R.layout.list,
list1);
lister1.setAdapter(itemsAdapter);


In the above example we need to explicitly use a layout, the layout will be


list.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="100dp"
android:layout_height="fill_parent"
>
<ImageView
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:src="@drawable/icon" android:id="@+id/image"/>
<TextView android:textColor="#000"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="" android:id="@+id/desc"
/>
</LinearLayout>



For the second listview, is normal listview, which is used with the pre defined layout android.R.layout.simple_list_item_1

The full ListViewExample.java file will be like this


ListViewExample.java

package com.list.viewer;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

/** http://www.android-codes-examples.blogspot.com/ */
public class ListViewExample extends Activity {

private String[] list1 = { "Icon", "Icon Creator", "Image", "Image Creator" };
private String[] list21 = { "Design", "Creation", "Selection", "Caller" };
private String[] list22 = { "Investor", "Producer", "Controller",
"Publisher" };
private String[] list23 = { "Designer", "Maker", "Creator", "Asignment" };
private String[] list24 = { "Arranger", "Caller", "Solution", "Result" };

private ListView lister1;
private ListView lister2;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lister1 = (ListView) findViewById(R.id.ListView1);
lister2 = (ListView) findViewById(R.id.ListView2);
ItemsAdapter itemsAdapter = new ItemsAdapter(ListViewExample.this,
R.layout.list, list1);
lister1.setAdapter(itemsAdapter);
lister2.setAdapter(new ArrayAdapter(ListViewExample.this,
android.R.layout.simple_list_item_1, list21));
lister1.setOnItemClickListener(new OnItemClickListener() {

@Override
public void onItemClick(AdapterView arg0, View arg1,
int positon, long arg3) {
String[] lister = null;
switch (positon) {
case 0:
lister = list21;
break;
case 1:
lister = list22;
break;
case 2:
lister = list23;
break;
case 3:
lister = list24;
break;
default:
lister = list21;
}
lister2.setAdapter(new ArrayAdapter(
ListViewExample.this,
android.R.layout.simple_list_item_1, lister));
}
});
}

private class ItemsAdapter extends BaseAdapter {
String[] items;

public ItemsAdapter(Context context, int textViewResourceId,
String[] items) {
this.items = items;
}

@Override
public View getView(final int position, View convertView,
ViewGroup parent) {
TextView mDescription;
View view = convertView;
ImageView image;
if (view == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(R.layout.list, null);
}
image = (ImageView) view.findViewById(R.id.image);
mDescription = (TextView) view.findViewById(R.id.desc);
mDescription.setText(items[position]);
image.setBackgroundResource(R.id.image);
return view;
}

public int getCount() {
return items.length;
}

public Object getItem(int position) {
return position;
}

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




The full source code

Download source


Have a good day.