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 ..
Related
So I'm stuck on this... I need to display images in a listview which gets its data from a json file.
I've already setup the connection, parsed the json file and displayed what i need. But somehow I can't find much information about how to turn a string (which has the URL) into an image in a listview.
The string which has the url is called "ImageLink"
Below is my MainActivity.
public class MainActivity extends ListActivity {
private ProgressDialog pDialog;
// URL to get game info JSON
private static String url = "https://dl.dropboxusercontent.com/u/38379784/Upcoming%20Games/DataForUPG.js";
// JSON Node names
private static final String TAG_Games = "games";
private static final String TAG_Title = "Title";
private static final String TAG_Description = "Description";
private static final String TAG_Release = "Release";
private static final String TAG_ImageLink = "ImageLink";
// Gameinfo JSONArray
JSONArray games = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> GamesList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GamesList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String Title = ((TextView) view.findViewById(R.id.Title))
.getText().toString();
String Description = ((TextView) view.findViewById(R.id.Description))
.getText().toString();
String Release = ((TextView) view.findViewById(R.id.Release))
.getText().toString();
String ImageLink = ((TextView) view.findViewById(R.id.ImageLink_label))
.getText().toString();
// Starting single contact activity
Intent in = new Intent(getApplicationContext(),
SingleListItem.class);
in.putExtra(TAG_Title, Title);
in.putExtra(TAG_Description, Description);
in.putExtra(TAG_Release, Release);
in.putExtra(TAG_ImageLink, ImageLink);
startActivity(in);
}
});
// Calling async task to get json
new GetGames().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetGames extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Loading Data...");
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
games = jsonObj.getJSONArray(TAG_Games);
// looping through All games
for (int i = 0; i < games.length(); i++) {
JSONObject c = games.getJSONObject(i);
String Title = c.getString(TAG_Title);
String Description = c.getString(TAG_Description);
String Release = c.getString(TAG_Release);
String ImageLink = c.getString(TAG_ImageLink);
// tmp hashmap for single game
HashMap<String, String> games = new HashMap<String, String>();
// adding each child node to HashMap key => value
games.put(TAG_Title, Title);
games.put(TAG_Description, Description);
games.put(TAG_Release, Release);
games.put(TAG_ImageLink, ImageLink);
// adding contact to gameinfo list
GamesList.add(games);
}
} 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(
MainActivity.this, GamesList,
R.layout.list_item, new String[] { TAG_Title, TAG_Release,
TAG_Description, TAG_ImageLink }, new int[] { R.id.Title,
R.id.Release, R.id.Description, R.id.ImageLink_label });
setListAdapter(adapter);
}
}
}
I would appreciate any help
Well, you could probably create another async task to handle downloading the image like this:
private class DownloadImg extends AsyncTask<String, Void, Bitmap>{
#Override
protected Bitmap doInBackground(String... params) {
// TODO Auto-generated method stub
String TAG_ImageLink = params[0];
Bitmap bm = null;
try {
InputStream in = new java.net.URL(TAG_ImageLink).openStream();
bm = BitmapFactory.decodeStream(in);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return bm;
}
#Override
protected void onPostExecute(Bitmap result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
}
or you could use a 3rd party image loading library like picasso or volley's ImageRequest
I was looking for a simple example on parsing a JSON file, using the loopj AsyncHttpClient. But so far I could not find any useful information. :(
Simple JSON file to parse:
{
"contact": [
{
"id": "10",
"name": "Tom",
"email": "tom#gmail.com"
}
}
]
}
I would be grateful for any suggestion.
Thanks!!
You need to get the json first. I assume you have done that
{ // json object node
"contact": [ //json array contact
{ // json object node
To parse
JSONObject jb = new JSONObject("your json");
JSONArray con = jb.getJSONArray("contact");
JSONObject contact = (JSONObject) con.getJSONObject(0);
String id = contact.getString("id");
String name = contact.getString("name");
String id = contact.getString("id");
public class MainActivity extends Activity {
private ProgressDialog pdialog;
private static String url = "http://highspecificationservers.com/apk/webservice.php";
private static final String TAG_STUDENT = "student";
private static final String TAG_FNAME = "fname";
private static final String TAG_EMAIL = "email";
private static final String TAG_MOBILE = "mobile";
JSONArray student = null;
ArrayList<HashMap<String, String>> studentlist;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
studentlist = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
String fname = ((TextView) view.findViewById(R.id.fname))
.getText().toString();
String cost = ((TextView) view.findViewById(R.id.email))
.getText().toString();
String description = ((TextView) view.findViewById(R.id.mobile))
.getText().toString();
Intent in = new Intent(getApplicationContext(),
SingleContactActivity.class);
in.putExtra(TAG_FNAME, fname);
in.putExtra(TAG_EMAIL, cost);
in.putExtra(TAG_MOBILE, description);
startActivity(in);
}
});
new GetStudent().execute();
}
private class GetStudent extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pdialog = new ProgressDialog(MainActivity.this);
pdialog.setMessage("please wait");
pdialog.setCancelable(false);
pdialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
ServiceHandler sh = new ServiceHandler();
String jString = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response:", "> " + jString);
if (jString != null) {
try {
JSONObject Jsonobj = new JSONObject(jString);
student = Jsonobj.getJSONArray(TAG_STUDENT);
for (int i = 0; i < student.length(); i++) {
JSONObject c = student.getJSONObject(i);
String fname = c.getString(TAG_FNAME);
String email = c.getString(TAG_EMAIL);
String mobile = c.getString(TAG_MOBILE);
HashMap<String, String> student = new HashMap<String, String>();
student.put(TAG_FNAME, fname);
student.put(TAG_EMAIL, email);
student.put(TAG_MOBILE, mobile);
studentlist.add(student);
}
} 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) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if (pdialog.isShowing())
pdialog.dismiss();
ListAdapter adapter = new SimpleAdapter(MainActivity.this,
studentlist, R.layout.list_item, new String[] { TAG_FNAME,
TAG_EMAIL, TAG_MOBILE }, new int[] { R.id.fname,
R.id.email, R.id.mobile });
setListAdapter(adapter);
}
private void setListAdapter(ListAdapter adapter) {
// TODO Auto-generated method stub
}
}
private ListView getListView() {
// TODO Auto-generated method stub
return null;
}
}
Go with this...
// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
contacts = jsonObj.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_ID, id);
contact.put(TAG_NAME, name);
contact.put(TAG_EMAIL, email);
// adding contact to contact list
contactList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
please i need help, am a rookie, how can i create a widget that get its feed from from a Json in android. Is there a helpful tutorial that can help with this or a source code i can look at. I have checked online for a suitable tutorail but i found none that can help directly. this is the json url feed i want to pass into my android widget:url
public class MinistryNews extends SherlockListActivity {
private ActionBarMenu abm;
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "http://";
// JSON Node names
private static final String TAG_QUERY = "query";
private static final String TAG_ID = "id";
private static final String TAG_TITLE = "title";
private static final String TAG_CONTENT = "content";
// private static final String TAG_CAT_CODE = "cat_code";
// private static final String TAG_STATUS = "status";
// private static final String TAG_CREATED_TIME = "created_time";
private static final String TAG_UPDATE_TIME = "update_time";
// private static final String TAG_AUTHOR_ID = "author_id";
// contacts JSONArray
JSONArray query = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> queryList;
#SuppressWarnings("deprecation")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ministry_news);
ActionBar actionbar = getSupportActionBar();
actionbar.setDisplayHomeAsUpEnabled(true);
abm = new ActionBarMenu(MinistryNews.this);
if (com.cepfmobileapp.org.service.InternetStatus.getInstance(this)
.isOnline(this)) {
// Toast t = Toast.makeText(this,"You are online!!!!",8000).show();
// Toast.makeText(getBaseContext(),"You are online",Toast.LENGTH_SHORT).show();
// Calling async task to get json
new GetQuery().execute();
} else {
// Toast.makeText(getBaseContext(),"No Internet Connection",Toast.LENGTH_LONG).show();
// Toast t =
// Toast.makeText(this,"You are not online!!!!",8000).show();
// Log.v("Home",
// "############################You are not online!!!!");
AlertDialog NetAlert = new AlertDialog.Builder(MinistryNews.this)
.create();
NetAlert.setMessage("No Internet Connection Found! Please check your connection and try again!");
NetAlert.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// here you can add functions
// finish();
}
});
NetAlert.show();
}
queryList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.title))
.getText().toString();
String cost = ((TextView) view.findViewById(R.id.time))
.getText().toString();
String description = ((TextView) view
.findViewById(R.id.content)).getText().toString();
// String plain = Html.fromHtml(description).toString();
// description.replace(/<\/?[^>]+>/gi, '');
// Starting single contact activity
Intent in = new Intent(getApplicationContext(),
SingleActivity.class);
in.putExtra(TAG_TITLE, name);
in.putExtra(TAG_UPDATE_TIME, cost);
in.putExtra(TAG_CONTENT, description);
startActivity(in);
}
});
// Calling async task to get json
// new GetQuery().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetQuery extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MinistryNews.this);
pDialog.setMessage("Please wait..Loading news");
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
query = jsonObj.getJSONArray(TAG_QUERY);
// looping through All Contacts
for (int i = 0; i < query.length(); i++) {
JSONObject c = query.getJSONObject(i);
String id = c.getString(TAG_ID);
String title = c.getString(TAG_TITLE);
String content = c.getString(TAG_CONTENT);
String update_time = c.getString(TAG_UPDATE_TIME);
// String address = c.getString(TAG_ADDRESS);
// String gender = c.getString(TAG_GENDER);
// Phone node is JSON Object
// JSONObject phone = c.getJSONObject(TAG_PHONE);
// String mobile = phone.getString(TAG_PHONE_MOBILE);
// String home = phone.getString(TAG_PHONE_HOME);
// String office = phone.getString(TAG_PHONE_OFFICE);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_ID, id);
contact.put(TAG_TITLE, title);
contact.put(TAG_CONTENT, content);
contact.put(TAG_UPDATE_TIME, update_time);
// contact.put(TAG_PHONE_MOBILE, mobile);
// adding contact to contact list
queryList.add(contact);
}
} 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(MinistryNews.this,
queryList, R.layout.list_item, new String[] { TAG_TITLE,
TAG_UPDATE_TIME, TAG_CONTENT }, new int[] {
R.id.title, R.id.time, R.id.content });
setListAdapter(adapter);
}
}
here is a nice tutorial for you to import json data http://mrbool.com/how-to-use-json-to-parse-data-into-android-application/28944
if its hard for you still.i can suggest you one thing ,you can import your rss to any website and customize it there as you want it to be and post them as json data it will be easier to do i guess.
its a raugh test for geting json data only the method i think its a bit easier and detail u can return the values instead of showing them in a text from the textvw
public void getdata()
{
String result=null;
InputStream inputstream=null;
try{
HttpClient httpclient=new DefaultHttpClient();
HttpPost httppost=new HttpPost("http://www.hadid.aero/news_and_json");
HttpResponse response=httpclient.execute(httppost);
HttpEntity httpentity=response.getEntity();
inputstream= httpentity.getContent();
}
catch(Exception ex)
{
resultview.setText(ex.getMessage()+"at 1st exception");
}
try{
BufferedReader reader=new BufferedReader(new InputStreamReader(inputstream,"iso-8859-1"),8);
StringBuilder sb=new StringBuilder();
String line=null;
while((line=reader.readLine())!= null)
{
sb.append(line +"\n");
}
inputstream.close();
result=sb.toString();
}
catch(Exception ex)
{
resultview.setText(ex.getMessage()+"at 2nd exception");
}
try{
String s="test :";
JSONArray jarray=new JSONArray(result);
for(int i=0; i<jarray.length();i++)
{
JSONObject json=jarray.getJSONObject(i);
s= s +"+json.getString("lastname")+"\n"+
"newsid&title : "+json.getString("id_news")+" "+json.getString("title")+"\n"+
"date :"+json.getString("date")+"\n"+
"description : "+json.getString("description");
}
resultview.setText(s);
}
catch(Exception ex)
{
this.resultview.setText(ex.getMessage()+"at 3rd exception");
}
Check out GSON library which will create Java object with JSON content and use this in Your widget
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
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));
}
}
}