Android Listview issues in adding data from AsyncTask - java

I am using android listview with lazyadapter to show images and textview in list.
and when user scrolls to the bottom i am using AsyncTask to add more contents but when i execute AsyncTask it kills the process.
here is my code.
mainactivity
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.NodeList;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.sax.Element;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
public class AndroidJSONParsingActivity extends Activity {
// url to make request
// JSON Node names
static final String TAG_CONTACTS = "comics";
static final String TAG_ID = "id";
static final String TAG_NAME = "title";
static final String TAG_EMAIL = "id";
static final String TAG_PHONE_MOBILE = "image";
// contacts JSONArray
JSONArray contacts = null;
ListView list;
LazyAdapter adapter;
static int counter = 0;
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
list=(ListView)findViewById(R.id.list);
// call the function
LoadData();
}
public void LoadData(){
String url = "http://myurl?start=" + counter;
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
contacts = json.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for(int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
String mobile = "http://www.funnydash.com/uploads/s/" + c.getString(TAG_PHONE_MOBILE);
// Phone number is agin JSON Object
// 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_NAME, name);
map.put(TAG_EMAIL, email);
map.put(TAG_PHONE_MOBILE, mobile);
// adding HashList to ArrayList
contactList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
/**
* Updating parsed JSON data into ListView
* */
// Getting adapter by passing xml data ArrayList
adapter=new LazyAdapter(this, contactList);
list.setAdapter(adapter);
list.setOnScrollListener(new EndlessScrollListener());
}
public class BackgroundLoadMore extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
// Showing progress dialog before sending http request
}
protected Void doInBackground(Void... unused) {
LoadData();
return (null);
}
protected void onPostExecute(Void unused) {
// On completing background task
// closing progress dialog etc,.
list.setOnScrollListener(new EndlessScrollListener());
}
}
public class EndlessScrollListener implements OnScrollListener {
private int visibleThreshold = 0;
private int currentPage = 0;
private int previousTotal = 0;
private boolean loading = true;
public EndlessScrollListener() {
}
public EndlessScrollListener(int visibleThreshold) {
this.visibleThreshold = visibleThreshold;
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if (loading) {
if (totalItemCount > previousTotal) {
loading = false;
previousTotal = totalItemCount;
counter +=12;
}
}
if (!loading && (totalItemCount - visibleItemCount) <= (firstVisibleItem + visibleThreshold)) {
// I load the next page of gigs using a background task,
// but you can call any function here.
new BackgroundLoadMore().execute();
loading = true;
}
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
}
}
Lazyadapter.java
import java.util.ArrayList;
import java.util.HashMap;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
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());
}
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.list_row, null);
TextView title = (TextView)vi.findViewById(R.id.title); // title
TextView artist = (TextView)vi.findViewById(R.id.artist); // artist name
ImageView thumb_image=(ImageView)vi.findViewById(R.id.list_image); // thumb image
HashMap<String, String> song = new HashMap<String, String>();
song = data.get(position);
// Setting all values in listview
title.setText(song.get(AndroidJSONParsingActivity.TAG_NAME));
artist.setText(song.get(AndroidJSONParsingActivity.TAG_ID));
imageLoader.DisplayImage(song.get(AndroidJSONParsingActivity.TAG_PHONE_MOBILE), thumb_image);
return vi;
}
}
and this is what i get in my logcat

The problem is because you're attempting to set an adapter on your list from outside the UI thread. Views in Android can not be modified in a background thread, which in this case, means you can not modify the UI from the doInBackground method of an AsyncTask. So, your method LoadData() can't call the following:
adapter=new LazyAdapter(this, contactList);
list.setAdapter(adapter);
list.setOnScrollListener(new EndlessScrollListener());
You will need to return some data (probably contactList) from your doInBackground() method, and then move the offending code to the onPostExecute() method, which is run on the UI thread.
The key problem noted in the stack trace is:
CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

1. Always keep the UI thread work on the UI thread, and Non-UI work on the Non-UI thread, this became a law from the arrival of the Honey Comb version of Android.
2. From your above logcat, it points to only one thing, that you are trying to do something from the Non-UI thread on the UI thread (The main Dedicated UI thread).
Here it is.... You are calling it on the doInBackground() which is a Non-UI thread.
adapter=new LazyAdapter(this, contactList);
list.setAdapter(adapter);
list.setOnScrollListener(new EndlessScrollListener());
3. Modify the adapter form UI thread, you can do it in onPostExecute()

You are trying to create a view off the main thread class.
As said on this line
07-26 22:26:36.933: E/AndroidRuntime(16353): Caused by:
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the
original thread that created a view hierarchy can touch its views.
Your main problem is here in your asyncTask. You can not create view items that are not in the original thread. What you can do. is to place this lines on your post method not in do background method or outside asynctask class.
// Getting adapter by passing xml data ArrayList
adapter=new LazyAdapter(this, contactList);
list.setAdapter(adapter);

Related

SearchView filter in ListView [duplicate]

here is my main activity
package com.javacodegeeks.android.lbs;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
import lbs.promotion.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
public class Curve extends Activity {
private ProgressDialog pDialog;
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> DaftarPromotion = new ArrayList<HashMap<String, String>>();
private static String url_daftar_promotion = "http://10.0.2.2/webserver_maaug/promotion/daftar_promotion.php";
String lon = "101.5178";
String lat = "3.0724";
public static final String TAG_SUCCESS = "success";
public static final String TAG_DAFTAR_PROMOTION = "daftar_promotion";
public static final String TAG_ID_PROMO = "PromoID";
public static final String TAG_NAMA_PROMO = "PromoName";
public static final String TAG_LINK_IMAGE_PROMO = "PromoImage";
public static final String TAG_DESC_PROMO= "PromoDesc";
public static final String TAG_CATE_PROMO = "PromoCate";
public static final String TAG_CONT_PROMO = "PromoContact";
public static final String TAG_DATES_PROMO = "PromoDateStart";
public static final String TAG_DATEE_PROMO = "PromoDateEnd";
JSONArray daftar_promotion = null;
ListView list;
PromotionListAdapter adapter;
EditText inputSearch;
private Curve activity;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_curve);
DaftarPromotion = new ArrayList<HashMap<String, String>>();
new Activity().execute();
activity = this;
list = (ListView) findViewById(R.id.list);
inputSearch = (EditText) findViewById(R.id.search_box);
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
Curve.this.adapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
HashMap<String, String> map = DaftarPromotion.get(position);
String pna = map.get(TAG_NAMA_PROMO);
String pde = map.get(TAG_DESC_PROMO);
String pca = map.get(TAG_CATE_PROMO);
String pcon = map.get(TAG_CONT_PROMO);
String pds = map.get(TAG_DATES_PROMO);
String pdae = map.get(TAG_DATEE_PROMO);
Toast.makeText(Curve.this, pna +"\n" + pde +"\n" + pca +"\n" + pds +" to " + pdae +"\n" + pcon,Toast.LENGTH_LONG).show();
}
});
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.smenu, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.about:
Toast.makeText(Curve.this,"Mobile Advertising Application Using GPS V1.0",Toast.LENGTH_LONG).show();
return true;
case R.id.search:{
Intent intent = new Intent(Curve.this, Search.class);
intent.putExtra("lon",lon);
intent.putExtra("lat",lat);
startActivity(intent);
//startActivity(new Intent(this, Search.class));
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void SetListViewAdapter(ArrayList<HashMap<String, String>> daftar) {
adapter = new PromotionListAdapter(activity, daftar);
list.setAdapter(adapter);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == 100) {
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
class Activity extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Curve.this);
pDialog.setMessage("Please Wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
JSONObject json = jParser.makeHttpRequest(url_daftar_promotion, "GET",params);
Log.d("All Products: ", json.toString());
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
daftar_promotion = json.getJSONArray(TAG_DAFTAR_PROMOTION);
for (int i = 0; i < daftar_promotion.length();i++){
JSONObject c = daftar_promotion.getJSONObject(i);
String PromoID = c.getString(TAG_ID_PROMO);
String PromoName = c.getString(TAG_NAMA_PROMO);
String pat = "http://10.0.2.2/webserver_maaug/";
String PromoImage = pat + c.getString(TAG_LINK_IMAGE_PROMO);
String PromoDesc = c.getString(TAG_DESC_PROMO);
String PromoCate = c.getString(TAG_CATE_PROMO);
String PromoDateStart = c.getString(TAG_DATES_PROMO);
String PromoDateEnd = c.getString(TAG_DATEE_PROMO);
String PromoContact = c.getString(TAG_CONT_PROMO);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_ID_PROMO, PromoID);
map.put(TAG_NAMA_PROMO, PromoName);
map.put(TAG_LINK_IMAGE_PROMO, PromoImage);
map.put(TAG_DESC_PROMO, PromoDesc);
map.put(TAG_CATE_PROMO, PromoCate);
map.put(TAG_DATES_PROMO, PromoDateStart);
map.put(TAG_DATEE_PROMO, PromoDateEnd);
map.put(TAG_CONT_PROMO, PromoContact);
DaftarPromotion.add(map);
}
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
SetListViewAdapter(DaftarPromotion);
}
});
}
}
}
and this is my custom adapter, it is a very simple one, without an object class of it's own
package lbs.promotion;
import java.util.ArrayList;
import java.util.HashMap;
import com.javacodegeeks.android.lbs.Curve;
import com.javacodegeeks.android.lbs.R;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.TextView;
public class PromotionListAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater = null;
public ImageLoader imageLoader;
public PromotionListAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data = d;
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_list_promotion, null);
TextView PromoID = (TextView) vi.findViewById(R.id.PromoID);
TextView PromoName = (TextView) vi.findViewById(R.id.PromoName);
TextView PromoImage = (TextView) vi.findViewById(R.id.PromoImage);
TextView PromoDesc = (TextView) vi.findViewById(R.id.PromoDesc);
TextView PromoCate = (TextView) vi.findViewById(R.id.PromoCate);
TextView PromoContact = (TextView) vi.findViewById(R.id.PromoContact);
TextView PromoDateStart = (TextView) vi.findViewById(R.id.PromoDateStart);
TextView PromoDateEnd = (TextView) vi.findViewById(R.id.PromoDateEnd);
ImageView thumb_image = (ImageView) vi.findViewById(R.id.image_promo);
HashMap<String, String> daftar_promotion = new HashMap<String, String>();
daftar_promotion = data.get(position);
PromoID.setText(daftar_promotion.get(Curve.TAG_ID_PROMO));
PromoName.setText(daftar_promotion.get(Curve.TAG_NAMA_PROMO));
PromoImage.setText(daftar_promotion.get(Curve.TAG_LINK_IMAGE_PROMO));
PromoDesc.setText(daftar_promotion.get(Curve.TAG_DESC_PROMO));
PromoCate.setText(daftar_promotion.get(Curve.TAG_CATE_PROMO));
PromoContact.setText(daftar_promotion.get(Curve.TAG_CONT_PROMO));
PromoDateStart.setText(daftar_promotion.get(Curve.TAG_DATES_PROMO));
PromoDateEnd.setText(daftar_promotion.get(Curve.TAG_DATEE_PROMO));
imageLoader.DisplayImage(daftar_promotion.get(Curve.TAG_LINK_IMAGE_PROMO),thumb_image);
return vi;
}
}
here is my layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<!-- Editext for Search -->
<EditText android:id="#+id/search_box"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="type to search"
android:inputType="text"
android:maxLines="1"/>
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:divider="#040404"
android:dividerHeight="1dp"
android:listSelector="#drawable/list_selector" />
</LinearLayout>
how do i get the getfilter() function working? or is there any simpler way to implement filtering in my listview? i want to filter based on my PromoName
A Filter has two major components, the performFiltering(CharSequence) method and the publishResults(CharSequence, FilterResults) method. In your PromotionListAdapter, you'll need to implement the Filterable interface then Override the getFilter() method to return a new Filter that has these methods implemented.
The performFiltering(CharSequence) method is where you'll do the bulk of your work. The CharSequence argument is the data which you're filtering on. Here, you'll first want to determine if the list should even be filtered as the base case. Once you've decided to perform the filtering, create a new ArrayList for your filtered dataset (in your case, a new ArrayList>), and loop through your complete set of list items, adding the values that match the filter to your new ArrayList.
The return type for the performFiltering method is FilterResults. FilterResults is a simple object with two variables, int count and Object results. Once performFiltering has created the new ArrayList with the filtered data, create a new FilterResults, setting your new ArrayList as results and the size of that ArrayList as count.
The publishResults(CharSequence, FilterResults) method is called after performFiltering() returns. The CharSequence parameter is the same String you were filtering on. The FilterResults parameter is the return from performFiltering(). In this method, you'll want to set your new ArrayList as the data source for your List and then call notifyDataSetChanged() to update the UI.
In order to implement this, I've had success when my Adapter keeps track of both the original ArrayList of data and a filtered ArrayList of what is currently being shown. Here's some boilerplate code based on your adapter that can help get you started. I've commented above important lines.
public class PromotionListAdapter extends BaseAdapter implements Filterable
{
private Activity activity;
private static LayoutInflater inflater = null;
public ImageLoader imageLoader;
//Two data sources, the original data and filtered data
private ArrayList<HashMap<String, String>> originalData;
private ArrayList<HashMap<String, String>> filteredData;
public PromotionListAdapter(Activity a, ArrayList<HashMap<String, String>> d)
{
activity = a;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader = new ImageLoader(activity.getApplicationContext());
//To start, set both data sources to the incoming data
originalData = d;
filteredData = d;
}
//For this helper method, return based on filteredData
public int getCount()
{
return filteredData.size();
}
//This should return a data object, not an int
public Object getItem(int position)
{
return filteredData.get(position);
}
public long getItemId(int position)
{
return position;
}
//The only change here is that we'll use filteredData.get(position)
//Even better would be to use getItem(position), which uses the helper method (see the getItem() method above)
public View getView(int position, View convertView, ViewGroup parent)
{
View vi = convertView;
if (convertView == null)vi = inflater.inflate(R.layout.item_list_promotion, null);
TextView PromoID = (TextView) vi.findViewById(R.id.PromoID);
TextView PromoName = (TextView) vi.findViewById(R.id.PromoName);
TextView PromoImage = (TextView) vi.findViewById(R.id.PromoImage);
TextView PromoDesc = (TextView) vi.findViewById(R.id.PromoDesc);
TextView PromoCate = (TextView) vi.findViewById(R.id.PromoCate);
TextView PromoContact = (TextView) vi.findViewById(R.id.PromoContact);
TextView PromoDateStart = (TextView) vi.findViewById(R.id.PromoDateStart);
TextView PromoDateEnd = (TextView) vi.findViewById(R.id.PromoDateEnd);
ImageView thumb_image = (ImageView) vi.findViewById(R.id.image_promo);
HashMap<String, String> daftar_promotion = new HashMap<String, String>();
//Get data from filtered Data
//This line can be replaced with:
// daftar_promotion = getItem(position);
daftar_promotion = filteredData.get(position);
PromoID.setText(daftar_promotion.get(Curve.TAG_ID_PROMO));
PromoName.setText(daftar_promotion.get(Curve.TAG_NAMA_PROMO));
PromoImage.setText(daftar_promotion.get(Curve.TAG_LINK_IMAGE_PROMO));
PromoDesc.setText(daftar_promotion.get(Curve.TAG_DESC_PROMO));
PromoCate.setText(daftar_promotion.get(Curve.TAG_CATE_PROMO));
PromoContact.setText(daftar_promotion.get(Curve.TAG_CONT_PROMO));
PromoDateStart.setText(daftar_promotion.get(Curve.TAG_DATES_PROMO));
PromoDateEnd.setText(daftar_promotion.get(Curve.TAG_DATEE_PROMO));
imageLoader.DisplayImage(daftar_promotion.get(Curve.TAG_LINK_IMAGE_PROMO),thumb_image);
return vi;
}
#Override
public Filter getFilter()
{
return new Filter()
{
#Override
protected FilterResults performFiltering(CharSequence charSequence)
{
FilterResults results = new FilterResults();
//If there's nothing to filter on, return the original data for your list
if(charSequence == null || charSequence.length() == 0)
{
results.values = originalData;
results.count = originalData.size();
}
else
{
ArrayList<HashMap<String,String>> filterResultsData = new ArrayList<HashMap<String,String>>();
for(HashMap<String,String> data : originalData)
{
//In this loop, you'll filter through originalData and compare each item to charSequence.
//If you find a match, add it to your new ArrayList
//I'm not sure how you're going to do comparison, so you'll need to fill out this conditional
if(data matches your filter criteria)
{
filterResultsData.add(data);
}
}
results.values = filterResultsData;
results.count = filteredResultsData.size();
}
return results;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults)
{
filteredData = (ArrayList<HashMap<String,String>>)filterResults.values;
notifyDataSetChanged();
}
};
}
}
And there you have it! As far as I can tell, you've already implemented the TextWatcher for your inputText EditText set up properly, so adding the getFilter() method and making a few other minor changes to your Adapter should lead you to a solution. I believe you can also create a member variable on your Adapter for your Filter, so you're not creating a new instance of the class each time getFilter() is called, but I copy/pasted this from a previous project of mine and am sure it works this way. Play with it and see what works for you! Hope this helps! And please do comment if you need anything clarified.
you adapter needs to implement Filterable .
for more info about this (and about listView) , watch the video "the world of listView"
here's a sample code:
http://codetheory.in/android-filters/

Why listview is not refresh after come back to the foreground?

I'm trying to do a chat application with two activities. On the first plan is a short list containing the last sent message in each row. A second activity contain all conversation. I use socket.io and my problem is that, when I click back button and then I come back to my app notifyDataSetChanged() stops working. My app recevie a messages from dialog box from a website which a cooperates with android app. In console log I see that a messages from a website are received and onTaskComplete() method is called but a listview is not refreshing. I read that an adapter loses a reference to a listview after restart an activity but how to see in my code I create a new adapter in onResume() method. I don't understand what I do wrong?
While if I will throw out beyond the condition "mSocket.on("message", onMessage);" then a listview is refresh after come back to app but a messages are multiple as many times as there were returns.
below is my code, please help!
MainActivity:
package com.example.seadog.fb_dialog;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import io.socket.client.Socket;
import io.socket.emitter.Emitter;
public class MainActivity extends Activity implements MyListener {
public ListView listView;
public MyBaseAdapter adapter;
public TextView textView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*
* Get Socket.io Object
*/
SocketIO socketIo = new SocketIO();
Socket mSocket = socketIo.getSocket(); // get socket
Integer id = socketIo.getId(); // get Website ID
if(mSocket == null) {
socketIo.Connection();
mSocket = socketIo.getSocket();
mSocket.on("message", onMessage);
}
listView = (ListView) findViewById(R.id.listView);
/*
* OnItemClickListener
*/
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this, Conversation.class);
intent.putExtra("item", position);
startActivity(intent);
TextView textView = (TextView) view.findViewById(R.id.descitem);
textView.setTypeface(null, Typeface.NORMAL);
}
});
textView = (TextView) findViewById(R.id.count);
}
private Emitter.Listener onMessage = new Emitter.Listener() {
/*
* Message Listener
*/
#Override
public void call(Object... args) {
Boolean isset = false;
try {
JSONObject object = (JSONObject) args[0];
String _id = object.getString("_id");
String message = object.getString("message");
JSONObject obj = new JSONObject();
obj.put("direction", "fb-lt");
obj.put("message", message);
obj.put("date", "2017-05-29T12:15:49.245Z");
for(int i = 0; i < arrayList.size(); i++){
ListData ld = (ListData) arrayList.get(i);
String id = ld.getId();
if(_id.equals(id)){
JSONArray Data = ld.getData();
Data.put(obj);
ld.setDescription(message);
arrayList.set(i, ld);
isset = true;
Log.d("LOG", message);
}
}
if(!isset) {
JSONArray jsonArray = new JSONArray();
jsonArray.put(obj);
ListData ld = new ListData();
ld.set_id(_id);
ld.setID(1);
ld.setTitle("Klient:");
ld.setDescription(message);
ld.setData(jsonArray);
arrayList.add(ld);
}
onTaskComplete();
} catch (JSONException e) {
e.printStackTrace();
}
}
};
public void onResume() {
super.onResume();
ArrayList clone = (ArrayList) arrayList.clone();
arrayList.clear();
arrayList.addAll(clone);
adapter = new MyBaseAdapter(this, arrayList);
listView.setAdapter(adapter);
}
#Override
public void onTaskComplete() {
runOnUiThread(new Runnable() {
#Override
public void run () {
Log.d("LOG:","refresh");
adapter.notifyDataSetChanged();
}
});
}
}
Interface MyListener:
package com.example.seadog.fb_dialog;
import java.util.ArrayList;
public interface MyListener {
ArrayList arrayList = new ArrayList();
void onTaskComplete();
}
If I remember well, when you open a new activity in android, that's something separate from the previous one.
When you press the back button, it just kill the activity you were in and show the previous activity.
Maybe you can try to do what you need when back is pressed in this :
#Override
public void onBackPressed()
{
//Do your things here
}
Hope I helped.

How to fetch data from MYSQL database and display it on the application?

I want to fetch data from the database using Json I tried a lot but the problem i am facing is that the data is not displaying into the screen.
Data is fetching perfectly but it is not displaying into the screen.
stuck in this please help me out..
Here, The Complete Code:
Order.java
package com.example.sachin.splashlogin;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class Order extends Fragment {
public Order(){};
JSONObject jsonobject;
JSONArray ownerObj;
ListView listview;
ListViewAdapter3 listadapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
String uid = "0";
SessionManager session;
private static String url_visitor = "http://10.0.2.2/portal/fetchinforder.php";
JSONParser jParser = new JSONParser();
ArrayList<String> itemwod = new ArrayList<String>();
ArrayList<String> itemorder = new ArrayList<String>();
ArrayList<String> item_remark= new ArrayList<String>();
//ArrayList<String> o_username= new ArrayList<String>();
View view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
// don't look at this layout it's just a listView to show how to handle the keyboard
View view = inflater.inflate(R.layout.activity_order, container, false);
getActivity().setTitle("Visit");
// listview = (ListView) view.findViewById(R.id.lvvisit);
session = new SessionManager(getActivity());
HashMap<String, String> user = session.getUserDetails();
uid = user.get(SessionManager.KEY_ID);
new DownloadJSON().execute();
return view;
}
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(getActivity());
mProgressDialog.setTitle("Please Wait");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... args) {
// Create an array
try {
arraylist = new ArrayList<HashMap<String, String>>();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("o_username", uid));
JSONObject json = jParser.makeHttpRequest(url_visitor, "GET", params);
int success1 = Integer.parseInt(json.getString("success4"));
Log.d("success4", json.toString());
if (success1 == 0) {
Snackbar.make(view, "Not Data Found", Snackbar.LENGTH_LONG).show();
}
if (success1 == 1) {
ownerObj = json.getJSONArray("Ordera");
// arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
// Locate the array name in JSON
// jsonarray = jsonobject.getJSONArray("images");
// JSONObject own = ownerObj.getJSONObject(0);
// display product data in EditText
// uid = own.getString("user_id");
for (int i = 0; i < ownerObj.length(); i++) {
// HashMap<String, String> map = new HashMap<String, String>();
jsonobject = ownerObj.getJSONObject(i);
// Retrive JSON Objects
if (jsonobject.getString("o_username").equalsIgnoreCase(uid)) {
itemwod.add(jsonobject.getString("itm_wod"));
itemorder.add(jsonobject.getString("itm_order"));
item_remark.add(jsonobject.getString("itm_remark"));
// o_username.add(jsonobject.getString("o_username"));
}
}
}
}
catch(Exception e)
{
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
listview = (ListView)getActivity().findViewById(R.id.list123);
listadapter = new ListViewAdapter3(getActivity(), itemwod,item_remark,itemorder);
// Set the adapter to the ListView
listview.setAdapter(listadapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
}
Here,ListviewAdapter3.java
package com.example.sachin.splashlogin;
import android.app.AlertDialog;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashMap;
public class ListViewAdapter3 extends BaseAdapter {
Context cntx;
AlertDialog.Builder alertDialogBuilder;
int loader = R.drawable.ic_menu_gallery;
ArrayList<String> itemwod = new ArrayList<String>();
ArrayList<String> itemorder = new ArrayList<String>();
ArrayList<String> item_remark= new ArrayList<String>();
// ArrayList<String> item_date = new ArrayList<String>();
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
HashMap<String, String> resultp = new HashMap<String, String>();
public ListViewAdapter3(Context context,
ArrayList<String> itm_wod,
ArrayList<String> itm_order,
ArrayList<String> itm_remark
) {
// TODO Auto-generated constructor stub
cntx = context;
itemwod = itm_wod;
itemorder = itm_order;
item_remark = itm_remark;
alertDialogBuilder = new AlertDialog.Builder(context);
alertDialogBuilder.setMessage("Do You Want To Call....");
}
#Override
public int getCount() {
return item_remark.size();
}
#Override
public Object getItem(int position) {
return item_remark.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#SuppressWarnings("deprecation")
public View getView(final int position, View convertView, ViewGroup parent) {
TextView lvtaskname,lvtaskdetails,lvtaskremark,lvtaskdate;
inflater = (LayoutInflater) cntx
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LayoutInflater inflater = LayoutInflater.from(cntx);
convertView = inflater.inflate(R.layout.raw_visit, parent,
false);
lvtaskname= (TextView) convertView.findViewById(R.id.lvtaskname);
lvtaskdetails = (TextView) convertView.findViewById(R.id.lvtaskdetails);
lvtaskremark = (TextView) convertView.findViewById(R.id.lvtaskremark);
//lvtaskdate = (TextView) convertView.findViewById(R.id.lvtaskdate);
lvtaskname.setText(itemwod.get(position));
lvtaskdetails.setText(itemorder.get(position));
lvtaskremark.setText(item_remark.get(position));
//lvtaskdate.setText(item_date.get(position));
return convertView;
}
}
I created 1 raw_order.xml,activity_order.xml
Here, Logcat in this the data is fetching proper.
09-21 04:49:42.280 8560-9051/com.example.sachin.splashlogin D/Parameters: http://10.0.2.2/portal/fetchinforder.php?o_username=JAYESHBHAI
09-21 04:49:42.633 8560-8570/com.example.sachin.splashlogin W/art: Suspending all threads took: 43.318ms
09-21 04:49:42.683 8560-8574/com.example.sachin.splashlogin I/art: Background sticky concurrent mark sweep GC freed 16412(1769KB) AllocSpace objects, 1(20KB) LOS objects, 3% free, 51MB/53MB, paused 18.379ms total 126.498ms
09-21 04:49:42.740 8560-8574/com.example.sachin.splashlogin W/art: Suspending all threads took: 55.554ms
09-21 04:49:42.783 8560-9051/com.example.sachin.splashlogin D/reader: org.apache.http.conn.EofSensorInputStream#d7f027a
09-21 04:49:42.789 8560-9051/com.example.sachin.splashlogin D/P: [o_username=JAYESHBHAI]
09-21 04:49:42.789 8560-9051/com.example.sachin.splashlogin E/Json Object:: {"Ordera":[{"o_parties":"ADCOM ENTERPRISE","o_product":"CTRLV4SWhite","o_remark":"today visit","o_date":"09\/21\/2016","o_username":"JAYESHBHAI"}],"success":1,"o_username":"JAYESHBHAI","date":"09\/21\/2016","success4":1}
09-21 04:49:42.789 8560-9051/com.example.sachin.splashlogin D/success4: {"Ordera":[{"o_parties":"ADCOM ENTERPRISE","o_product":"CTRLV4SWhite","o_remark":"today visit","o_date":"09\/21\/2016","o_username":"JAYESHBHAI"}],"success":1,"o_username":"JAYESHBHAI","date":"09\/21\/2016","success4":1}
09-21 04:49:42.921 8560-8981/com.example.sachin.splashlogin E/Surface: getSlotFromBufferLocked: unknown buffer: 0xa1da1590
I don't understand what's wrong in this?? please Help me out from this..
I think your problem is in this line:
if (jsonobject.getString("o_username").equalsIgnoreCase(uid)) {
Your 'uid' is "0"
String uid = "0";
So your if statement returning false.
I think you have forgot to setText-->
lvtaskname.setText(itemwod.get(position)); -- here you not getName please check
// lvtaskname.setText(itemwod.get(position).getName); --- check this
lvtaskdetails.setText(itemorder.get(position));
lvtaskremark.setText(item_remark.get(position));
//lvtaskdate.setText(item_date.get(position));
return convertView;

Load image in listview

I have an application which uses json to get links and texts and now i want to load the image from the downloaded url (by json) in the Listview.
I can load texts in the listview but i can load images!
PLZ help me i have spended 2 days for this and searched,... but no chance! I really need your help! anyone can help me i'll make a great thanks to him in application. PLZZZ help me.
MY CODE :
package rappage.rapfarsi.media.appteam.rapnews;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import rappage.rapfarsi.media.appteam.Articlectivity;
import rappage.rapfarsi.media.appteam.Main;
import rappage.rapfarsi.media.appteam.R;
import rappage.rapfarsi.media.appteam.json.JSONParser;
public class tab2 extends ListFragment {
static final String url_all_products = "http://normaluse.persianrapapp021.ml/article/get_all_products.php";
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
final String TAG_SUCCESS = "success";
final String TAG_RAPNEWS = "article";
final String TAG_PID = "pid";
final String TAG_TITLE = "title";
final String TAG_PIC = "pic";
final String TAG_WRITER = "writer";
Bitmap bmp;
// JSON Node names
// products JSONArray
JSONArray rapnews = null;
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.tab_2, container, false);
final View rootView = super.onCreateView(inflater, container, savedInstanceState);
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
/**
* Background Async Task to Load all product by making HTTP Request
* */
try {
new LoadAllProducts().execute();
}catch (Exception e)
{
final AlertDialog.Builder dlgAlert = new AlertDialog.Builder(getActivity());
dlgAlert.setMessage("لطفا اینترنت خودرا چک کنید! یا ممکن است سرور از دسترس خارج شده باشد ، برای اخبار اپدیت و مشکلات به ویکی رپ مراجعه کنید!");
dlgAlert.setTitle("Connection Error!");
dlgAlert.setNegativeButton("باشه گرفتم", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
startActivity(new Intent(getActivity() , Main.class));
}
});
dlgAlert.create().show();
}
return v;
}
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
*/
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading, 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
rapnews = json.getJSONArray(TAG_RAPNEWS);
// looping through All Products
for (int i = 0; i < 11; i++) {
JSONObject c = rapnews.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_TITLE);
String pic = c.getString(TAG_PIC);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_TITLE, name);
map.put(TAG_PIC, pic);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getActivity().getApplicationContext(),
Main.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 UI from Background Thread
getActivity().runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
getActivity(), productsList,
R.layout.list_item, new String[]{TAG_PID,
TAG_TITLE},
new int[]{R.id.pid, R.id.txttitle}
);
setListAdapter(adapter);
}
});
}
}
public void onListItemClick(ListView l, View v, int position, long id) {
Toast.makeText(getActivity().getApplicationContext(), "Loading, Please Wait...",
Toast.LENGTH_LONG).show();
String pid = ((TextView) v.findViewById(R.id.pid)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getActivity(),Articlectivity.class);
// sending pid to next activity
in.putExtra(TAG_PID, pid);
// starting new activity and expecting some response back
startActivity(in);
}
}
I WANT TO LOAD IMAGES ATLEAST IN THIS BASE... OR ANYOTHER THING...
There are lots of image loading library available for android.
Have a look at these
https://github.com/square/picasso
https://github.com/nostra13/Android-Universal-Image-Loader
https://code.google.com/p/android-query/wiki/ImageLoading
https://android.googlesource.com/platform/frameworks/volley
https://github.com/koush/UrlImageViewHelper
https://github.com/novoda/image-loader
You can use library by square called Picasso
Here is the documentation.
Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);
Here is a custom adapter for a listview having 2 texts and an image
public class CustomArrayAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] values1;
private final String[] values2;
public CustomArrayAdapter(Context context, String[] values1, String[] values2) {
super(context, R.layout.some_layout, values1);
this.context = context;
this.values1 = values1;
this.values2 = values2;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
// LayoutInflater inflater = LayoutInflater.from(context);
// View rowView = inflater.inflate(R.layout.some_layout, null);
View rowView = convertView;
if (rowView == null) {
LayoutInflater inflater = LayoutInflater.from(context);
rowView = inflater.inflate(R.layout.some_layout, null);
holder = new ViewHolder();
holder.text1 = (TextView) rowView.findViewById(R.id.firstLine);
holder.text2 = (TextView) rowView.findViewById(R.id.secondLine);
holder.img = (ImageView) rowView.findViewById(R.id.imageView);
rowView.setTag(holder);
}
else {
holder=(ViewHolder)rowView.getTag();
}
holder.text1.setText(values1[position]);
holder.text2.setText(values2[position]);
Picasso.with(rowView.getContext()).load("http://www.9ori.com/store/media/images/8ab579a656.jpg").into(holder.img);
// if (position%2==0) {
// holder.img.setImageResource(R.drawable.correct);
// }
// else {
// holder.img.setImageResource(R.drawable.incorrect);
// }
return rowView;
}
public static class ViewHolder {
public TextView text1, text2;
public ImageView img;
}
}

Use ListActivity inside a Fragment

Here are two codes that I wanted to combine and make it work, I have this navigation drawer which I wanted to put my post comment post inside and enable it to run.
To enable it to run, I will need to make the listActivity runs inside a fragments. It's not possible to extend two activities, so I would like the community to take a look at my code if it can be connect and make it works. This code I got it online.
The HomeFragment.java
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class HomeFragment extends Fragment {
public HomeFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container,
false);
return rootView;
}
ReadComments.java
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class ReadComments extends ListActivity {
private static final String READ_COMMENTS_URL = "http://www.xxxx.com/webservice/comments.php";
private static final String TAG_MESSAGE = "message";
private static final String TAG_POSTS = "posts";
private static final String TAG_POST_ID = "post_id";
private static final String TAG_SUCCESS = "success";
private static final String TAG_TITLE = "title";
private static final String TAG_USERNAME = "username";
private JSONArray mComments = null;
private ArrayList<HashMap<String, String>> mCommentList;
private ProgressDialog pDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// note that use read_comments.xml instead of our single_post.xml
setContentView(R.layout.fragment_home);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
// loading the comments via AsyncTask
new LoadComments().execute();
}
public void addComment(View v) {
Intent i = new Intent(ReadComments.this, AddComment.class);
startActivity(i);
}
/**
* Retrieves recent post data from the server.
*/
public void updateJSONdata() {
// Instantiate the arraylist to contain all the JSON data.
// we are going to use a bunch of key-value pairs, referring
// to the json element name, and the content, for example,
// message it the tag, and "I'm awesome" as the content..
mCommentList = new ArrayList<HashMap<String, String>>();
// Bro, it's time to power up the J parser
JSONParser jParser = new JSONParser();
// Feed the beast our comments url, and it spits us
// back a JSON object. Boo-yeah Jerome.
JSONObject json = jParser.getJSONFromUrl(READ_COMMENTS_URL);
// when parsing JSON stuff, we should probably
// try to catch any exceptions:
try {
// I know I said we would check if "Posts were Avail." (success==1)
// before we tried to read the individual posts, but I lied...
// mComments will tell us how many "posts" or comments are
// available
mComments = json.getJSONArray(TAG_POSTS);
// looping through all posts according to the json object returned
for (int i = 0; i < mComments.length(); i++) {
JSONObject c = mComments.getJSONObject(i);
// gets the content of each tag
String title = c.getString(TAG_TITLE);
String content = c.getString(TAG_MESSAGE);
String username = c.getString(TAG_USERNAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_TITLE, title);
map.put(TAG_MESSAGE, content);
map.put(TAG_USERNAME, username);
// adding HashList to ArrayList
mCommentList.add(map);
// annndddd, our JSON data is up to date same with our array
// list
}
} catch (JSONException e) {
e.printStackTrace();
}
}
/**
* Inserts the parsed data into the listview.
*/
private void updateList() {
ListAdapter adapter = new SimpleAdapter(this, mCommentList,
R.layout.single_post, new String[] { TAG_TITLE, TAG_MESSAGE,
TAG_USERNAME }, new int[] { R.id.title, R.id.message,
R.id.username });
// I shouldn't have to comment on this one:
setListAdapter(adapter);
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
}
public class LoadComments extends AsyncTask<Void, Void, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ReadComments.this);
pDialog.setMessage("Loading Comments...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected Boolean doInBackground(Void... arg0) {
updateJSONdata();
return null;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
pDialog.dismiss();
updateList();
}
}
}
Use a ListFragment for this, you can find the documentation and reference here: http://developer.android.com/reference/android/app/ListFragment.html
you can google examples (e.g: http://www.vogella.com/tutorials/AndroidListView/article.html#listactivity)

Categories

Resources