OnItemClickListener Problem - android

i'm creating a lazy load of image in ListView.
i was followed the tutorial from this source which i found in Stack Overflow
It was run successful.
But, when i join the code together with my project then i face a problem. the program was no perform the OnItemClickListener :(
my project have a TabHost and it had 5 tab contents. 2 contents is using the ListActivity and run perfectly.
here is my coding, Main.java:
public class ProductListing extends Activity {
ListView list;
MyListAdapter adapter;
Controller c;
ImageLoader imageLoader;
TextView select;
//========== JSON ===========
ArrayList<String> strName = new ArrayList<String>();
ArrayList<String> strImage = new ArrayList<String>();
ArrayList<String> strDesc = new ArrayList<String>();
ArrayList<String> strSize = new ArrayList<String>();
JSONObject jsonObject;
String[] listItem;
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LoadJSON();
setContentView(R.layout.productlisting_tab);
list=(ListView)findViewById(R.id.ListView01);
c = new Controller(this);
adapter=new MyListAdapter(this,this, strName, strImage,strDesc,strSize);
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
System.out.println("Item Clicked");
}
});
}
public void LoadJSON(){
try {
InputStream is = this.getResources().openRawResource(R.raw.premium);
byte[] buffer;
buffer = new byte[is.available()];
while(is.read(buffer) != -1);
String jsonText = new String(buffer);
jsonObject = new JSONObject(jsonText);
JSONObject premium_tab = jsonObject.getJSONObject("premium_tab");
int totalItem = premium_tab.getInt(".total");
for (int i = 1; i <= totalItem; i++) {
JSONObject premium = premium_tab.getJSONObject("premium_"+i);
String tempName =premium.getString(".name").toString();
String tempImg = premium.getString(".image").toString();
String tempDesc = premium.getString(".desc").toString();
String tempSize = premium.getString(".size").toString();
strName.add(tempName);
strImage.add(tempImg);
strDesc.add(tempDesc);
strSize.add(tempSize);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
MyListAdapter.java:
public MyListAdapter(Context b,Activity a, ArrayList<String> strName, ArrayList<String> strImage,
ArrayList<String> strDesc, ArrayList<String> strSize) {
activity = a;
name = strName;
image = strImage;
desc = strDesc;
size = strSize;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader=new ImageLoader(activity.getApplicationContext());
}
public int getCount() {
return image.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public static class ViewHolder{
public TextView ProductName,ProductSize, ProductDesc;
public ImageView ProductIcon;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
ViewHolder holder;
if(convertView==null){
vi = inflater.inflate(R.layout.productlisting, null);
holder=new ViewHolder();
holder.ProductName=(TextView)vi.findViewById(R.id.text);
holder.ProductIcon=(ImageView)vi.findViewById(R.id.image);
holder.ProductDesc=(TextView)vi.findViewById(R.id.textdesc);
holder.ProductSize=(TextView)vi.findViewById(R.id.textsize);
vi.setTag(holder);
}
else
holder=(ViewHolder)vi.getTag();
holder.ProductName.setText(name.get(position));
holder.ProductDesc.setText(desc.get(position));
holder.ProductIcon.setTag(image.get(position));
holder.ProductSize.setText(size.get(position));
imageLoader.DisplayImage(image.get(position), activity, holder.ProductIcon);
return vi;
}
}
Another class which name ImageLoader.java please refer the source link above.
May i know where is my mistake? i understand my code will very ugly, i'm a new in android please help me to solve the problem. it was stuck me for few days.
your reply is very appreciated !!!
P/S: I'm sorry about my bad english, hope you guys understand what i'm talking about.
Thank you.
Regard
Wynix

I use a different technique adding event-listeners. In the OnCreate-method i write btnAdd.setOnClickListener(onAdd); and adding a stand-alone method to hook up to the event like this:
private View.OnClickListener onAdd=new View.OnClickListener() {
public void onClick(View v) {
// your code here
}
};
This makes it easier to search for errors in your code.
From your code, you set the event-listener to the entire list, instead of each individual item. Maybe you should try adding events to individual items instead?

I have solve the problem and solve it. the erroe is on the xml file. in ListView should NOT have
android:focusable="true"; menthod.
anyway Thanks for trying to fix my problem.
Thanks again.
Cheers!
Regard Wynix

Related

Add load more button to listview in android

I am working on android projects. In my application I am getting the data from php webservice. I added my data to different arraylists and set them to listadapter. But my problem is it is taking very long time to display the data in list. Hence now I want to display first 10 items and want to keep a loadmore button at the bottom of the screen. Once the load more button is clicked the next 10 items need to display. Please can anybody help me in this regard. I would really appreciate for this help.
Thank you in advance.
Code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main1);
Longop op = new Longop();
op.execute("");
}
public void loadSomeDummyData() {
try {
response = CustomHttpClient
.executeHttpPost(
"http://website.com/folder/testfile.php",
postParameters);
for (int i = 1; i < arr1.length - 1; i++) {
id.add(new String(arr[0]));
name.add(new String(arr[1]));
dateofbirth.add(new String(arr[2]));
status.add(new String(arr[3]));
}
} catch (Exception e) {
e.printStackTrace();
}
}
private class Longop extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
loadSomeDummyData();
return "Executed";
}
#Override
protected void onPostExecute(String result) {
mdialog.dismiss();
myListView.setAdapter(new MyArrayAdapter(Sample.this,
R.layout.list, id, name, dateofbirth,
status));
}
#Override
protected void onPreExecute() {
mdialog = ProgressDialog.show(Sample.this, "Please wait...",
"Retrieving data ...", true);
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
private class MyArrayAdapter extends ArrayAdapter<String> {
// this list hold the data that we will see in listview
private List<String> myData = new ArrayList<String>();
private List<String> myData1 = new ArrayList<String>();
private List<String> myData2 = new ArrayList<String>();
private List<String> myData3 = new ArrayList<String>();
public MyArrayAdapter(Context context, int textViewResourceId,
List<String> objects, List<String> objects1,
List<String> objects2, List<String> objects3) {
super(context, textViewResourceId, objects);
// TODO Auto-generated constructor stub
context = getContext();
myData = objects;
myData1 = objects1;
myData2 = objects2;
myData3 = objects3;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v = convertView;
if (v == null) {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.list, null);
// Log.d(EKSI, "Getting the inflater from the system context");
}
String sid = myData.get(position);
String sname = myData1.get(position);
String dob = myData2.get(position);
String sstatus = myData3.get(position);
TextView entryTextView = (TextView) v.findViewById(R.id.id1);
entryTextView.setText(sid);
TextView entryTextView1 = (TextView) v
.findViewById(R.id.id2);
entryTextView1.setText(sname);
TextView entryTextView2 = (TextView) v
.findViewById(R.id.id3);
entryTextView2.setText(dob);
TextView entryTextView3 = (TextView) v
.findViewById(R.id.id4);
entryTextView3.setText(sstatus);
return v;
}
}
You could also use this lib
https://github.com/chrisbanes/Android-PullToRefresh.
I implement this function not base ListView that can do this;
Custom loading view,override onDraw menthod
Add loading view at the end of LinearLayout view. When loading view is show, it should call some methods to get data from server by HTTP.
you just need to inflate an xml in
lstView.addFooterView(R.layout.footer);
and handle onclick of the button residing in footer

android - identify items in a ListView

I'm having some troubles with correct identification of items in a ListView.
There are 4 classes that matter, it's a lot of code so at first I'm going to explain the logic of those classes.
Enter the ListActivity and initialize its ListView
execute an AsyncTask that downloads JSON response from the server, parses it, populates the ListView with Objects and sets the adapter while showing a ProgressDialog
the PlaylistItem class includes methods which simply get the data from a single JSONObject. It is used to parameterize the ArrayList with its Objects
after the AsyncTask is done the list is filled with items and looks like |Button| Artist(TextView) - Title(TextView)
UPDATE
resolved 1st issue but still can't figure out what's wrong with buttons
2). I set an OnClickListener to my buttons in the Adapter's getView() method. To find out if the button is identified correctly I did nothing but just changed its background. BUT a click on a certain button forces the background of every 11th or 12th button to be changed. Can't figure it out so far.
I can't proceed to getting url and streaming audio until those problems are resolved, so any help is greatly appreciated. My classes go below, please ask if something appears unclear.
AudioList
public class AudioList extends ListActivity {
private ListView lv;
private PlaylistLoader loader;
private AudioListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_audio_list);
init(); // initialize the ListView
/*--- populate the list with user's audio in case network connection is available ---*/
loader = new PlaylistLoader(this, lv, adapter);
if (Utils.isNetworkAvailable(this)) {
loader.execute();
} else {
APP_CONSTANTS.NO_DATA_CONNECTION(this);
}
}
#Override
protected void onResume() {
super.onResume();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Toast.makeText(getApplicationContext(), Integer.toString(arg2),
Toast.LENGTH_SHORT).show();
}
});
}
private void init() {
lv = getListView();
lv.setTranscriptMode(0x00000000);
lv.setDividerHeight(1);
lv.setSmoothScrollbarEnabled(true);
lv.setVerticalFadingEdgeEnabled(true);
}
PlaylistLoader
public class PlaylistLoader extends AsyncTask<Void, Void, Void> {
private JSONObject usersPlaylist, singleJSONItem;
private JSONArray responseJSONArray;
private ListView lv;
private ArrayList<PlaylistItem> playlist;
private Activity a;
private PlaylistItem audioList;
private SharedPreferences prefs;
private ProgressDialog pd;
AudioListAdapter adapter;
public PlaylistLoader(Activity a, ListView lv, AudioListAdapter adapter) {
this.lv = lv;
this.a = a;
this.adapter = adapter;
}
#Override
protected Void doInBackground(Void... arg0) {
/*--- create new ArrayList of PlaylistItem Objects ---*/
playlist = new ArrayList<PlaylistItem>();
/*--- get the preferences using context of calling activity ---*/
prefs = PreferenceManager.getDefaultSharedPreferences(a);
try {
/*--- download the response JSONObject from server // access_token and
* user_id come from activity's defaultSharedPreferences ---*/
usersPlaylist = Utils.retrieveJsonObjectFromUrl(new URL(
APP_CONSTANTS.REQUEST_AUDIO_LIST(prefs)), a);
/*--- get the response array from received object ---*/
responseJSONArray = usersPlaylist.getJSONArray("response");
/*--- populate the ArrayList with Objects from the response array ---*/
for (int i = 0; i < responseJSONArray.length(); i++) {
singleJSONItem = responseJSONArray.getJSONObject(i);
audioList = new PlaylistItem(singleJSONItem);
playlist.add(audioList);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(a);
pd.setTitle("Please wait");
pd.setMessage("Retrieving audio list...");
pd.show();
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
lv.setVisibility(View.VISIBLE);
pd.dismiss();
/*--- set the adapter passed in constructor as an adapter for passed ListView ---*/
adapter = new AudioListAdapter(a, R.layout.playlist_item, playlist);
lv.setAdapter(adapter);
}
}
AudioListAdapter
public class AudioListAdapter extends ArrayAdapter<PlaylistItem> {
private PlaylistItem pl;
private Context context;
private int layoutResourceId;
private PlaylistItem aud;
private ArrayList<PlaylistItem> data = null;
public AudioListAdapter(Context context, int layoutResourceId,
ArrayList<PlaylistItem> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public PlaylistItem getItem(int position) {
return super.getItem(position);
}
#Override
public int getCount() {
return data.size();
}
#Override
public int getPosition(PlaylistItem item) {
return super.getPosition(item);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
pl = new PlaylistItem();
aud = getItem(position);
if (convertView == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
convertView = inflater.inflate(layoutResourceId, parent, false);
pl.btnPlay = (Button) convertView.findViewById(R.id.btn_list_play);
pl.imgSaved = (ImageView) convertView
.findViewById(R.id.img_list_audio_saved);
pl.tvArtist = (TextView) convertView
.findViewById(R.id.tvListItemArtist);
pl.tvTitle = (TextView) convertView
.findViewById(R.id.tvListItemSong);
convertView.setTag(pl);
} else {
pl = (PlaylistItem) convertView.getTag();
pl.btnPlay.setBackgroundResource(R.drawable.list_button_play);
}
pl.tvArtist.setText(aud.getArtist() + " " + "-");
pl.tvTitle.setText(aud.getTitle());
pl.btnPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/*--- vibrate if this option is enabled in the preferences ---*/
if (APP_CONSTANTS.isHapticFeedbackEnabled(getContext())) {
APP_CONSTANTS.doVibrate(getContext());
}
pl.btnPlay.setBackgroundResource(R.drawable.list_button_pause);
}
});
return convertView;
}
PlayListItem
public class PlaylistItem {
private String artist, title;
private JSONObject obj;
public Button btnPlay;
public TextView tvArtist, tvTitle;
public ImageView imgSaved;
public int duration;
public int audio_id;
public String url;
/*--- the constructor takes a single JSONObject from the response array ---*/
public PlaylistItem(JSONObject obj) {
this.obj = obj;
}
public PlaylistItem() {
// default constructor
}
/*--- the methods below return values by key from the passed JSONObject ---*/
public String getArtist() {
try {
artist = obj.getString("artist");
} catch (JSONException e) {
e.printStackTrace();
}
return artist;
}
public String getTitle() {
try {
title = obj.getString("title");
} catch (JSONException e) {
e.printStackTrace();
}
return title;
}
public int getID() {
try {
audio_id = obj.getInt("aid");
} catch (JSONException e) {
e.printStackTrace();
}
return audio_id;
}
public String getURL() {
try {
url = obj.getString("url");
} catch (JSONException e) {
e.printStackTrace();
}
return url;
}
}
Edit:
Try this
Take a custom Selector in your drawable
button_play.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#drawable/pause_button"
android:state_selected="true" />
<item android:drawable="#drawable/play_button" />
</selector>
Modifty your adapter like this
public class AudioListAdapter extends ArrayAdapter<PlaylistItem> {
private PlaylistItem pl;
private Context context;
private int layoutResourceId;
private PlaylistItem aud;
private ArrayList<PlaylistItem> data = null;
Button previous;
public AudioListAdapter(Context context, int layoutResourceId,
ArrayList<PlaylistItem> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
previous=new Button(context);
this.context = context;
this.data = data;
}
....
....
#Override
public View getView(int position, View convertView, ViewGroup parent) {
pl = new PlaylistItem();
aud = getItem(position);
if (convertView == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
convertView = inflater.inflate(layoutResourceId, parent, false);
pl.btnPlay = (Button) convertView.findViewById(R.id.btn_list_play);
pl.btnPlay.setBackGroundResouce(R.drawable.button_play); //you can set here or in xml
pl.imgSaved = (ImageView) convertView
.findViewById(R.id.img_list_audio_saved);
pl.tvArtist = (TextView) convertView
.findViewById(R.id.tvListItemArtist);
pl.tvTitle = (TextView) convertView
.findViewById(R.id.tvListItemSong);
convertView.setTag(pl);
} else {
pl = (PlaylistItem) convertView.getTag();
}
pl.tvArtist.setText(aud.getArtist() + " " + "-");
pl.tvTitle.setText(aud.getTitle());
pl.btnPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/*--- vibrate if this option is enabled in the preferences ---*/
if (APP_CONSTANTS.isHapticFeedbackEnabled(getContext())) {
APP_CONSTANTS.doVibrate(getContext());
}
//for some reason, the background gets changed for every 11th or 12th button in the list
Button current=((Button)v);
current.setSelected(true);
previous.setSelected(false);
previous=current;
}
});
return convertView;
}
}
The reason why your button and listitem not clickable is because Your list have a focus item button, so you need to setFocusable=false for your button.
Try setting focusable=false for your button in the xml. If it is not worked for you than do like this
In your row xml file
1.set focusable=true for your button.
2.In the same set android:descendantFocusability="blocksDescendants" for your parent item.(i.e parent layout in which your views lie).
In getView() method after setting the onclickListener for the button, set focusable false for the button.
It will work for sure. I hope this will help you..
BUT a click on a certain button forces the background of every 11th or 12th button to be changed. Can't figure it out so far.
You are fighting the way ListViews recycle the row layouts.
Think of it this way: if you have a ListView with 10,000 rows but can only fit 9 of them on the screen, then it doesn't make sense to create 10,000 unique layouts. This just waste resources, instead ListView only creates ~10 layouts and reuses them.
Solution: return each row to it's default state when it is reused. In getView() add:
} else {
pl = (PlaylistItem) convertView.getTag();
pl.btnPlay.setBackgroundResource(R.drawable.list_button_play);
// I guessed at the resource's name ^^^^^^^^^^^^^^^^
}
(Also you can make a few small changes to speed up your code. For instance, you only need one OnClickListener since they all contain the same code, make this a class variable and pass this to each play Button. There are more.)

Notepad Tutorial: Add baseadapter

I have done the notepad tutorial from android webside. I added an own Module-Class. Now I also want to add a own baseadapter. But I have problems with the implementation.
My problem is the fillData() method. It is in the third code part. I am also not sure, if I will need a cursor?
I hope anybody can help me, to correct the fillData() method.
My Module-Class
public class Module {
private String title;
private String device_type;
private String home_code;
private String device_code;
public Module(String n, String m, String hc, String mc) {
title = n;
device_type = m;
home_code = hc;
device_code = mc;
}
public String getTitle() { return title; }
public String getDeviceType() { return device_type; }
public String getHomeCode() { return home_code; }
public String getDeviceCode() { return device_code; }
}
My Module Adapter:
public class ModuleAdapter extends BaseAdapter implements OnClickListener {
private Context context;
private List<Module> listModule;
public ModuleAdapter(Context context, List<Module> listModule) {
this.context = context;
this.listModule = listModule;
}
public int getCount() {
return listModule.size();
}
public Object getItem(int position) {
return listModule.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup viewGroup) {
Module entry = listModule.get(position);
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.notes_row, null);
}
TextView tvTitle = (TextView) convertView.findViewById(R.id.text1);
tvTitle.setText(entry.getTitle());
TextView tvDeviceType = (TextView) convertView.findViewById(R.id.text2);
tvDeviceType.setText(entry.getDeviceType());
TextView tvHomeCode = (TextView) convertView.findViewById(R.id.text3);
tvHomeCode.setText(entry.getHomeCode());
TextView tvDeviceCode = (TextView) convertView.findViewById(R.id.text4);
tvDeviceCode.setText(entry.getDeviceCode());
return convertView;
}
#Override
public void onClick(View view) {
Module entry = (Module) view.getTag();
listModule.remove(entry);
// listModule.remove(view.getId());
notifyDataSetChanged();
}
private void showDialog(Module entry) {
// Create and show your dialog
// Depending on the Dialogs button clicks delete it or do nothing
}
}
The fillData() method from the main code:
private void fillData() {
//Cursor notesCursor = mDbHelper.fetchAllNotes();
//startManagingCursor(notesCursor);
final List<Module> from = new ArrayList<Module>();
from.add(new Module(NotesDbAdapter.KEY_TITLE, NotesDbAdapter.KEY_DEVICETYPE, NotesDbAdapter.KEY_HOMECODE, NotesDbAdapter.KEY_DEVICECODE));
// Now create a simple cursor adapter and set it to display
//SimpleCursorAdapter notes =
// new SimpleCursorAdapter(this, R.layout.notes_row, notesCursor, from, to);
//notes.setViewBinder(new ModuleViewBinder());
ModuleAdapter adapter = new ModuleAdapter(this, from);
setListAdapter(adapter);
}
Thanks a lot!
Felix
The problem is your data is in a database, so you should keep using the SimpleCursorAdapter as you were doing in the code you commented out.
Your new code puts a module filled in with the names of the database columns (and not the actual data) in the ArrayList:
from.add(new Module(NotesDbAdapter.KEY_TITLE, NotesDbAdapter.KEY_DEVICETYPE, NotesDbAdapter.KEY_HOMECODE, NotesDbAdapter.KEY_DEVICECODE));
Then your custom adapter works correctly, because it displays those values.
What probably got you confused is that you were passing the same strings to the SimpleCursorAdapter, but that adapter uses the column names to fetch data from the database. Your custom adapter instead simply shows what's in the list.
If you want to show the values from the database you should stick to SimpleCursorAdapter (or extend it if you need to do more).

OnItemClickListener getting data from model

I am fairly new to Android development and I am trying to build a ListView which get data from web service using gson. I have a model class, a list class, an adapter class and the activity class.
The list works fine and it got the data, and now I want to integrate the OnItemClickListener to it and pass the data to the 2nd activity. And I'd like to get the item id (DistrictId) and pass it to the next Activity(listView) instead of the row id. It would be great if someone could show me the light... as the documentation is not as clear to understand and because I am new.
Below is my code.
The model class
package com.sample.myapp;
public class DistrictModel {
private String id;
private String districtName;
public String getDistrictId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getDistrictName(){
return districtName;
}
public void setDistrictEN(String districtName){
this.districtName = districtName;
}
}
The List class
public class DistrictList {
private List<DistrictModel> districts;
public List<DistrictModel> getDistricts(){
return districts;
}
public void setDistrictList(List<DistrictModel> districts){
this.districts = districts;
}
}
The Adapter class
public class DistrictAdapter extends ArrayAdapter<DistrictModel>{
int resource;
String response;
Context context;
private LayoutInflater dInflater;
public DistrictAdapter(Context context, int resource, List<DistrictModel> objects) {
super(context, resource, objects);
this.resource = resource;
dInflater = LayoutInflater.from(context);
}
static class ViewHolder {
TextView title;
}
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder holder;
//Get the current location object
DistrictModel lm = (DistrictModel) getItem(position);
//Inflate the view
if(convertView==null)
{
convertView = dInflater.inflate(R.layout.item_district, null);
holder = new ViewHolder();
holder.title = (TextView) convertView
.findViewById(R.id.district_name);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
holder.title.setText(lm.getDistrictName());
return convertView;
}
}
The activity class
public class DistrictListActivity extends Activity{
LocationManager lm;
ArrayList<DistrictModel> districtArray = null;
DistrictAdapter districtAdapter;
DistrictList list;
ListView lv;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.districtlist_layout);
lv = (ListView) findViewById(R.id.list_district);
districtArray = new ArrayList<DistrictModel>();
districtAdapter = new DistrictAdapter(DistrictListActivity.this, R.layout.item_district, districtArray);
lv.setTextFilterEnabled(true);
lv.setAdapter(districtAdapter);
try {
new DistrictSync().execute("http://aws.something.com/service");
} catch(Exception e) {}
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View convertView, int position, long id) {
AlertDialog.Builder adb=new AlertDialog.Builder(DistrictListActivity.this);
adb.setTitle("LVSelectedItemExample");
adb.setMessage("Selected Item is = "+(lv.getItemIdAtPosition(position)));
adb.setPositiveButton("Ok", null);
adb.show();
}
}); **//i'd like to get the DistrictId from the json data.**
}
private class DistrictSync extends AsyncTask<String, Integer, DistrictList> {
protected DistrictList doInBackground(String... urls) {
DistrictList list = null;
int count = urls.length;
for (int i = 0; i < count; i++) {
try {
// ntar diganti service
RestClient client = new RestClient(urls[i]);
try {
client.Execute(RequestMethod.GET);
} catch (Exception e) {
e.printStackTrace();
}
String json = client.getResponse();
list = new Gson().fromJson(json, DistrictList.class);
//
} catch(Exception e) {}
}
return list;
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(DistrictList dislist) {
for(DistrictModel lm : dislist.getDistricts())
{
districtArray.add(lm);
}
districtAdapter.notifyDataSetChanged();
}
}
}
For testing purpose, now I click the row it will show me the row id, so I know the onclick listener works, but I just want it to grab me the DistrictId so I can use it to pass to the next activity.
Thank you so much.
(out of my head) Try this:
((DistrictModel)lv.getAdapter().getItem(position)).getDistrictId();
Generally when you want to pass data from one Activity to another, you just place it into the Intent that you use to create the new Activity.
For example (and here are some additional examples):
Intent i = new Intent(context, MyNewActivity.class);
i.putExtra("MyCurrentHealth", mCurrentHealth);
context.startActivity(i);
To retrieve the data do this:
Bundle extras = getIntent().getExtras();
if (extra != null) {
... // Do stuff with extras
}

problem with an adapter in android app

I have an app in android in which I return some data from facebook(some names and id's) and right after I return this data I use an adapter to set all this names in a list view.
All this work I do it in onCreate().First time I use a method getData() to return some names from facebook and after that I call for the adapter.
The problem is that getData() returns in an array of Strings the names that will be setup up with the adapter.Now,the adapter called does some processing on this array.
How I return these names from web this part works slowly and the array is not filled in time so when the adapter gets called the array is still empty and I get force close.
this is how I do it:
private String[] mStrings;
private String[] fName;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.invitefriends);
....................
/*In here I request for friends from facebook which ae set up in an array*/
mAsyncRunner.request("me/friends", new SampleRequestListener());
/*here is the adapter that processes the arrays returned in SampleRequestListener*/
adapter=new LazyAdapter1(this, mStrings,fName);
list.setAdapter(adapter);
}
/Here is the SampleRequestListener that does return from facebook the names in some arrays/
public class SampleRequestListener extends BaseRequestListener{
int i;
public void onComplete(final String response, final Object state){
friends = new ArrayList<Friends>();
try{
Log.d("facebook-example","Response: " + response.toString());
JSONObject json = Util.parseJson(response);
JSONArray array = json.optJSONArray("data");
if(array!=null){
for(int i=0; i<array.length(); i++)
{
String name=array.getJSONObject(i).getString("name");
String id= array.getJSONObject(i).getString("id");
Friends f=new Friends(name,id);
friends.add(f);
Log.d(name,id);
}
mStrings = new String[friends.size()];
for(int i=0; i< mStrings.length; i++){
mStrings[i] = "http://graph.facebook.com/"+friends.get(i).getId()+"/picture?type=small";
}
fName = new String[friends.size()];
for(int i=0; i<friends.size(); i++)
{
fName[i]=friends.get(i).getName();
}
}
}
catch(JSONException e)
{
//do nothing
}
catch(FacebookError e)
{
e.getMessage();
}
}
}
And finally here is the adapter's body:
public class LazyAdapter1 extends BaseAdapter {
private Activity activity;
private String[] data;
private String[] nume;
private static LayoutInflater inflater=null;
public ImageLoader imageLoader;
public LazyAdapter1(Activity a, String[] d, String[] f) {
activity = a;
data=d;
nume=f;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader=new ImageLoader(activity.getApplicationContext());
}
public int getCount() {
return data.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public static class ViewHolder{
public TextView text;
public ImageView image;
}
public View getView(int position, View convertView, ViewGroup parent) {
//........
}
}
The problem is that mStrings[] and fName[] are not returned in time by the background thread so they are still empty when I try to act with the adapter on them.
So could someone tell how should I proceed for this thing to work right??Thanks
use the AsyncTask class and extend with your custom class.
this was good for getting the data in background process.
and when the data are fetched then set into the adapter
check this links
http://www.vogella.de/articles/AndroidPerformance/article.html
http://developer.android.com/reference/android/os/AsyncTask.html
http://www.xoriant.com/blog/mobile-application-development/android-async-task.html

Categories

Resources