unable to set listview text - android

I am using json parser to pass image url and description into my listview. now i managed to load the images but how do i change the text for my list view? currently it just shows item 0, item 1 and so on.. how do i pass the description into the lazyadapter?
Main activity:
public class MainActivity extends Activity {
// CREATING JSON PARSER OBJECT
JSONParser jParser = new JSONParser();
JSONArray guide = null;
ListView list;
LazyAdapter adapter;
String[] mImageIds;
ArrayList<String> guideList =new ArrayList<String>();
ArrayList<String> descriptionList =new ArrayList<String>();
// GUIDE URL
private static String url_guide = "http://58.185.41.178/magazine_android/get_guide.txt";
private static final String TAG_GUIDES = "guides"; //the parent node of my JSON
private static final String TAG_DESCRIPTION = "description";
private static final String TAG_IMAGE = "image";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// LOADING Guide IN BACKGROUND THREAD
new LoadGuide().execute();
list=(ListView)findViewById(R.id.list);
adapter=new LazyAdapter(this,guideList);
list.setAdapter(adapter);
Button b=(Button)findViewById(R.id.button1);
b.setOnClickListener(listener);
}
#Override
public void onDestroy()
{
list.setAdapter(null);
super.onDestroy();
}
public OnClickListener listener=new OnClickListener(){
#Override
public void onClick(View arg0) {
adapter.imageLoader.clearCache();
adapter.notifyDataSetChanged();
}
};
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadGuide extends AsyncTask<String, String, String> {
/**
* getting All videos from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_guide, "GET", params);
// CHECKING OF JSON RESPONSE
Log.d("All guide: ", json.toString());
try {
guide = json.getJSONArray(TAG_GUIDES);
for (int i = 0; i < guide.length(); i++) {
JSONObject c = guide.getJSONObject(i);
//String title = c.getString(TAG_DESCRIPTION);
String image = c.getString(TAG_IMAGE);
String description = c.getString(TAG_DESCRIPTION);
guideList.add(image);
descriptionList.add(description);
System.out.println(guideList);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// UPDATING UI FROM BACKGROUND THREAD
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
adapter.notifyDataSetChanged();
}
});
}
}
}
Image adapter:
public class LazyAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<String> data;
private static LayoutInflater inflater=null;
public ImageLoader imageLoader;
public LazyAdapter(Activity a, ArrayList<String> guideList) {
activity = a;
data=guideList;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader=new ImageLoader(activity.getApplicationContext());
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.item, null);
TextView text=(TextView)vi.findViewById(R.id.text);;
ImageView image=(ImageView)vi.findViewById(R.id.image);
text.setText("item "+position);
imageLoader.DisplayImage(data.get(position), image);
return vi;
}
}

In your adapter, you are making the TextView say "item 1", "item 2" etc specifically. What you need to do is add in the Adapter constructor your descriptionList
public LazyAdapter(Activity a, ArrayList<String> guideList, ArrayList<String> descriptionList) {
and then do
text.setText(descriptionList.get(position));

When your activity calls adapter.notifyDataSetChanged(), that forces a re-draw of every item in the list. That will trigger a call into the getView() method your adapter. So your logic belongs in the getView() method:
text.setText(descriptionList.get(position));

Use a single Hashmap for guidelist and descriptionlist and then pass that to the lazyadapter constructor. use the description part of the hashmap in the getview() method to the set the text.

#user1933630
descriptionList.add(description.subString(1,description.length()-1);

Related

activity shows blank result?

I am developing an app using api to display list, and listview contains data. But when i run the project, activity shows blank result and logcat shown 'no value of "program"(i.e.array name)' message.
How do i show result of following code?
public class MainActivity extends Activity {
// Declare Variables
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String AID = "asanaid";
static String ANAME = "asananame";
static String DURATION = "duration";
static String IMGURL = "imgeurl";
static String IMGVERSION = "imgeversion";
static String AUDIOURL = "audiourl";
static String AUDIOVERSION = "audioversion";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from listview_main.xml
setContentView(R.layout.activity_relaxation_lv);
// Execute DownloadJSON AsyncTask
new DownloadJSON().execute();
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(MainActivity.this);
// Set progressdialog title
mProgressDialog.setTitle("Android JSON Parse Tutorial");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions
.getJSONfromURL("http://www.....");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("program");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("asanaid", jsonobject.getString("asanaid"));
map.put("asananame", jsonobject.getString("asananame"));
map.put("duration", jsonobject.getString("duration"));
map.put("imgeurl", jsonobject.getString("imgeurl"));
map.put("imgeversion", jsonobject.getString("imgeversion"));
map.put("audiourl", jsonobject.getString("audiourl"));
map.put("audioversion", jsonobject.getString("audioversion"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listview);
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(MainActivity.this, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
}
public class ListViewAdapter extends BaseAdapter{
// Declare Variables
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
ImageLoader imageLoader;
HashMap<String, String> resultp = new HashMap<String, String>();
public ListViewAdapter(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
imageLoader = new ImageLoader(context);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
TextView tvAname, tvId, imgUrl, imgVersion, audioUrl, audioVersion, duration;
ImageView imgPose;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.relaxationlv_single_item, parent, false);
// Get the position
resultp = data.get(position);
// Locate the TextViews in listview_item.xml
tvAname = (TextView) itemView.findViewById(R.id.lv_aname);
tvAname.setText(resultp.get(MainActivity.ANAME));
tvId = (TextView)itemView.findViewById(R.id.lv_aid);
tvId.setText(resultp.get(MainActivity.AID));
duration = (TextView)itemView.findViewById(R.id.lv_duration);
duration.setText(resultp.get(MainActivity.DURATION));
imgVersion = (TextView)itemView.findViewById(R.id.lv_imgversion);
imgVersion.setText(resultp.get(MainActivity.IMGURL));
audioVersion = (TextView)itemView.findViewById(R.id.lv_audioversion);
audioVersion.setText(resultp.get(MainActivity.AUDIOVERSION));
audioUrl= (TextView)itemView.findViewById(R.id.lv_audiourl);
audioUrl.setText(resultp.get(MainActivity.AUDIOURL));
imgPose = (ImageView)itemView.findViewById(R.id.lv_imgurl);
imageLoader.DisplayImage(resultp.get(MainActivity.IMGURL), imgPose);
// Capture ListView item click
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Get the position
resultp = data.get(position);
Intent intent = new Intent(context, RelaxationLvAudioPlayerActivity1.class);
intent.putExtra("asanaid", resultp.get(MainActivity.AID));
intent.putExtra("asananame", resultp.get(MainActivity.ANAME));
intent.putExtra("duration", resultp.get(MainActivity.DURATION));
intent.putExtra("imgeurl", resultp.get(MainActivity.IMGURL));
intent.putExtra("imgeversion", resultp.get(MainActivity.IMGVERSION));
intent.putExtra("audiourl", resultp.get(MainActivity.AUDIOURL));
intent.putExtra("audioversion", resultp.get(MainActivity.AUDIOVERSION));
context.startActivity(intent);
}
});
return itemView;
}
}
You are getting the JSONException -
Please check if one of the following field is missing in your JSON Response -
map.put("asanaid", jsonobject.getString("asanaid"));
map.put("asananame", jsonobject.getString("asananame"));
map.put("duration", jsonobject.getString("duration"));
map.put("imgeurl", jsonobject.getString("imgeurl"));
map.put("imgeversion", jsonobject.getString("imgeversion"));
map.put("audiourl", jsonobject.getString("audiourl"));
map.put("audioversion", jsonobject.getString("audioversion"));
You can check this buy printing the value of jsonobject.getString("asaname") and so on.
Or the another case might be the value is of different dataType. E.g. audioversion you are trying to get as String but in JSON it is type of Integer.

Android GridView Adapter using ArrayList

I'm stuck creating an Adapter for my Griview that accepts an ArrayList. I think the bad line in the Adapter class is: viewHldr.wcbc_image_iv.setImageResource(urlStrArrList.get(position)); and it appears that the call .setImageResource is the problem.
public class JGrid66 extends Activity {
JSONObject jsonOb;
JSONArray JSArrGallery = null;;
GridView grid65_gv;
JGrid66Adapter2 jGr7Adap;
ProgressDialog mProgressDialog;
ArrayList<String> idStrArrList = new ArrayList<String>();
ArrayList<String> urlStrArrList = new ArrayList<String>();
ArrayList<String> descrStrArrList = new ArrayList<String>();
// JSON Node names
private static final String TAG_GALLERY = "gallery";
private static final String TAG_GALLERYURL = "galleryurl";
private static final String TAG_ID = "id";
private static final String TAG_GALLERYDESCR = "gallerydescr";
static String FLAG = "flag";
private String jsonUrl = "http://www.mysite.com/apps/wcbc/galleryuil.txt";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.jgrid66);
grid65_gv = (GridView) findViewById(R.id.jgrid66_gv);
}//--- END onCreate
//--- DownloadJSON Class
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
JGrid4Adapter jParser = new JGrid4Adapter();
// getting JSON string from URL
JSONObject jsonOb = jParser.getJSONFromUrl(jsonUrl);
try {
JSArrGallery = jsonOb.getJSONArray(TAG_GALLERY);
// looping through All gallery images
for (int i = 0; i < JSArrGallery.length(); i++) {
JSONObject galleryJO = JSArrGallery.getJSONObject(i);
String idStr = galleryJO.getString(TAG_ID);
String urlStr = galleryJO.getString(TAG_GALLERYURL);
String descrStr = galleryJO.getString(TAG_GALLERYDESCR);
idStrArrList.add(idStr);
urlStrArrList.add(urlStr);
descrStrArrList.add(descrStr);
}// -- END for loop
} catch (JSONException e) {
e.printStackTrace();
}// --- END Try
return null;
}
#Override
protected void onPostExecute(Void args) {
jGr7Adap = new JGrid66Adapter2(JGrid66.this, urlStrArrList);
grid65_gv.setAdapter(jGr7Adap);
jGr7Adap.notifyDataSetChanged();
}
}
//--- END DownloadJSON Class
}
Here;s the Adapter:
public class JGrid66Adapter2 extends BaseAdapter {
private ArrayList<String> urlStrArrList;
Context context;
public JGrid66Adapter2(Context context,ArrayList<String> urlStrArrList) {
super();
this.urlStrArrList = urlStrArrList;
}
#Override
public int getCount() {
return urlStrArrList.size();
}
#Override
public String getItem(int position) {
return urlStrArrList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
public static class ViewHolder
{
public ImageView wcbc_image_iv;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHldr;
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
if(convertView==null){
viewHldr = new ViewHolder();
convertView = inflater.inflate(R.layout.jgrid66_item, null);
viewHldr.wcbc_image_iv = (ImageView) convertView.findViewById (R.id.jgrid66_iv);
convertView.setTag(viewHldr);
}
else
{
viewHldr = (ViewHolder) convertView.getTag();
}
//--- I commented this out because this is where it breaks.
//viewHldr.wcbc_image_iv.setImageResource(urlStrArrList.get(position));
return convertView;
}
}
Any help would be great!
private ArrayList<String> urlStrArrList;
is arraylist of strings. If you have the url you need to download the images and then set it to imageview.
setImageResource takes a resource id as a param which is an int value.
public void setImageResource (int resId)
Added in API level 1
Sets a drawable as the content of this ImageView.
You may consider using Lazy Loading Universal Image Loader or using picasso
Caching images and displaying

Deleting item from a Custom ListView

I have a Custom ListView which is populated with retrieved from a database. Now, what I can't understand is how to remove an item from the list: searching on Google I've seen different questions without a standard solution, so I have doubts about this. How can I delete a row from a CustomListView also using Async Task?
Here is Leggi_Pizzaiolo activity (where I display the listView):
public class Leggi_Pizzaiolo extends Activity
{
// Progress Dialog
private ProgressDialog pDialog;
public List list = new LinkedList();
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
private static String url_all_products = "http://10.0.2.2/tesina/Leggi_Pizzaiolo.php";
// JSON Node names
private static final String TAG_SUCCESS = "Esito";
private static final String TAG_PRODUCTS = "comande";
private static final String TAG_PID = "ID";
private static final String TAG_NAME = "Nome";
private static final String TAG_TABLE = "Tavolo";
public ListView lv;
// products JSONArray
JSONArray products = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ordini_cuoco);
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
// Get listview
lv = (ListView)findViewById(R.id.lista);
new LoadAllProducts().execute();
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String>
{
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Leggi_Pizzaiolo.this);
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
int id = c.getInt(TAG_PID);
String name = c.getString(TAG_NAME);
int Tavolo= c.getInt(TAG_TABLE);
list.add(new Comanda(name, id, Tavolo));
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
Listino.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url)
{
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating listview
final ComandaCursorAdapter adapter = new ComandaCursorAdapter(Leggi_Pizzaiolo.this, R.layout.comanda_cuoco, list);
lv.setAdapter(adapter);
}
}
}
This is the CursorAdapter:
public class ComandaCursorAdapter extends ArrayAdapter<Comanda>
{
public ComandaCursorAdapter(Context context, int comandaCuoco, List list) {
super(context, comandaCuoco, list);
// TODO Auto-generated constructor stub
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.comanda_cuoco, null);
TextView Nome = (TextView)convertView.findViewById(R.id.Comanda);
TextView Tavolo = (TextView)convertView.findViewById(R.id.Tavolo);
TextView Codice = (TextView)convertView.findViewById(R.id.Codice);
Comanda c = getItem(position);
Nome.setText(c.getNome());
Tavolo.setText("Tavolo: " + Integer.toString(c.getTavolo()));
Codice.setText("Codice: " + Integer.toString(c.getCodice()));
return convertView;
}
And this is the object Comanda:
public class Comanda {
private String Nome;
private int Codice;
private int Tavolo;
public Comanda(String Nome, int Codice, int Tavolo)
{
this.Nome = Nome;
this.Codice = Codice;
this.Tavolo = Tavolo;
}
public String getNome()
{
return Nome;
}
public void setNome(String Nome)
{
this.Nome = Nome;
}
public int getCodice()
{
return Codice;
}
public void setCodice(int Codice)
{
this.Codice = Codice;
}
public int getTavolo()
{
return Tavolo;
}
public void setTavolo(int Tavolo)
{
this.Tavolo = Tavolo;
}
}
Now, where I have to declare the setOnItemClickListener in Leggi_Pizzaiolo activity? Should I have to implement a remove method into the class or something? Please let me know how...
Now, what I can't understand is how to remove an item from the list
No, normally create for example OnItemClickListener() to be able to handle click events on ListView. Then in onItemClick() you have parameter int position that returns position of item in Adapter. Now you need to remove item from your List and then perform
list.remove(position)
and then you need to call
adapter.notifyDataSetChanged();
to notify Adapter that datasource has changed.
Note: For more comfort you can show after click on ListItem some AlertDialog with buttons for deleting or not.
Try this
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
AlertDialog.Builder adb=new AlertDialog.Builder(MyActivity.this);
adb.setTitle("Delete?");
adb.setMessage("Are you sure you want to delete " + position);
final int positionToRemove = position;
adb.setNegativeButton("Cancel", null);
adb.setPositiveButton("Ok", new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
MyDataObject.remove(positionToRemove);
adapter.notifyDataSetChanged();
}});
adb.show();
}
});
where lv is your listview,adb is a dialog, mydataobject is the collection you are using to populate your listview and adapter is your adapter.

How to get live updates via JSON to listview

I couldn't find a way to get live updates via JSON to a listview.
My activity is requesting JSON data from a webpage and the code is:
public class Second extends Activity {
static final String Li_nk = "LinkName:";
static final String Image_name = "ImageName:";
ListView list;
public final static String AUTH = "authentication";
static final String KEY_THUMB_URL = "thumb_image"; // Uri.decode("http://zeesms.info/android_app_images/Koala.jpg");
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent i2 = getIntent();
String wrd = i2.getStringExtra("entrd");
Log.v("keyis", wrd);
// if(wrd.equalsIgnoreCase("test")){
JSONObject j2 = JSONfunctions.getJSONfromURL("/webservice_search.php?keyword=" + wrd + "&format=json");
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
try {
JSONArray jray = j2.getJSONArray("listings");
for (int i = 0; i < jray.length(); i++) {
Log.v("state", "json data being read");
JSONObject j3 = jray.getJSONObject(i);
String first = j3.getString("listing");
Log.v("sublist", first);
JSONObject j4 = j3.getJSONObject("listing");
String sec = j4.getString("links");
int maxLength = (sec.length() < 30) ? sec.length() : 27;
sec.substring(0, maxLength);
String cutsec = sec.substring(0, maxLength);
Log.v("links are", cutsec);
String img = j4.getString("image_name");
Log.v("image name is ", img);
// Uri
// dimg=Uri.parse("http://zeesms.info/android_app_images/Koala.jpg");
HashMap<String, String> map = new HashMap<String, String>();
map.put("Id", String.valueOf(i));
map.put(Li_nk, cutsec);
map.put(Image_name, j4.getString("image_name"));
map.put(KEY_THUMB_URL, "http://zeesms.info/android_app_images/" + img);
mylist.add(map);
}
}
catch (JSONException e) {
alertbox();
Log.e("loG_tag", "Error parsing" + e.toString());
}
list = (ListView) findViewById(R.id.lv1);
this.list.setEmptyView(findViewById(R.id.empty));
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Toast.makeText(getApplicationContext(),"Click ListItem Number "
// + position, Toast.LENGTH_LONG).show();
Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.riffre.com/"));
startActivity(myIntent);
}
});
LazyAdapter adapter = new LazyAdapter(this, mylist);
list.setAdapter(adapter);
list.setItemsCanFocus(false);
// }
/*
* else{ alertbox(); }
*/
}
/*
* public void register(View view) { Log.w("C2DM",
* "start registration process"); Intent intent = new
* Intent("com.google.android.c2dm.intent.REGISTER");
* intent.putExtra("app", PendingIntent.getBroadcast(this, 0, new
* Intent(), 0)); // Sender currently not used intent.putExtra("sender",
* "nonsenses#gmail.com"); startService(intent); }
*
* public void showRegistrationId(View view) { SharedPreferences prefs =
* PreferenceManager .getDefaultSharedPreferences(this); String string =
* prefs.getString(AUTH, "n/a"); Toast.makeText(this, string,
* Toast.LENGTH_LONG).show(); Log.d("C2DM RegId", string);
*
* }
*/
public void alertbox() {
new AlertDialog.Builder(this).setMessage("Invalid Keyword,No Results found").setTitle("Alert").setCancelable(true).setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
finish();
}
}).show();
}
}
and I'm using a custom adapter with the code as follows:
public class LazyAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
public ImageLoader imageLoader;
public LazyAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader=new ImageLoader(activity.getApplicationContext());
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return data.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.custom_row_view1, null);
TextView title = (TextView)vi.findViewById(R.id.linkname); // merchnts name
TextView artist = (TextView)vi.findViewById(R.id.imagename); // address
//TextView duration = (TextView)vi.findViewById(R.id); // distance
ImageView thumb_image=(ImageView)vi.findViewById(R.id.mClogo); // logo
HashMap<String, String> jsn = new HashMap<String, String>();
jsn = data.get(position);
// Setting all values in listview
title.setText(jsn.get(Second.Li_nk));
artist.setText(jsn.get(Second.Image_name));
//duration.setText(song.get(CustomizedListView.KEY_DURATION));
imageLoader.DisplayImage(jsn.get(Second.KEY_THUMB_URL), thumb_image);
return vi;
}
}
What I want is that the application updates the listview with data every minute or so. Also the latest entry in the list should stay on top.
What would be the best way to do this?
Put your JSON parsing code, that's probably your try..catch block in a separate function and not in onCreate().
So can easily call that part every minute. let's say that function name LoadData() also add one more line adapter.notifyDataSetChanged() to update adapter/list every time.
now in your onCreate(), write this code to call that function every one minute,
final Handler handler = new Handler();
Runnable runable = new Runnable() {
#Override
public void run() {
//call the function
LoadData();
//also call the same runnable
handler.postDelayed(this, 1000);
}
};
handler.postDelayed(runable, 1000);
Now for second problem, to add new data at top..
I am just getting one thing in mind right now to write a loop , ADD THIS TO IN YOUR FUNCTION BEFORE CALLING ADAPTER NOTIFY CHANGE,like
ArrayList<HashMap<String,String>> mylist = new ArrayList<HashMap<String,String>>();
ArrayList<HashMap<String,String>> mylistTemp = new ArrayList<HashMap<String,String>>();
for(int i = mylist.size()-1 ; i >=0;i--)
{
mylistTemp.add(mylist.get(i));
}
mylist = mylistTemp;
Well if your code above is working, you should be able to achieve your goal with the following steps:
Extract your JSON-Loading code into an AsyncTask, which you can trigger every minute. (AsyncTask)
Update your ListAdapter using the AsyncTask.
Here is a possible implementation of the onCreate() method, which will run an update-task every minute:
public class JSON_AndroidActivity extends Activity {
/** Called when the activity is first created. */
private JSONLoaderTask mJSONLoaderTask;
private Handler mHandler;
private ArrayAdapter<String> mArrayAdapter;
private Runnable mRefresher = new Runnable() {
#Override
public void run() {
mJSONLoaderTask = new JSONLoaderTask(JSON_AndroidActivity.this, mArrayAdapter);
mJSONLoaderTask.execute("");
mHandler.postDelayed(this, 1000);
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mHandler.postDelayed(mRefresher, 1000);
}
}
And here is a hull implementation of a possible task, where you can do your heavy loading and update your adapter for the list:
public class JSONLoaderTask extends AsyncTask<String, String, String> {
private Context context;
private ProgressDialog progressDialog;
private final ArrayAdapter<String> mArrayAdapter;
public JSONLoaderTask(Context pContext, ArrayAdapter<String> pArrayAdapter) {
this.context = pContext;
this.mArrayAdapter = pArrayAdapter;
}
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(context);
progressDialog.show();
}
#Override
protected String doInBackground(String... params) {
String result = getJSONStream();
return result;
}
private String getJSONStream() {
//load your string here
return "";
}
#Override
protected void onPostExecute(String result) {
progressDialog.dismiss();
// Update your ArrayAdapter
}
}

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