Unable to load images from the URL - android

public class MyFragment extends Fragment {
int mCurrentPage;
Context c;
GridView mListView;
String id, cat;
String strUrl;
TextView tvtitle;
TextView tv_id, tv_rating, tv_url;
public static String img_url, img_rating, img_id, img_name;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle data = getArguments();
mCurrentPage = data.getInt("current_page", 0);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = null;
DownloadTask downloadTask = new DownloadTask();
v = inflater.inflate(R.layout.starters, container, false);
tv_id = (TextView) v.findViewById(R.id.tv_starter_hide_id);
tv_rating = (TextView) v.findViewById(R.id.tv_starter_hide_ratinf);
tv_url = (TextView) v.findViewById(R.id.tv_starter_hide_url);
cat = Category.Main_Cat;
Log.i("Logcat Cat1", cat);
switch (mCurrentPage) {
case 1:
Log.v("MyFragment Heap", "Max Mem in MB:"
+ (Runtime.getRuntime().maxMemory() / 1024 / 1024));
// strUrl =
// "http://vaibhavtech.com/work/android/get_json.php?cat="+cat+"&subcat=1";
strUrl = " http://vaibhavtech.com/work/android/movie_list.php?category=BollyWood%20&sub_category=top";
downloadTask.execute(strUrl);
mListView = (GridView) v.findViewById(R.id.lv_countries);
mListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
Intent i = new Intent(getActivity().getBaseContext(),
Starter_info.class);
img_id = ((TextView) arg1
.findViewById(R.id.tv_starter_hide_id)).getText()
.toString();
img_rating = ((TextView) arg1
.findViewById(R.id.tv_starter_hide_ratinf))
.getText().toString();
img_url = ((TextView) arg1
.findViewById(R.id.tv_starter_hide_url)).getText()
.toString();
img_name = ((TextView) arg1
.findViewById(R.id.tv_starter_hide_imagename))
.getText().toString();
startActivity(i);
}
});
break;
case 2:
// strUrl =
// "http://vaibhavtech.com/work/android/get_json.php?cat="+cat+"&subcat=1";
strUrl = " http://vaibhavtech.com/work/android/movie_list.php?category=BollyWood%20&sub_category=top";
downloadTask.execute(strUrl);
Log.v("Splash Heap", "Max Mem in MB:"
+ (Runtime.getRuntime().maxMemory() / 1024 / 1024));
mListView = (GridView) v.findViewById(R.id.lv_countries);
mListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
Intent i = new Intent(getActivity().getBaseContext(),
Starter_info.class);
img_id = ((TextView) arg1
.findViewById(R.id.tv_starter_hide_id)).getText()
.toString();
img_rating = ((TextView) arg1
.findViewById(R.id.tv_starter_hide_ratinf))
.getText().toString();
img_url = ((TextView) arg1
.findViewById(R.id.tv_starter_hide_url)).getText()
.toString();
img_name = ((TextView) arg1
.findViewById(R.id.tv_starter_hide_imagename))
.getText().toString();
startActivity(i);
}
});
break;
default:
Log.i("Cat IS", Category.Main_Cat);
// strUrl =
// "http://vaibhavtech.com/work/android/get_json.php?cat="+cat+"&subcat=1";
strUrl = " http://vaibhavtech.com/work/android/movie_list.php?category=BollyWood%20&sub_category=top";
downloadTask.execute(strUrl);
Log.v("Splash Heap", "Max Mem in MB:"
+ (Runtime.getRuntime().maxMemory() / 1024 / 1024));
mListView = (GridView) v.findViewById(R.id.lv_countries);
mListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
Intent i = new Intent(getActivity().getBaseContext(),
Starter_info.class);
img_id = ((TextView) arg1
.findViewById(R.id.tv_starter_hide_id)).getText()
.toString();
img_rating = ((TextView) arg1
.findViewById(R.id.tv_starter_hide_ratinf))
.getText().toString();
img_url = ((TextView) arg1
.findViewById(R.id.tv_starter_hide_url)).getText()
.toString();
img_name = ((TextView) arg1
.findViewById(R.id.tv_starter_hide_imagename))
.getText().toString();
startActivity(i);
}
});
break;
}
return v;
}
private String downloadUrl(String strUrl) throws IOException {
String data = "";
InputStream iStream = null;
try {
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(
iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
br.close();
} catch (Exception e) {
Log.d("Exception while downloading url", e.toString());
} finally {
iStream.close();
}
return data;
}
private class DownloadTask extends AsyncTask<String, Integer, String> {
String data = null;
#Override
protected String doInBackground(String... url) {
try {
data = downloadUrl(url[0]);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
#Override
protected void onPostExecute(String result) {
ListViewLoaderTask listViewLoaderTask = new ListViewLoaderTask();
listViewLoaderTask.execute(result);
}
}
private class ListViewLoaderTask extends
AsyncTask<String, Void, SimpleAdapter> {
JSONObject jObject;
#Override
protected SimpleAdapter doInBackground(String... strJson) {
try {
jObject = new JSONObject(strJson[0]);
StarterParser countryJsonParser = new StarterParser();
countryJsonParser.parse(jObject);
} catch (Exception e) {
Log.d("JSON Exception1", e.toString());
}
StarterParser countryJsonParser = new StarterParser();
List<HashMap<String, Object>> countries = null;
try {
// Getting the parsed data as a List construct
countries = countryJsonParser.parse(jObject);
} catch (Exception e) {
Log.d("Exception", e.toString());
}
String[] from = { "poster", "year", "duration", "id", "title" };
int[] to = { R.id.iv_flag, R.id.tv_starter_hide_url,
R.id.tv_starter_hide_ratinf, R.id.tv_starter_hide_id,
R.id.tv_starter_hide_imagename };
SimpleAdapter adapter = new SimpleAdapter(getActivity()
.getBaseContext(), countries, R.layout.lv_layout, from, to);
return adapter;
}
#Override
protected void onPostExecute(SimpleAdapter adapter) {
mListView.setAdapter(adapter);
ImageLoader imageLoader=new ImageLoader(getActivity());
for (int i = 0; i < adapter.getCount(); i++) {
HashMap<String, Object> hm = (HashMap<String, Object>) adapter
.getItem(i);
String imgUrl = (String) hm.get("flag_path");
ImageView posterImage=((ImageView)adapter.getView(i, null, null).findViewById(R.id.iv_flag));
imageLoader.DisplayImage(imgUrl, R.drawable.empty_photo, posterImage);
//ImageLoaderTask imageLoaderTask = new ImageLoaderTask();
HashMap<String, Object> hmDownload = new HashMap<String, Object>();
hm.put("flag_path", imgUrl);
hm.put("position", i);
// imageLoaderTask.execute(hm);*/
}
}
}
private class ImageLoaderTask extends
AsyncTask<HashMap<String, Object>, Void, HashMap<String, Object>> {
#Override
protected HashMap<String, Object> doInBackground(
HashMap<String, Object>... hm) {
InputStream iStream = null;
String imgUrl = (String) hm[0].get("flag_path");
int position = (Integer) hm[0].get("position");
URL url;
try {
url = new URL(imgUrl);
// Creating an http connection to communicate with url
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
// Getting Caching directory
File cacheDirectory = getActivity().getBaseContext()
.getCacheDir();
// Temporary file to store the downloaded image
File tmpFile = new File(cacheDirectory.getPath() + "/wpta_"
+ position + ".png");
// The FileOutputStream to the temporary file
FileOutputStream fOutStream = new FileOutputStream(tmpFile);
// Creating a bitmap from the downloaded inputstream
Bitmap b = BitmapFactory.decodeStream(iStream);
// Writing the bitmap to the temporary file as png file
b.compress(Bitmap.CompressFormat.PNG, 100, fOutStream);
// Flush the FileOutputStream
fOutStream.flush();
// Close the FileOutputStream
fOutStream.close();
// Create a hashmap object to store image path and its position
// in the listview
HashMap<String, Object> hmBitmap = new HashMap<String, Object>();
// Storing the path to the temporary image file
hmBitmap.put("flag", tmpFile.getPath());
// Storing the position of the image in the listview
hmBitmap.put("position", position);
// Returning the HashMap object containing the image path and
// position
return hmBitmap;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(HashMap<String, Object> result) {
// Getting the path to the downloaded image
String path = (String) result.get("flag");
// Getting the position of the downloaded image
int position = (Integer) result.get("position");
// Getting adapter of the listview
SimpleAdapter adapter = (SimpleAdapter) mListView.getAdapter();
// Getting the hashmap object at the specified position of the
// listview
HashMap<String, Object> hm = (HashMap<String, Object>) adapter
.getItem(position);
// Overwriting the existing path in the adapter
hm.put("flag", path);
// Noticing listview about the dataset changes
adapter.notifyDataSetChanged();
}
}
}
In my application
My images URL are showing in LogCat but unable to display the images and its temporary image is also not displaying. What should i do to make it work? Share your suggestion. thank you. :-)
1.Device image
2.Logcat image

I don't know why you writing your own code for downloading images,
https://github.com/nostra13/Android-Universal-Image-Loader
Here is library, It will download you images from url, assign them to imageviews, and will also cache images, When you demand for image in future, It will search in local cache and provide to your application without downloading again and again.

Related

Android Can't set image in a ListView layout

Looks like find the image but i don't know how to insert into the simple adapter (or anything that let me set the image in my layout)
https://gyazo.com/61ab064c19ae50090f08e6436776a52e
I want to set an image for each object in the array, like:
monsterimglist.setImageResource(R.mipmap.icon_name);
For the moment im testing to show R.mipmap.a1 in all the array items in the listview.
Error: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageResource(int)' on a null object reference
Someone can help me? Thanks a lot
ListView monsterslistview;
ImageView monsterimg;
TextView monstername;
TextView monstertype;
private static String monsterid;
ArrayList<HashMap<String, String>> MonstersList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_monsters);
//Fiquem els elements creats la seva id corresponent
monstername = (TextView) findViewById(R.id.namelayout);
monstertype = (TextView) findViewById(R.id.typelayout);
monsterslistview = (ListView) findViewById(R.id.monsterslistview);
monsterimg = (ImageView) findViewById(R.id.imglayout);
HashMap<String, String> hashMap;
//Creem un nou objecte ArrayList per inserir les dades
MonstersList = new ArrayList<HashMap<String, String>>();
//..........Process JSON DATA................
try {
JSONObject reader = new JSONObject(loadJSONFromAsset());
//Guardem a un Array de tipus JSON les dades
JSONArray jr = reader.getJSONArray("monsters");
for (int i = 0; i < jr.length(); i++) {
JSONObject jsonObjectLine = jr.getJSONObject(i);
// Desem els items JSON en una variable
String id = jsonObjectLine.getString("id");
String name = jsonObjectLine.getString("name");
String type = jsonObjectLine.getString("type");
String icon = jsonObjectLine.getString("icon");
//Toast.makeText(ListMonsters.this, id, Toast.LENGTH_LONG).show();
// Afegim la clau-valor a un objecte HashMap
hashMap = new HashMap<String, String>();
hashMap.put("id", id);
hashMap.put("name", name);
hashMap.put("type", type);
hashMap.put("icon", icon);
MonstersList.add(hashMap);
//mostrem per pantalla els elements que volem mostar
ListAdapter adapter = new SimpleAdapter(
ListMonsters.this,
MonstersList,
R.layout.onemonster,
new String[]{"name", "type","icon"},
new int[]{R.id.namelayout, R.id.typelayout, R.id.imglayout}
);
//Picasso.with(getApplicationContext()).load(R.mipmap.a1).into(monsterimglist);
monsterslistview.setAdapter(adapter);
//String idagafat = MonstersList.get(i).get("icon").replace(" ", "");
monsterimg.setImageResource(R.mipmap.a1);
monsterslistview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
/**
String idagafat = MonstersList.get(position).get("id").replace(" ", "");
String positionagafada = String.valueOf(position);
openmonster(idagafat, positionagafada);
**/
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
// FunciĆ³ llegir json
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = ListMonsters.this.getAssets().open("monsters.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
public void openmonster(String id, String pos){
int posarray = Integer.parseInt(pos);
Toast.makeText(ListMonsters.this, MonstersList.get(posarray).get("icon").replace(" ", ""), Toast.LENGTH_SHORT).show();
//Toast.makeText(ListMonsters.this, MonstersList.get(posarray).get("name").replace(" ", ""), Toast.LENGTH_SHORT).show();
//Toast.makeText(ListMonsters.this, MonstersList.get(posarray).get("type").replace(" ", ""), Toast.LENGTH_SHORT).show();
}
}
Close the Bracket before creating the adapter.May be it will change your result.
Updated :
ListView monsterslistview; ImageView monsterimg; TextView monstername; TextView monstertype;
private static String monsterid; ArrayList<HashMap<String, String>> MonstersList;
#Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_monsters);
//Fiquem els elements creats la seva id corresponent
monstername = (TextView) findViewById(R.id.namelayout);
monstertype = (TextView) findViewById(R.id.typelayout);
monsterslistview = (ListView) findViewById(R.id.monsterslistview);
monsterimg = (ImageView) findViewById(R.id.imglayout);
HashMap<String, String> hashMap;
//Creem un nou objecte ArrayList per inserir les dades
MonstersList = new ArrayList<HashMap<String, String>>();
//..........Process JSON DATA................
try {
JSONObject reader = new JSONObject(loadJSONFromAsset());
//Guardem a un Array de tipus JSON les dades
JSONArray jr = reader.getJSONArray("monsters");
for (int i = 0; i < jr.length(); i++) {
JSONObject jsonObjectLine = jr.getJSONObject(i);
// Desem els items JSON en una variable
String id = jsonObjectLine.getString("id");
String name = jsonObjectLine.getString("name");
String type = jsonObjectLine.getString("type");
String icon = jsonObjectLine.getString("icon");
//Toast.makeText(ListMonsters.this, id, Toast.LENGTH_LONG).show();
// Afegim la clau-valor a un objecte HashMap
hashMap = new HashMap<String, String>();
hashMap.put("id", id);
hashMap.put("name", name);
hashMap.put("type", type);
hashMap.put("icon", icon);
MonstersList.add(hashMap);
} //-----This Bracket was missed in your code
//mostrem per pantalla els elements que volem mostar
ListAdapter adapter = new SimpleAdapter(
ListMonsters.this,
MonstersList,
R.layout.onemonster,
new String[]{"name", "type","icon"},
new int[]{R.id.namelayout, R.id.typelayout, R.id.imglayout}
);
//Picasso.with(getApplicationContext()).load(R.mipmap.a1).into(monsterimglist);
monsterslistview.setAdapter(adapter);
//String idagafat = MonstersList.get(i).get("icon").replace(" ", "");
monsterimg.setImageResource(R.mipmap.a1);
monsterslistview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
/**
String idagafat = MonstersList.get(position).get("id").replace(" ", "");
String positionagafada = String.valueOf(position);
openmonster(idagafat, positionagafada);
**/
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
// FunciĆ³ llegir json public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = ListMonsters.this.getAssets().open("monsters.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json; }
public void openmonster(String id, String pos){
int posarray = Integer.parseInt(pos);
Toast.makeText(ListMonsters.this, MonstersList.get(posarray).get("icon").replace(" ", ""), Toast.LENGTH_SHORT).show();
//Toast.makeText(ListMonsters.this, MonstersList.get(posarray).get("name").replace(" ", ""), Toast.LENGTH_SHORT).show();
//Toast.makeText(ListMonsters.this, MonstersList.get(posarray).get("type").replace(" ", ""), Toast.LENGTH_SHORT).show(); }

how to show data that get from selected listview in another activity

i have an app where in a form show the list view. the user can click one of the list view and when clicking the app will move to another activity and it's activity will show some data based on "code" that sent from the list view form. my app is success to move in another activity but doesn't show the data. please help me.
Thank you.
This is my code in list view form :
final ListView lv = (ListView)findViewById(R.id.lv);
String url = "http://192.168.43.244/wewash/listview.php";
try {
JSONArray data = new JSONArray(getJSONUrl(url));
final ArrayList<HashMap<String, String>> MyArrList = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map;
for(int i = 0; i < data.length(); i++){
JSONObject c = data.getJSONObject(i);
map = new HashMap<String, String>();
map.put("nama", c.getString("nama"));
map.put("tanggal_keluar", c.getString("tanggal_keluar"));
MyArrList.add(map);
}
SimpleAdapter sAdap;
sAdap = new SimpleAdapter(halaman_utama.this, MyArrList, R.layout.listview,
new String[] {"nama", "tanggal_keluar","id", ""}, new int[] {R.id.tsnama, R.id.tstglk, R.id.kode, R.id.tsspasi});
lv.setAdapter(sAdap);
lv.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
String kode = ((TextView) findViewById(R.id.kode)).getText().toString();
Intent in = new Intent(halaman_utama.this, p_daftar_pakaian.class);
//menampilkan value dari item yg diklik
in.putExtra("id", kode);
startActivity(in);
}
});
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
and it's my code in new activity :
Intent intent = getIntent();
String kode = intent.getStringExtra("id");
String url = "http://192.168.43.244/wewash/listview_detail.php?id="+kode;
try {
JSONArray data = new JSONArray(getJSONUrl(url));
for(int i = 0; i < data.length(); i++){
JSONObject c = data.getJSONObject(i);
String idpk = c.getString("id");
String namapk = c.getString("nama");
String paketpk = c.getString("paket");
String cbiasapk = c.getString("cbiasa");
String ckhususpk = c.getString("ckhusus");
String tglantarpk = c.getString("tanggal_keluar");
String totalpk = c.getString("total");
// String nomorpk = c.getString("no_hp");
atasnama.setText(namapk);
ereview.setText("Id Pelanggan : " +idpk+
"\nNama Pelanggan : "+namapk+
"\nPaket : "+paketpk+
"\nCucian Biasa : "+cbiasapk+" kg"+
"\nCucian Khusus : "+ckhususpk+" item"+
"\nTotal : "+totalpk+" rupiah"+
"\nTanggal Antar : "+tglantarpk);
// enomer.setText(nomorpk);
}
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
and it's the php file
<?php
mysql_connect("localhost","root","");
mysql_select_db("wewash");
$kode=$_GET["id"];
$sql=mysql_query("select * from pakaian where id='$kode'");
$arrayId=array();
if($sql === FALSE) {
die(mysql_error());
}
while($row=mysql_fetch_array($sql)){
$arrayId["id"]=$row["id"];
$arrayId["nama"]=$row["nama"];
$arrayId["tanggal_keluar"]=$row["tanggal_keluar"];
$arrayId["paket"]=$row["paket"];
$arrayId["cbiasa"]=$row["cbiasa"];
$arrayId["ckhusus"]=$row["ckhusus"];
$arrayId["total"]=$row["total"];
}
echo json_encode($arrayId);
?>

ListView CustomAdapter getView is not calling

Below is my code, here i am getting response..
Fetching Data from server in josn
getRequest();
list = (ListView) findViewById(R.id.list);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
//
private void getRequest(){
Thread trd = new Thread(new Runnable() {
#Override
public void run() {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
//
try{
Log.d("Get top called","try block");
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
if(response!=null){
try{
HashMap<String, String> defaultSongsDetails;
songs = new JSONArray(response);
JSONObject jsonObject;
for(int i=0;i<songs.length();i++){
defaultSongsDetails = new HashMap<String, String>();
String title,artist,language,imageUrl,songUrl,vocalUrl,duration=null;
String sdCardPathOfImage,sdCardPathOfOriginalSong,sdCardPathOfVocalSong=null;
jsonObject = songs.getJSONObject(i);
title = jsonObject.getString(SONG_TITLE);
defaultSongsDetails.put("song_title",title);
artist = jsonObject.getString(SONG_ARTIST);
defaultSongsDetails.put("song_artist",artist);
language = jsonObject.getString(SONG_LANGUAGE);
defaultSongsDetails.put("song_language",language);
duration = jsonObject.getString(SONG_DURATION);
defaultSongsDetails.put("song_duration",duration);
imageUrl = jsonObject.getString(SONG_THUMBNAL);
songUrl = jsonObject.getString(SONG_DOWNLOAD_URL);
vocalUrl = jsonObject.getString(SONG_VOCAL_URL);
String thumbnail=null;
int cutImg = imageUrl.lastIndexOf('/');
if (cutImg != -1) {
thumbnail = imageUrl.substring(cutImg + 1);
}
sdCardPathOfImage = basepath + "/songs/" + thumbnail;
defaultSongsDetails.put("song_thumbnail", sdCardPathOfImage);
String fileName=null; int cut = songUrl.lastIndexOf('/'); if (cut != -1) { fileName = songUrl.substring(cut + 1); }
sdCardPathOfOriginalSong = basepath+"/songs/" + fileName;
defaultSongsDetails.put("song_original_path",
sdCardPathOfOriginalSong);
String vocalFileName=null; int cutVocal = songUrl.lastIndexOf('/'); if (cut != -1) { vocalFileName =
songUrl.substring(cutVocal + 1); } sdCardPathOfVocalSong =
basepath+"/songs/" + vocalFileName;
defaultSongsDetails.put("song_vocal_path", sdCardPathOfVocalSong);
//Adding Hashmap to ArrayList
defaultSongsDetailList.add(defaultSongsDetails);
adapter = new CustomList(JsonActivity.this,defaultSongsDetailList);
}catch (Exception e){ e.printStackTrace(); } } }catch (Exception e) { e.printStackTrace(); } }
}); trd.start();
}
//CustomList Adapter class
public class CustomList extends ArrayAdapter<HashMap<String, String>>{
private final Activity context;
private ArrayList<HashMap<String, String>> songList;
public CustomList(Activity context,
ArrayList<HashMap<String, String>> songList) {
super(context, R.layout.list_item_view, songList);
this.context = context;
this.songList = songList;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView= inflater.inflate(R.layout.list_item_view, null, true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.title);
ImageView imageView = (ImageView) rowView.findViewById(R.id.list_image);
TextView txtArtist = (TextView) rowView.findViewById(R.id.artist);
TextView txtDuration = (TextView) rowView.findViewById(R.id.duration);
System.out.println(" title ** "+songList.get(position).get("song_title")+" duration **
"+songList.get(position).get("song_duration")
+" thumb ** "+songList.get(position).get("song_thumbnail")+" language **
"+songList.get(position).get("song_language"));
txtArtist.setText(songList.get(position).get("song_title"));
txtDuration.setText(songList.get(position).get("song_duration"));
File file = new File(songList.get(position).get("song_thumbnail"));
Uri uri = Uri.fromFile(file);
imageView.setImageBitmap(BitmapFactory.decodeFile(defaultFilePath));
imageView.setImageURI(uri);
txtTitle.setText(songList.get(position).get("song_language"));
return rowView;
}
}
Any help would be appreciated...
//Fetching Data from server in josn
getRequest();
gAdapter = new BaseAdapter(HomeJsonActivity.this, defaultSongsDetailList);;
list = (ListView) findViewById(R.id.list);
gAdapter.notifyDataSetChanged();
list.setAdapter(gAdapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
private void getRequest() {
Thread trd = new Thread(new Runnable() {
#Override
public void run() {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
try {
Log.d("Get top called", "try block");
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
if (response != null) {
try {
HashMap<String, String> defaultSongsDetails;
songs = new JSONArray(response);
JSONObject jsonObject;
defaultSongsDetails = new HashMap<String, String>();
String title, artist, language, imageUrl, songUrl, vocalUrl, duration = null;
String sdCardPathOfImage, sdCardPathOfOriginalSong, sdCardPathOfVocalSong = null;
jsonObject = songs.getJSONObject(i);
title = jsonObject.getString(SONG_TITLE);
defaultSongsDetails.put("song_title", title);
artist = jsonObject.getString(SONG_ARTIST);
defaultSongsDetails.put("song_artist", artist);
language = jsonObject.getString(SONG_LANGUAGE);
defaultSongsDetails.put("song_language", language);
duration = jsonObject.getString(SONG_DURATION);
defaultSongsDetails.put("song_duration", duration);
imageUrl = jsonObject.getString(SONG_THUMBNAL);
songUrl = jsonObject.getString(SONG_DOWNLOAD_URL);
vocalUrl = jsonObject.getString(SONG_VOCAL_URL);
String thumbnail = null;
int cutImg = imageUrl.lastIndexOf('/');
if (cutImg != -1) {
thumbnail = imageUrl.substring(cutImg + 1);
}
sdCardPathOfImage = basepath + "/songs/" + thumbnail;
defaultSongsDetails.put("song_thumbnail", sdCardPathOfImage);
String fileName = null;
int cut = songUrl.lastIndexOf('/');
if (cut != -1) {
fileName = songUrl.substring(cut + 1);
}
sdCardPathOfOriginalSong = basepath + "/songs/" + fileName;
defaultSongsDetails.put("song_original_path", sdCardPathOfOriginalSong);
String vocalFileName = null;
int cutVocal = songUrl.lastIndexOf('/');
if (cut != -1) {
vocalFileName = songUrl.substring(cutVocal + 1);
}
sdCardPathOfVocalSong = basepath + "/songs/" + vocalFileName;
defaultSongsDetails.put("song_vocal_path", sdCardPathOfVocalSong);
defaultSongsDetailList.add(defaultSongsDetails);
}
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
trd.start();
}
//Custom Base Adapter Class
public class BaseAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private ArrayList<HashMap<String, String>> songList;
public BaseAdapter(Context context, ArrayList<HashMap<String, String>> list) {
this.mInflater = LayoutInflater.from(context);
this.songList = list;
for (HashMap hh : songList) {
System.out.println("**** hh ***" + hh);
}
}
#Override
public int getCount() {
return songList.size();
}
#Override
public Object getItem(int position) {
return songList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView;
ViewHolder holder;
if (convertView == null) {
rowView = mInflater.inflate(R.layout.list_item_view, parent, false);
holder = new ViewHolder();
holder.title = (TextView) rowView.findViewById(R.id.title);
holder.thumb = (ImageView) rowView.findViewById(R.id.list_image);
holder.artist = (TextView) rowView.findViewById(R.id.artist);
holder.duration = (TextView) rowView.findViewById(R.id.duration);
rowView.setTag(holder);
} else {
rowView = convertView;
holder = (ViewHolder) rowView.getTag();
}
holder.title.setText(songList.get(position).get("song_title"));
File file = new File(songList.get(position).get("song_thumbnail"));
Uri uri = Uri.fromFile(file);
holder.thumb.setImageURI(uri);
holder.artist.setText(songList.get(position).get("song_artist"));
holder.duration.setText(songList.get(position).get("song_duration"));
System.out.println(" title ** " + songList.get(position).get("song_title") + " duration ** " + songList.get(position).get("song_duration")
+ " thumb ** " + songList.get(position).get("song_thumbnail") + " language ** " + songList.get(position).get("song_language"));
return rowView;
}
private class ViewHolder {
public ImageView thumb;
public TextView title, duration, artist;
}
}

Correct item is not selected in Listview

I am using this Tutorial for Creating a custom listview with radio button. In this tutorial when we click the item in the list then color of item change.
This is happening when i am testing this code above 4.0 but below 4.0 it is not workin properly I am not understand why????
Class Blog.java
public class Blog extends Activity {
ListView listView;
ArrayList< String>arrayList; // list of the strings that should appear in ListView
ArrayAdapter arrayAdapter; // a middle man to bind ListView and array list
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.custom);
listView = (ListView) findViewById(R.id.lstDemo);
// LIST OF STRINGS / DATA THAT SHOULD APPEAR IN LISTVIEW HERE WE HAVE HARD CODED IT WE CAN TAKE THIS INPUT FROM USER AS WELL
arrayList = new ArrayList();
arrayList.add("India");
arrayList.add("USA");
arrayList.add("England");
arrayList.add("Singapur");
arrayList.add("China");
arrayList.add("Canada");
arrayList.add("Srilanka");
arrayList.add("SouthAfrica");
arrayAdapter = new ArrayAdapter(getApplicationContext(), android.R.layout.simple_list_item_single_choice,arrayList);
listView.setAdapter(arrayAdapter);
// LETS HIGHLIGHT SELECTED ITEMS
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView arg0, View view, int position,
long itemId) {
/*
* when we click on item on list view we can get it catch item here.
* so view is the item clicked in list view and position is the position
* of that item in list view which was clicked.
*
* Now that we know which item is click we can easily change the color
* of text but when we click on next item we we have to deselect the old
* selected item means recolor it back to default , and then hight the
* new selected item by coloring it .
*
* So here's the code of doing it.
*
*
* */
CheckedTextView textView = (CheckedTextView) view;
for (int i = 0; i < listView.getCount(); i++) {
textView= (CheckedTextView) listView.getChildAt(i);
if (textView != null) {
textView.setTextColor(Color.WHITE);
}
}
listView.invalidate();
textView = (CheckedTextView) view;
if (textView != null) {
textView.setTextColor(Color.BLUE);
}
}
});
}
}
My xml View
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/lstDemo"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:choiceMode="singleChoice">
</ListView>
Define your variables like this
private ProgressDialog pDialog;
private ListView lv;
private ArrayList<GoModelAll> m_ArrayList = null;
GoArrayAdapter gaa;
Define your AsyncTask like this
new GoAsyncTask().execute();
Your AsyncTask class Code like this
class GoAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
/*pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Please wait ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();*/
pd.show();
}
#Override
protected String doInBackground(String... params) {
sal = new StaticApiList();
myUrl = StaticApiList.go_api;
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(myUrl);
try {
HttpResponse httpResponse = httpClient.execute(httpGet);
System.out.println("httpResponse");
InputStream inputStream = httpResponse.getEntity().getContent();
InputStreamReader inputStreamReader = new InputStreamReader(
inputStream);
BufferedReader bufferedReader = new BufferedReader(
inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
while ((bufferedStrChunk = bufferedReader.readLine()) != null) {
stringBuilder.append(bufferedStrChunk);
}
jsonString = stringBuilder.toString();
Log.i("talk_all_json", jsonString);
return stringBuilder.toString();
} catch (ClientProtocolException cpe) {
System.out.println("Exception generates caz of httpResponse :"
+ cpe);
cpe.printStackTrace();
} catch (IOException ioe) {
System.out
.println("Second exception generates caz of httpResponse :"
+ ioe);
ioe.printStackTrace();
}
return null;
}
#SuppressWarnings("static-access")
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
vivek = true;
try{
m_ArrayList = new ArrayList<GoModelAll>();
if (jsonString.length() > 0) {
JSONArray jArray = new JSONArray(jsonString);
dh.open();
for(int i=0; i < jArray.length(); i++) {
JSONObject jObject = jArray.getJSONObject(i);
description = jObject.getString("description");
excert = jObject.getString("excert");
thumsrc = jObject.getString("thumsrc");
title = jObject.getString("title");
postid = jObject.getInt("postid");
Log.d("talklog", "Title -> " + title + " , thumsrc -> " + thumsrc
+ " , excert -> " + excert + " , description -> " + description);
Log.d("talklog", "============================= end of " + i + " ===============================");
gma = new GoModelAll();
gma.description = description;
gma.excert = excert;
gma.thumsrc = thumsrc;
gma.title = title;
gma.postid = postid;
Cursor cursor = dh.getSeenStatus(gma.postid);
if(cursor.getCount()>0)
{
cursor.moveToFirst();
if(cursor.getInt(0) == 0)
{
gma.isSeen = false;
}
else
{
gma.isSeen = true;
}
}
else
{
ContentValues cv = new ContentValues();
cv.put(DbHandler.KEY_ID, postid);
cv.put(DbHandler.KEY_VALUE, 0);
dh.addData(DbHandler.TABLE_SEEN, cv);
}
m_ArrayList.add(gma);
}
dh.close();
}
gaa = new GoArrayAdapter(getActivity(), m_ArrayList);
lv = (ListView) getActivity().findViewById(R.id.go_list);
lv.setVisibility(View.VISIBLE);
lv.setAdapter(gaa);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
dh.open();
dh.updateSeenStatus(m_ArrayList.get(arg2).postid, 1);
m_ArrayList.get(arg2).isSeen = true;
dh.close();
GoDetail fragment = new GoDetail();
Bundle bundle = new Bundle();
bundle.putString("title", m_ArrayList.get(arg2).title);
bundle.putString("excert", m_ArrayList.get(arg2).excert);
bundle.putString("description", m_ArrayList.get(arg2).description);
bundle.putString("thumsrc", m_ArrayList.get(arg2).thumsrc);
bundle.putString("header_title", "Go");
//bundle.putInt("postid", m_ArrayList.get(arg2).postid);
fragment.setArguments(bundle);
((BaseContainerFragment)getParentFragment()).replaceFragment(fragment, true);
}
});
}catch(Exception e){
e.printStackTrace();
}
//pDialog.dismiss();
pd.dismiss();
}
}
Your Adapter class
public class GoArrayAdapter extends ArrayAdapter<GoModelAll> {
private final Context context;
ImageLoader imgLoader;
private final ArrayList<GoModelAll> values;
DataHelper dh;
public GoArrayAdapter(Context context,
ArrayList<GoModelAll> values) {
super(context, R.layout.go_row, values);
this.context = context;
this.values = values;
imgLoader = new ImageLoader(context);
dh = new DataHelper(context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.go_row, parent, false);
/** Get view over here.. */
GoModelAll asm = values.get(position);
TextView title = (TextView) rowView.findViewById(R.id.go_tv);
ImageView business_logo = (ImageView) rowView.findViewById(R.id.go_image);
ImageView go_red = (ImageView)rowView.findViewById(R.id.go_red);
if(asm.isSeen)
{
go_red.setVisibility(View.INVISIBLE);
}
/**Set view over here..*/
title.setText(asm.title);
// Loader image - will be shown before loading image
int loader = R.drawable.image_not_available;
String image_url = asm.thumsrc;
imgLoader.DisplayImage(image_url, loader, business_logo);
return rowView;
}
}
At last your Model class
public class GoModelAll {
public String description = "";
public String excert = "";
public String thumsrc = "";
public String title = "";
public int postid = 0;
public boolean isSeen = false;
}
Show us your adapter code as well and try not to change an item of list view from setOnItemClickListener instead change your data and notify adapter to refresh the view.
Set this as background to your list item :
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:color="#color/white" />
<item android:color="#color/black" />
</selector>

Android listview header

i have an app that is showing data in listview ,but i want first row to be inflated by diferent layout , and i did that but since there is gona be a big number of listitems , i want to optimize listview and there is issue. i cant optimize listview when iam filling listview on that way , so how can i put content that should go in fist row inside listview header witch is inflated by some layout ,here is the code of Adapter
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
LinearLayout content = (LinearLayout) findViewById(R.id.content);
LinearLayout refLayout = (LinearLayout) findViewById(R.id.refLayout);
refLayout.setVisibility(View.GONE);
mBtnNaslovnica = (Button) findViewById(R.id.mBtnNaslovnica);
mBtnNaslovnica.setSelected(true);
TextView txtView=(TextView) findViewById(R.id.scroller);
txtView.setSelected(true);
loadPage();
ImageButton mBtnRefresh = (ImageButton) findViewById(R.id.btnRefresh);
mBtnRefresh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new LoadingTask().execute(URL);
}
});
}
public void loadPage(){
ArrayList<HashMap<String, String>> homeList = new ArrayList<HashMap<String, String>>();
JSONObject jsonobj;
try {
jsonobj = new JSONObject(getIntent().getStringExtra("json"));
JSONObject datajson = jsonobj.getJSONObject("data");
JSONArray news = datajson.getJSONArray(TAG_NEWS);
JSONArray actual = datajson.getJSONArray("actual");
for(int i = 0; i < news.length(); i++){
JSONObject c = news.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String title = c.getString(TAG_TITLE);
String story = c.getString(TAG_STORY);
String shorten = c.getString(TAG_SH_STORY);
String author = c.getString(TAG_AUTHOR);
String datetime = c.getString(TAG_DATETIME);
String img = c.getString(TAG_IMG);
String big_img = c.getString(TAG_BIG_IMG);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_TITLE, title);
map.put(TAG_STORY, story);
map.put(TAG_IMG, img);
map.put(TAG_BIG_IMG, big_img);
map.put(TAG_DATETIME, datetime);
map.put(TAG_AUTHOR, author);
// adding HashList to ArrayList
homeList.add(map);}
for(int i = 0; i < actual.length(); i++){
JSONObject c = actual.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ACT_TIME);
String body = c.getString(TAG_ACT_BODY);
String anews = " | "+ id+ " " + body;
String cur_anews = ((TextView) findViewById(R.id.scroller)).getText().toString();
String complete = anews + cur_anews;
TextView anewstv = (TextView) findViewById(R.id.scroller);
anewstv.setText(complete);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
list=(ListView)findViewById(R.id.list);
// Getting adapter by passing xml data ArrayList
adapter=new LazyAdapter(this, homeList);
list.setAdapter(adapter);
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
String cur_title = ((TextView) view.findViewById(R.id.title)).getText().toString();
String cur_story = ((TextView) view.findViewById(R.id.einfo2)).getText().toString();
String cur_author = ((TextView) view.findViewById(R.id.einfo1)).getText().toString();
String cur_datetime = ((TextView) view.findViewById(R.id.tVdatetime)).getText().toString();
String cur_actual = ((TextView) findViewById(R.id.scroller)).getText().toString();
ImageView cur_img = (ImageView) view.findViewById(R.id.list_image);
String cur_img_url = (String) cur_img.getTag();
Intent i = new Intent("com.example.androidhive.CURENTNEWS");
i.putExtra("CUR_TITLE", cur_title);
i.putExtra("CUR_STORY", cur_story);
i.putExtra("CUR_AUTHOR", cur_author);
i.putExtra("CUR_DATETIME", cur_datetime);
i.putExtra("CUR_IMG_URL", cur_img_url);
i.putExtra("CUR_ACTUAL", cur_actual);
startActivity(i);
}
});
}
public void reloadPage(String jsonstring){
ArrayList<HashMap<String, String>> homeList = new ArrayList<HashMap<String, String>>();
JSONObject jsonobj;
try {
jsonobj = new JSONObject(jsonstring);
JSONObject datajson = jsonobj.getJSONObject("data");
JSONArray news = datajson.getJSONArray(TAG_NEWS);
JSONArray actual = datajson.getJSONArray("actual");
for(int i = 0; i < news.length(); i++){
JSONObject c = news.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String title = c.getString(TAG_TITLE);
String story = c.getString(TAG_STORY);
String shorten = c.getString(TAG_SH_STORY);
String author = c.getString(TAG_AUTHOR);
String datetime = c.getString(TAG_DATETIME);
String img = c.getString(TAG_IMG);
String big_img = c.getString(TAG_BIG_IMG);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_TITLE, title);
map.put(TAG_STORY, story);
map.put(TAG_IMG, img);
map.put(TAG_BIG_IMG, big_img);
map.put(TAG_DATETIME, datetime);
map.put(TAG_AUTHOR, author);
// adding HashList to ArrayList
homeList.add(map);}
for(int i = 0; i < actual.length(); i++){
JSONObject c = actual.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ACT_TIME);
String body = c.getString(TAG_ACT_BODY);
String anews = " | "+ id+ " " + body;
String cur_anews = ((TextView) findViewById(R.id.scroller)).getText().toString();
String complete = anews + cur_anews;
TextView anewstv = (TextView) findViewById(R.id.scroller);
anewstv.setText(complete);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
list=(ListView)findViewById(R.id.list);
// Getting adapter by passing xml data ArrayList
adapter=new LazyAdapter(this, homeList);
list.setAdapter(adapter);
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
String cur_title = ((TextView) view.findViewById(R.id.title)).getText().toString();
String cur_story = ((TextView) view.findViewById(R.id.einfo2)).getText().toString();
String cur_author = ((TextView) view.findViewById(R.id.einfo1)).getText().toString();
String cur_datetime = ((TextView) view.findViewById(R.id.tVdatetime)).getText().toString();
String cur_actual = ((TextView) findViewById(R.id.scroller)).getText().toString();
ImageView cur_img = (ImageView) view.findViewById(R.id.list_image);
String cur_img_url = (String) cur_img.getTag();
Intent i = new Intent("com.example.androidhive.CURENTNEWS");
i.putExtra("CUR_TITLE", cur_title);
i.putExtra("CUR_STORY", cur_story);
i.putExtra("CUR_AUTHOR", cur_author);
i.putExtra("CUR_DATETIME", cur_datetime);
i.putExtra("CUR_IMG_URL", cur_img_url);
i.putExtra("CUR_ACTUAL", cur_actual);
startActivity(i);
}
});
}
public void startNewActivity(){
}
public class LoadingTask extends AsyncTask<String, Object, Object>{
XMLParser parser = new XMLParser();
JSONParser jParser = new JSONParser();
LinearLayout content = (LinearLayout) findViewById(R.id.content);
LinearLayout refLayout = (LinearLayout) findViewById(R.id.refLayout);
protected void onPreExecute(){
content.setClickable(false);
refLayout.setVisibility(View.VISIBLE);
}
#Override
protected Object doInBackground(String... params) {
// TODO Auto-generated method stub
String URL = params[0];
JSONObject json = jParser.getJSONFromUrl(URL);
//String xml = parser.getXmlFromUrl(URL); // getting XML from URL
// getting DOM element
return json;
}
protected void onPostExecute(Object result){
String json;
json = result.toString();
reloadPage(json);
refLayout.setVisibility(View.GONE);
}
}
}
If I got your point - you can go with 2 approaches:
Add headerView to the list. That is just easy as inflate your View and pass it to
addHeaderView(View) of your List. Note: you must add this view before setting the adapter, or it will throw the exception.
However, as your 'header' is representing the same data as all other items, but has different layout - I suggest not to use Header here. Instead, try to implement getItemViewType() in your adapter. http://developer.android.com/reference/android/widget/BaseAdapter.html#getItemViewType(int)
If you'll do - you'll have ability to check which type of layout to return in getView() method. And Android will take care of optimizing and reusing your inflated Views for you, so you can be sure that convertView, passed to your getView will be of the right type and layout.
Please let me know if I should explain with more details.
You can do it like this:
...
convertView.setOnClickListener(new OnItemClick(position));
...
public class OnItemClick implements OnClickListener {
private final int index;
public OnItemClick(int _index) {
this.index = _index;
}
#Override
public void onClick(View v) {
//dosomething
}
}

Categories

Resources