AsyncTas Implementation ListView - android

How to use asynctask to show listview from json
how to put
onPreExecute()
onPostExecute()
doInBackground()
onProgressUpdate()
MainActivity.java
list = (ListView) activity.findViewById(R.id.listView1);
ArrayList<HashMap<String, String>> followingList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(URL);
try {
// Getting Array of Following
following = json.getJSONArray(KEY_FOLLOWING);
// looping through All Following
for(int i = 0; i < following.length(); i++){
JSONObject c = following.getJSONObject(i);
// Storing each json item in variable
String nama = c.getString(KEY_NAMA);
String instansi = c.getString(KEY_INSTANSI);
String status = c.getString(KEY_STATUS);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(KEY_NAMA, nama);
map.put(KEY_INSTANSI, instansi);
map.put(KEY_STATUS, status);
// adding HashList to ArrayList
followingList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
// Getting adapter by passing xml data ArrayList
adapter1=new LazyAdapter(this, followingList);
list.setAdapter(adapter1);
How to implementation asycntask to show list view?
DashboardTask
package net.drieanto.lagidimana;
import net.drieanto.lagidimana.library.DatabaseHandler;
import net.drieanto.lagidimana.library.JSONParser;
import net.drieanto.lagidimana.library.UserFunctions;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.HashMap;
public class DashboardTask extends AsyncTask<String, Void, Integer> {
private ProgressDialog progressDialog;
private DashboardActivity activity;
ListView list1;
LazyAdapter adapter1;
private ListView list;
// All static variables
static final String URL = "http://git.drieanto.net/LagiDimanaAPI/index.php/user/get_following/XX3";
// JSON node keys
private int responseCode = 0;
static final String KEY_FOLLOWING = "following";
static final String KEY_NAMA = "nama"; // parent node
static final String KEY_INSTANSI = "instansi";
static final String KEY_STATUS = "status";
private static String KEY_SUCCESS = "success";
private static String KEY_ERROR = "error";
// following JSONArray
JSONArray following = null;
public DashboardTask(DashboardActivity activity,
ProgressDialog progressDialog) {
this.activity = activity;
this.progressDialog = progressDialog;
}
#Override
protected void onPreExecute() {
progressDialog.show();
}
#Override
protected Integer doInBackground(String... arg0) {
// check for login response
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(URL);
try {
if (json.getString(KEY_SUCCESS) != null) {
String res = json.getString(KEY_SUCCESS);
if (Integer.parseInt(res) == 1) {
responseCode = 1;
} else {
responseCode = 0;
// Error in login
}
}
} catch (NullPointerException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return responseCode;
}
#Override
protected void onPostExecute(Integer responseCode) {
if (responseCode == 1) {
progressDialog.dismiss();
ArrayList<HashMap<String, String>> followingList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(URL);
try {
// Getting Array of Following
following = json.getJSONArray(KEY_FOLLOWING);
// looping through All Following
for (int i = 0; i < following.length(); i++) {
JSONObject c = following.getJSONObject(i);
// Storing each json item in variable
String nama = c.getString(KEY_NAMA);
String instansi = c.getString(KEY_INSTANSI);
String status = c.getString(KEY_STATUS);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(KEY_NAMA, nama);
map.put(KEY_INSTANSI, instansi);
map.put(KEY_STATUS, status);
// adding HashList to ArrayList
followingList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
// Getting adapter by passing xml data ArrayList
adapter1 = new LazyAdapter(activity, followingList);
list.setAdapter(adapter1);
} else {
progressDialog.dismiss();
activity.showDashboardError(responseCode);
}
}
}
But contain error whats wrong?

You can use the following
ProgressDialog pd;
LazyAdapter adapter1;
ListView list;
String URL;
HashMap<String, String> map = new HashMap<String, String>();
ArrayList<HashMap<String, String>> followingList = new ArrayList<HashMap<String, String>>();
In your activity onCreate()
setContentView(R.layout.activity_main);
list = (ListView)findViewById(R.id.listView1);
pd = new ProgressDialog(ActivityName.this);
pd.setTitle("Processing...");
URL ="your url";
new TheTask().execute();
Define Asynctask as a inner class in your activity class
class extends AsyncTask<Void,Void,Void>
{
#Override
protected void onPreExecute() {
super.onPreExecute();
pd.show();
}
#Override
protected Void doInBackground(Void... params) {
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(URL);
try {
// Getting Array of Following
following = json.getJSONArray(KEY_FOLLOWING);
// looping through All Following
for(int i = 0; i < following.length(); i++){
JSONObject c = following.getJSONObject(i);
// Storing each json item in variable
String nama = c.getString(KEY_NAMA);
String instansi = c.getString(KEY_INSTANSI);
String status = c.getString(KEY_STATUS)
// adding each child node to HashMap key => value
map.put(KEY_NAMA, nama);
map.put(KEY_INSTANSI, instansi);
map.put(KEY_STATUS, status);
// adding HashList to ArrayList
followingList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
pd.dismiss();
adapter1=new LazyAdapter(ActivityName.this, followingList);
list.setAdapter(adapter1);
}
}
Exaplanation
AsyncTask is invoked on the UI thread.
onPreExecute() invoked on UI Thread. display progress dialog
doInBackground() invoked on the background thread. do some operation. Do not update UI here
OnPostExecute() invoked on UI thread. dismiss dialog and update ui here.
For more info check the doc
http://developer.android.com/reference/android/os/AsyncTask.html

Related

Progress dialog does not dismiss if i scroll faster in my listview

If i scroll faster my progress dialog does not dismiss and stays on the screen for infinite time.Any help? Tried a lot of things but it still remains there. Is there any way i can dismiss it. I guess the dismis() function is not called in onPostExecute().
Code
package com.company.napp;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.widget.AbsListView;
import android.widget.ListView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class MainActivity extends Activity {
// Declare Variables
ArrayList<HashMap<String, String>> arraylist1;
int page=1;
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String TITLE = "title";
static String ADDRESS = "address";
static String COUNTRY = "country";
static String IMAGE = "image";
static String SERVICETYPE="serviceType";
static String PHNUM="phnum";
static String DESCRIPTION="description";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview_main);
// Execute DownloadJSON AsyncTask
new DownloadJSON().execute();
listview = (ListView) findViewById(R.id.listview);
listview.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// TODO Auto-generated method stub
int threshold = 1;
int count = listview.getCount();
System.out.println("\nLast visible = "+listview.getLastVisiblePosition()+"\nCount = "+count);
if (scrollState == SCROLL_STATE_IDLE) {
if (listview.getLastVisiblePosition()+1 > count-1) {
// Execute LoadMoreDataTask AsyncTask
new LoadMoreDataTask().execute();
}
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
// TODO Auto-generated method stub
}
});
}
//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("Napp");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
mProgressDialog.setCanceledOnTouchOutside(false);
//mProgressDialog.getWindow().setGravity(Gravity.BOTTOM);
}
#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://54.169.88.65/events/TA/JsonTA.php?page=1");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("Contacts");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
String t, a, d, s;
t = jsonobject.getString("title");
t = t.replaceAll("\\n", "");
//t="\n"+t;
a = jsonobject.getString("address");
a = a.replaceAll("\\n", "");
d = jsonobject.getString("description");
d = d.replaceAll("\\n", "");
s = jsonobject.getString("serviceType");
s = s.replaceAll("\\n", "");
//s=s+"\n";
map.put("title", t);
map.put("address", a);
map.put("country", jsonobject.getString("country"));
map.put("image", jsonobject.getString("image"));
map.put("serviceType", s);
map.put("phnum", jsonobject.getString("phnum"));
map.put("description", d);
// 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();
}
}
private class LoadMoreDataTask extends AsyncTask <Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(MainActivity.this);
// Set progressdialog title
//mProgressDialog.setTitle("Napp");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
//Show progressdialog
mProgressDialog.show();
mProgressDialog.setCanceledOnTouchOutside(false);
//mProgressDialog.getWindow().setGravity(Gravity.BOTTOM);
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
page+=1;
//arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions.getJSONfromURL("http://54.169.88.65/events/TA/JsonTA.php?page="+page);
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("Contacts");
arraylist1 = new ArrayList<HashMap<String, String>>();
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
String t,a,d,s;
t=jsonobject.getString("title");
t=t.replaceAll("\\n", "");
//t="\n"+t;
a=jsonobject.getString("address");
a=a.replaceAll("\\n","");
d=jsonobject.getString("description");
d=d.replaceAll("\\n","");
s=jsonobject.getString("serviceType");
s=s.replaceAll("\\n","");
//s=s+"\n";
map.put("title",t);
map.put("address",a);
map.put("country", jsonobject.getString("country"));
map.put("image", jsonobject.getString("image"));
map.put("serviceType",s);
map.put("phnum",jsonobject.getString("phnum"));
map.put("description",d);
// Set the JSON Objects into the array
arraylist1.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Set the JSON Objects into the array
arraylist.addAll(arraylist1);
//locate listview last item
int position =listview.getLastVisiblePosition();
adapter = new ListViewAdapter(MainActivity.this, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
//show the lastest retrieved results on the top
listview.setSelectionFromTop(position,0);
adapter.notifyDataSetChanged();
// Close the progressdialog
mProgressDialog.dismiss();
}
}
}
Looks like before the first call of the Asynctask is completed, you are making a call to it again. So the best solution would be to not create a progress dialog everytime you create the task but check if the dialog is already running and handle accordingly. There are multiple instances of the progress dialog getting created and all are not being destroyed

Android Lazy Loading List - retrieve images dynamically (MySQL & JSON)

I am new to Android.
I want to get the values of drk_image or TAG_DRK_IMAGE from the HashMap and store it to private String[ ] drinkImages. Is this possible?
Code:
Lazy_ListItem.java
public class Lazy_ListItem extends Activity {
ListView list;
Lazy_Adapter adapter;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> drinksList;
// url to get all drinks list
private static String url_all_drinks = "http://10.0.2.2/restosnapp/get_all_products.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_DRINKS = "drinks";
private static final String TAG_DRK_IMAGE = "drk_image";
// drinks JSONArray
JSONArray drinks = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_item);
list = (ListView) findViewById(R.id.list);
adapter = new Lazy_Adapter(this, drinkImages);
list.setAdapter(adapter);
}
#Override
public void onDestroy() {
list.setAdapter(null);
super.onDestroy();
}
/**
* Background Async Task to Load all drinks by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* getting All drinks 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_drinks, "GET",
params);
// Check your log cat for JSON response
Log.d("All Drinks: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// drinks found
// Getting Array of Drinks
drinks = json.getJSONArray(TAG_DRINKS);
// looping through All Drinks
for (int i = 0; i < drinks.length(); i++) {
JSONObject c = drinks.getJSONObject(i);
// Storing each json item in variable
String drk_image = c.getString(TAG_DRK_IMAGE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_DRK_IMAGE, drk_image);
// adding HashList to ArrayList
drinksList.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
private String[] drinkImages = {
"http://webitprojects.com/restaurant/images/drinks/drk_coffee.jpg",
"http://webitprojects.com/restaurant/images/drinks/drk_calamansijuice.jpg",
"http://webitprojects.com/restaurant/images/drinks/drk_blackgulaman.jpg",
"http://webitprojects.com/restaurant/images/drinks/drk_avocadoshake.jpg",
"http://webitprojects.com/restaurant/images/drinks/drk_durianshake.jpg" }; }
The value of String[ ] drinkImages must be replaced with values from the HashMap (from the database) and so I can pass it to Lazy_Adapter.
I want to get the values from the database instead of just declaring it like this:
private String[] drinkImages = {
"http://webitprojects.com/restaurant/images/drinks/drk_coffee.jpg",
"http://webitprojects.com/restaurant/images/drinks/drk_calamansijuice.jpg",
"http://webitprojects.com/restaurant/images/drinks/drk_blackgulaman.jpg",
"http://webitprojects.com/restaurant/images/drinks/drk_avocadoshake.jpg",
"http://webitprojects.com/restaurant/images/drinks/drk_durianshake.jpg" };
Lazy_Adapter.java
public class Lazy_Adapter extends BaseAdapter {
String drk_name, drk_desc, drk_price, drk_avail;
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> drinksList;
// url to get all drinks list
private static String url_all_drinks = "http://10.0.2.2/restosnapp/get_all_products.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_DRINKS = "drinks";
private static final String TAG_RID = "rid";
private static final String TAG_DRK_ID = "drk_id";
private static final String TAG_DRK_NAME = "drk_name";
private static final String TAG_DRK_DESC = "drk_desc";
private static final String TAG_DRK_PRICE = "drk_price";
private static final String TAG_DRK_AVAIL = "drk_avail";
private static final String TAG_DRK_IMAGE = "drk_image";
// drinks JSONArray
JSONArray drinks = null;
private Activity activity;
private String[] data;
private static LayoutInflater inflater = null;
public Lazy_ImageLoader imageLoader;
public Lazy_Adapter(Activity a, String[] d) {
activity = a;
data = d;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader = new Lazy_ImageLoader(activity.getApplicationContext());
// Hashmap for ListView
drinksList = new ArrayList<HashMap<String, String>>();
// Loading drinks in Background Thread
new LoadAllProducts().execute();
}
public int getCount() {
return data.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
// ///
/**
* Background Async Task to Load all drinks by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* getting All drinks 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_drinks, "GET",
params);
// Check your log cat for JSON response
Log.d("All Drinks: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// drinks found
// Getting Array of Drinks
drinks = json.getJSONArray(TAG_DRINKS);
// looping through All Drinks
for (int i = 0; i < drinks.length(); i++) {
JSONObject c = drinks.getJSONObject(i);
// Storing each json item in variable
drk_name = c.getString(TAG_DRK_NAME);
drk_desc = c.getString(TAG_DRK_DESC);
drk_price = c.getString(TAG_DRK_PRICE);
drk_avail = c.getString(TAG_DRK_AVAIL);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_DRK_NAME, drk_name);
map.put(TAG_DRK_DESC, drk_desc);
map.put(TAG_DRK_PRICE, drk_price);
map.put(TAG_DRK_AVAIL, drk_avail);
// adding HashList to ArrayList
drinksList.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
#SuppressWarnings("unused")
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.item, null);
for (Map<String, String> menuItem : drinksList) {
ImageView image = (ImageView) vi.findViewById(R.id.image);
imageLoader.DisplayImage(data[position], image);
TextView tvMenuName = (TextView) vi.findViewById(R.id.tvMenuName);
tvMenuName.setText(drinksList.get(position).get(TAG_DRK_NAME));
TextView tvMenuDesc = (TextView) vi.findViewById(R.id.tvMenuDesc);
tvMenuDesc.setText(drinksList.get(position).get(TAG_DRK_DESC));
TextView tvMenuPrice = (TextView) vi.findViewById(R.id.tvMenuPrice);
tvMenuPrice.setText("P"
+ drinksList.get(position).get(TAG_DRK_PRICE));
TextView tvMenuAvail = (TextView) vi.findViewById(R.id.tvMenuAvail);
tvMenuAvail.setText(drinksList.get(position).get(TAG_DRK_AVAIL));
}
return vi;
}}
EDIT:
Output:
This is the output if I have declared private String[] drinkImages. I am hoping to get the same output when getting it from the database.
Emulator Screenshot
Database Screenshot
I am doing this for my thesis. Really appreciate any help.
Thanks a lot~
Because you are using AsyncTask, maybe your task isn't finished yet.
So, you should add your adapter instance and assign it to your listview in onPostExecute method.
Please change your LazyListItem.java looklike below code:
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import android.os.AsyncTask;
import android.widget.ListView;
public class Lazy_ListItem extends Activity {
ListView list;
Lazy_Adapter adapter;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> drinksList;
// url to get all drinks list
private static String url_all_drinks = "http://10.0.2.2/restosnapp/get_all_products.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_DRINKS = "drinks";
private static final String TAG_DRK_IMAGE = "drk_image";
// Your Images Array
private String[] drinkImages;
// drinks JSONArray
JSONArray drinks = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_item);
list = (ListView) findViewById(R.id.list);
new LoadAllProducts().execute();
}
#Override
public void onDestroy() {
list.setAdapter(null);
super.onDestroy();
}
/**
* Background Async Task to Load all drinks by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* getting All drinks 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_drinks, "GET",
params);
// Check your log cat for JSON response
Log.d("All Drinks: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// drinks found
// Getting Array of Drinks
drinks = json.getJSONArray(TAG_DRINKS);
// Define Lenght for Images Array
drinkImages = new String[drinks.length()];
// looping through All Drinks
for (int i = 0; i < drinks.length(); i++) {
JSONObject c = drinks.getJSONObject(i);
// Storing each json item in variable
String drk_image = c.getString(TAG_DRK_IMAGE);
// Add image into Array
drinkImages[i] = drk_image;
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_DRK_IMAGE, drk_image);
// adding HashList to ArrayList
drinksList.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
adapter = new Lazy_Adapter(this, drinkImages);
list.setAdapter(adapter);
super.onPostExecute(result);
}
}

can't create multiple choice listview

This is my code i can't create the multiple choice mode listview.
Data is fetched by jason and set in the listview.
I want to multiple selection choice mode on the list view
public class ExamView extends ListActivity{
private ProgressDialog pDialog;
Intent activity;
// URL to get contacts JSON
// JSON Node names
private static final String TAG_USERMST = "products";
private static final String TAG_QID = "que_id";
private static final String TAG_QUE = "question";
private static final String TAG_QANS = "ans";
JSONArray products = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.user_activity_lv);
contactList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
new GetContacts().execute();
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(ExamView.this);
pDialog.setMessage("Exam Paper is downloading...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
products = jsonObj.getJSONArray(TAG_USERMST);
// looping through All Contacts
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
String queid = c.getString(TAG_QID);
String que = c.getString(TAG_QUE);
String queans = c.getString(TAG_QANS);
// tmp hashmap for single contact
HashMap<String, String> product = new HashMap<String, String>();
// adding each child node to HashMap key => value
product.put(TAG_QID,queid);
product.put(TAG_QUE, que);
product.put(TAG_QANS, queans);
// adding contact to contact list
contactList.add(product);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
ExamView.this, contactList,
R.layout.user_list_item_lbl, new String[] { TAG_QID, TAG_QUE,
TAG_QANS }, new int[] { R.id.name,
R.id.email, R.id.mobile });
setListAdapter(adapter);
}
}
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
setListAdapter(new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_multiple_choice, array_sort));
Use this code its working for me.
Here array_sort is an arraylist i.e. list of all the items to be displayed.
Multiple items can be selected with this.

How can I parse a JSON object and display it in a list view?

Below is the code I am having problems with. The php file works like a charm, as you can see if you go to the value the url_all_dates variable holds. Below this class is my .xml layout file for the list_item. The app runs but doesn't display any of the dates in the database.:
public class RequestTour extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> datesList;
// url to get all dates list
private static String url_all_dates = "http://www.prayingmantesconcepts.com/androidfinal/get_all_avail_dates.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_DATES = "dates";
private static final String TAG_DATEID = "dateID";
private static final String TAG_DATE = "date";
// dates JSONArray
JSONArray dates = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dates);//put dates layout here.
// Hashmap for ListView
datesList = new ArrayList<HashMap<String, String>>();
// Loading dates in Background Thread
new LoadAllDates().execute();
// Get listview
ListView lv = getListView();
// on seleting single date
// launching Book Tour Screen
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String dateID = ((TextView) view.findViewById(R.id.dateID)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
BookTour.class);
// sending dateID to next activity
in.putExtra(TAG_DATEID, dateID);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});
}
// Response from Edit Product Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// if result code 100 is received
// means user booked a tour
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
/**
* Background Async Task to Load all dates by making HTTP Request
* */
class LoadAllDates extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(RequestTour.this);
pDialog.setMessage("Loading dates. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All dates 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_dates, "GET", params);
// Check your log cat for JSON response
Log.d("All Dates: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// found
// Getting Array of
dates = json.getJSONArray(TAG_DATES);
// looping through All Dates Available for Request
for (int i = 0; i < dates.length(); i++) {
JSONObject c = dates.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_DATEID);
String date = c.getString(TAG_DATE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_DATEID, id);
map.put(TAG_DATE, date);
// adding HashList to ArrayList
datesList.add(map);
}
} else {
// no found
// Launch Add New product Activity
Intent i = new Intent(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
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
RequestTour.this, datesList,
R.layout.list_item, new String[] { TAG_DATEID,
TAG_DATE},
new int[] { R.id.dateID, R.id.date });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
<!------------------------------------------------------------------------------------>
list_item.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" >
<!-- Date id (dateID) - will be HIDDEN - used to pass to other activity -->
<TextView
android:id="#+id/dateID"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:visibility="gone" />
<!-- Date Label -->
<TextView
android:id="#+id/date"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingTop="6dip"
android:paddingLeft="6dip"
android:textSize="17dip"
android:textStyle="bold" />
</LinearLayout>
FIRST ISSUE :
here
// no found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
Main.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
you are trying to access Ui elements from background Thread .move these lines of code to onPostExecute for Updating UI from AsyncTask after doInBackground is completed.
SECOND ISSUE :
here
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
}
});
because we are able to access UI elements in onPostExecute method of AsyncTask so no need to use runOnUiThread for updating UI elements in onPostExecute like in your case you are trying to use access ListAdapter or ListView inside runOnUiThread in onPostExecute
SOLUTION :
Change your LoadAllDates code as by using AsyncTask in proper way:
class LoadAllDates extends AsyncTask<String, String,
ArrayList<HashMap<String, String>>> {
datesList=new ArrayList<HashMap<String, String>>;
#Override
protected void onPreExecute() {
super.onPreExecute();
//YOUR CODE HERE
}
protected ArrayList<HashMap<String, String>>
doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json =
jParser.makeHttpRequest(url_all_dates, "GET", params);
// Check your log cat for JSON response
Log.d("All Dates: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// found
// Getting Array of
dates = json.getJSONArray(TAG_DATES);
// looping through All Dates Available for Request
for (int i = 0; i < dates.length(); i++) {
JSONObject c = dates.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_DATEID);
String date = c.getString(TAG_DATE);
// creating new HashMap
HashMap<String, String> map =
new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_DATEID, id);
map.put(TAG_DATE, date);
// adding HashList to ArrayList
datesList.add(map);
}
} else {
// no found
}
} catch (JSONException e) {
e.printStackTrace();
}
return ArrayList<HashMap<String, String>>;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(
ArrayList<HashMap<String, String>> file_url) {
// dismiss the dialog after getting all
pDialog.dismiss();
// updating UI from Background Thread
if(file_url.size()>0)
{
ListAdapter adapter = new SimpleAdapter(
RequestTour.this, file_url,
R.layout.list_item, new String[] { TAG_DATEID,
TAG_DATE},
new int[] { R.id.dateID, R.id.date });
// updating listview
setListAdapter(adapter);
}
else{
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
Main.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
}
}
You have to use Gson Json parsing this is a good way to parse Json object
eg:
String json1 = "[{\"contactName\":\"3\",\"contactNumber\":\"3\"},{\"contactName\":\"4\",\"contactNumber\":\"4\"}]";
Gson gson = new Gson();
Type collectionType = new TypeToken<List<ContactDetail>>(){}.getType();
List<ContactDetail> details = gson.fromJson(json1, collectionType);
Here ContactDetail class consists of String contactName and String contactNumber and their corresponding getters and setters.
Note: make List<ContactDetail> details as a public static variable in your class and
from your activity class pass this list object in your listview adapter.
here is my answer. Hope it helps. You can also visit the url i parsed:http://redsox.tcs.auckland.ac.nz/734A/CSService.svc/courses
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.ArrayList;
import java.util.zip.GZIPInputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ListActivity;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class Courses extends Activity {
ArrayList<String> items = new ArrayList<String>();
//URL requestUrl = new URL(url);
JSONArray courses = null;
//private static final String TAG_COURSES = "Courses";
static JSONObject jObj = null;
static String json = "";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.courses);
new MyTask().execute("http://redsox.tcs.auckland.ac.nz/734A/CSService.svc/courses");
}
private class MyTask extends AsyncTask<String, Void, JSONObject> {
#Override
protected JSONObject doInBackground(String... urls) {
// return loadJSON(url);
String url = new String(urls[0]);
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
//HttpPost httpPost = new HttpPost(url);
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
/*BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "UTF-8"), 8);*/
InputStream inputStream = is;
GZIPInputStream input = new GZIPInputStream(inputStream);
InputStreamReader reader = new InputStreamReader(input);
BufferedReader in = new BufferedReader(reader);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = in.readLine()) != null) {
sb.append(line);
//System.out.println(line);
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
JSONArray courses = new JSONArray(json);
//JSONArray people = new JSONArray(json);
for (int i = 0; i < courses.length(); i++) {
//System.out.println(courses.getJSONObject(i).toString());
JSONObject c = courses.getJSONObject(i);
// Storing each json item in variable
String course_id = c.getString("codeField");
String course_name = c.getString("titleField");
String course_semester = c.getString("semesterField");
items.add(course_id +"\n"+course_name+"\t"+course_semester);
/*Log.v("--", "Course:" + course_id + "\n Course Title: " + course_name
+ "\n Semesters offered: " + course_semester);*/
}
//jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
#SuppressWarnings("unchecked")
protected void onPostExecute(JSONObject json) {
ListView myListView = (ListView)findViewById(R.id.coursesList);
myListView.setAdapter(new ArrayAdapter(getApplicationContext(), android.R.layout.simple_list_item_1, items));
}
}
}

JSON Parser Low Performances

i'm reposting here in order to get some help.
I made a JSON Parser wich returns a JSONArray (in order to get info from my WebService).
My last code threw a NetworkException error (on version 2.3.3 it was long but good working) when i tested it on IceScreamSandwich..
I changed my code to stop it and try getting better perfs.. but it still not working on my ICS phone : now no more errors but a ioexcepetion : "failed to read from JSON URL"..
I show you my Activity:
public class TabNewsJSONParsingActivity extends ListActivity
{
// url to make request
private static String url = "http://developer.prixo.fr/API/GetEvents?zone=8";
//JSON names
private static final String TAG_content = "content";
private static final String TAG_zone = "zone";
private static final String TAG_id = "id";
private static final String TAG_area = "area";
private static final String TAG_title = "title";
private static final String TAG_date = "date";
private static final String TAG_author = "author";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.onglet_news);
// Hashmap for ListView
ArrayList<HashMap<String, String>> newsList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONArray json;
try {
json = jParser.getJSONFromUrl1(url);
for(int i=0; i < json.length(); i++)
{
JSONObject child = json.getJSONObject(i);
String id = child.getString(TAG_id);
String title = child.getString(TAG_title);
String content = child.getString(TAG_content);
String date = child.getString(TAG_date);
String author = child.getString(TAG_author);
String zone = child.getString(TAG_zone);
String area = child.getString(TAG_area);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_content, content);
map.put(TAG_title, title);
map.put(TAG_author, author);
// adding HashList to ArrayList
newsList.add(map);
}
}
catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(this, newsList,R.layout.onglet_news_listitem,new String[] { TAG_content, TAG_title, TAG_author }, new int[] {R.id.name, R.id.email, R.id.mobile });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
String cost = ((TextView) view.findViewById(R.id.email)).getText().toString();
String description = ((TextView) view.findViewById(R.id.mobile)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), TabNewsSingleMenuItemActivity.class);
in.putExtra(TAG_content, name);
in.putExtra(TAG_title, cost);
in.putExtra(TAG_author, description);
startActivity(in);
}
});
}
public boolean onOptionsItemSelected(MenuItem item)
{
//On regarde quel item a été cliqué grâce à son id et on déclenche une action
switch (item.getItemId())
{
case R.id.credits:
//pop up
Toast.makeText(TabNewsJSONParsingActivity.this, "Un delire", Toast.LENGTH_SHORT).show();
return true;
case R.id.quitter:
//Pour fermer l'application il suffit de faire finish()
finish();
return true;
}
return false;
}
}
And my Parser:
public class JSONParser
{
static InputStream is = null;
static JSONObject jObj = null;
static String jsonstr = "";
public JSONParser() {}
// throws IOException just to tell the caller that something bad happened (and
// what) instead of simply returning 'null' without any more information.
public JSONArray getJSONFromUrl1(String url) throws IOException
{
try
{
// should be a member of the parser to allow multiple calls without recreating the client every time.
DefaultHttpClient httpClient = new DefaultHttpClient();
// Using POST means sending data (or it its not following HTTP RFCs)
//HttpPost httpPost = new HttpPost(url);
HttpGet httpGet = new HttpGet(url);
// Here the client may not be entirely initialized (no timeout, no agent-string).
HttpResponse httpResponse = httpClient.execute(httpGet);
//HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
// The native utility function is also handling other charsets
String httpString = EntityUtils.toString(httpEntity);
return new JSONArray(httpString);
} catch (IOException ioe) {
throw ioe;
} catch (Exception ex) {
throw new IOException("Failed to read JSON from Url");
}
}
}
Who knows about get better perfs and make it rum for 4.0 ?
How to use it with Async Task ?
Thanks
you need to use AsyncTask to download and parse your data
code below
import java.io.IOException;
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.os.StrictMode;
import android.view.MenuItem;
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;
import android.widget.TextView;
import android.widget.Toast;
public class TabNewsJSONParsingActivity extends ListActivity
{
static{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
// url to make request
private static String url = "http://developer.prixo.fr/API/GetEvents?zone=8";
//JSON names
private static final String TAG_content = "content";
private static final String TAG_zone = "zone";
private static final String TAG_id = "id";
private static final String TAG_area = "area";
private static final String TAG_title = "title";
private static final String TAG_date = "date";
private static final String TAG_author = "author";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.onglet_news);
// selecting single ListView item
ListView lv = getListView();
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
String cost = ((TextView) view.findViewById(R.id.email)).getText().toString();
String description = ((TextView) view.findViewById(R.id.mobile)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), TabNewsSingleMenuItemActivity.class);
in.putExtra(TAG_content, name);
in.putExtra(TAG_title, cost);
in.putExtra(TAG_author, description);
startActivity(in);
}
});
new DownloadData().execute();
}
public boolean onOptionsItemSelected(MenuItem item)
{
//On regarde quel item a été cliqué grâce à son id et on déclenche une action
switch (item.getItemId())
{
case R.id.credits:
//pop up
Toast.makeText(TabNewsJSONParsingActivity.this, "Un delire", Toast.LENGTH_SHORT).show();
return true;
case R.id.quitter:
//Pour fermer l'application il suffit de faire finish()
finish();
return true;
}
return false;
}
private class DownloadData extends AsyncTask<Void, Integer, ArrayList<HashMap<String, String>>>
{
ProgressDialog pd = null;
/* (non-Javadoc)
* #see android.os.AsyncTask#onPreExecute()
*/
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pd = new ProgressDialog(TabNewsJSONParsingActivity.this);
pd.setTitle("Downloading...");
pd.setMessage("Please wait...");
pd.setCancelable(false);
pd.show();
}
/* (non-Javadoc)
* #see android.os.AsyncTask#doInBackground(Params[])
*/
#Override
protected ArrayList<HashMap<String, String>> doInBackground(Void... params) {
// TODO Auto-generated method stub
// Hashmap for ListView
ArrayList<HashMap<String, String>> newsList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONArray json;
try {
json = jParser.getJSONFromUrl1(url);
for(int i=0; i < json.length(); i++)
{
JSONObject child = json.getJSONObject(i);
String id = child.getString(TAG_id);
String title = child.getString(TAG_title);
String content = child.getString(TAG_content);
String date = child.getString(TAG_date);
String author = child.getString(TAG_author);
String zone = child.getString(TAG_zone);
String area = child.getString(TAG_area);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_content, content);
map.put(TAG_title, title);
map.put(TAG_author, author);
// adding HashList to ArrayList
newsList.add(map);
}
}
catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return newsList;
}
/* (non-Javadoc)
* #see android.os.AsyncTask#onPostExecute(java.lang.Object)
*/
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> newsList) {
// TODO Auto-generated method stub
super.onPostExecute(newsList);
pd.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(TabNewsJSONParsingActivity.this, newsList,R.layout.onglet_news_listitem,new String[] { TAG_content, TAG_title, TAG_author }, new int[] {R.id.name, R.id.email, R.id.mobile });
TabNewsJSONParsingActivity.this.setListAdapter(adapter);
}
}
}
Start you AsycnTask:
JSONTask g = new JSONTask();
g.execute();
And some code on how you can implement it;
public abstract class JSONTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... arg) {
//Do http get json here
String htpStatus= "";
String httpJSON = "" // this is the json data from you web service
// Create here your JSONObject...
JSONObject json = new JSONObject(httpJSON);
for(int i=0; i < json.length(); i++){
JSONObject child = json.getJSONObject(i);
String id = child.getString(TAG_id);
String title = child.getString(TAG_title);
String content = child.getString(TAG_content);
String date = child.getString(TAG_date);
String author = child.getString(TAG_author);
String zone = child.getString(TAG_zone);
String area = child.getString(TAG_area);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_content, content);
map.put(TAG_title, title);
map.put(TAG_author, author);
// adding HashList to ArrayList
newsList.add(map);
}
return htpStatus; // This value will be returned to your onPostExecute(result) method
}
#Override
protected void onPostExecute(String result) {
}
}
It might be because you run web connections on the main thread.. Try to run that piece of code into an AsyncTask or a different thread ..

Categories

Resources