Android JSON ListView import - android

I'm slowly turning crazy here.
I've got NewsActivity that gets information from a website and puts it in the listview but it isn't working.
public class NewsActivity extends ListActivity {
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String NEWS_URL = "http://www.bandofbrothersgaming.nl/android/news.php";
// JSON Node names
private static final String TAG_POSTID = "sid";
private static final String TAG_POSTSUBJECT = "title";
private static final String TAG_POSTTEXT = "hometext";
// contacts JSONArray
JSONArray post_id = null;
// Hashmap for ListView
ArrayList < HashMap < String, String >> NewsList;
#
Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news);
NewsList = 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.post_id))
.getText().toString();
String cost = ((TextView) view.findViewById(R.id.post_subject))
.getText().toString();
String description = ((TextView) view.findViewById(R.id.post_text))
.getText().toString();
// Starting single contact activity
/* Intent in = new Intent(getApplicationContext(),
SingleContactActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_EMAIL, cost);
in.putExtra(TAG_PHONE_MOBILE, description);
startActivity(in);*/
}
});
// Calling async task to get json
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetContacts extends AsyncTask < Void, Void, Void > {
#
Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(NewsActivity.this);
pDialog.setMessage("Please wait...");
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(NEWS_URL, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
post_id = jsonObj.getJSONArray(TAG_POSTID);
// looping through All Posts
for (int i = 0; i < post_id.length(); i++) {
JSONObject c = post_id.getJSONObject(i);
String postid = c.getString(TAG_POSTID);
String postsubject = c.getString(TAG_POSTSUBJECT);
String posttext = c.getString(TAG_POSTTEXT);
// tmp hashmap for single contact
HashMap < String, String > contact = new HashMap < String, String > ();
// adding each child node to HashMap key => value
contact.put(TAG_POSTID, postid);
contact.put(TAG_POSTSUBJECT, postsubject);
contact.put(TAG_POSTTEXT, posttext);
// adding contact to contact list
NewsList.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(
NewsActivity.this, NewsList,
R.layout.list_item, new String[] {
TAG_POSTID, TAG_POSTSUBJECT,
TAG_POSTTEXT
}, new int[] {
R.id.post_id,
R.id.post_subject, R.id.post_text
});
setListAdapter(adapter);
}
}
}
When I run it LogCat says the following :
12-29 13:56:39.698: W/System.err(1685): org.json.JSONException: Value [{"hometext":"Welcome to Nuke-Evolution.<br \/><br \/>\r\n\r\nYou must now setup an admin account. You can do this by <a href=\"admin.php\">clicking here<\/a>.<br \/><br \/><br \/><br \/>\r\n\r\n<b>NOTE:<\/b> You can remove this by going into the News Administration or by clicking the delete button below.\r\n","sid":"1","time":"2005-07-02 10:38:28","title":"Welcome To Nuke-Evolution"},{"hometext":"<p>\n\ttest android<\/p>\n<p>\n\tandroid test<\/p>","sid":"2","time":"2014-12-28 23:21:25","title":"android test"}] of type org.json.JSONArray cannot be converted to JSONObject
Does anybodey knows what im doing wrong?

You are trying to convert jsonStr to a JSONObject, but in fact is a JSONArray, looking at the LogCat. So convert it to a JSONArray first, then iterate over it and get the data you are looking for.

You can use
JSONArray post_id = new JSONArray(jsonStr);
instead of
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
post_id = jsonObj.getJSONArray(TAG_POSTID);
because jsonStr you get is a JSONArray

That is response of you php file, review your code PHP.

try this
JSONArray jsonArr = new JSONArray(jsonStr);
for(int i = 0; i < jsonArr.length(); i++){
JSONObject item = jsonArr.getJSONObject(i);
String postid = item.getString(TAG_POSTID);
String postsubject = item.getString(TAG_POSTSUBJECT);
String posttext = item.getString(TAG_POSTTEXT);
// tmp hashmap for single contact
HashMap < String, String > contact = new HashMap < String, String > ();
// adding each child node to HashMap key => value
contact.put(TAG_POSTID, postid);
contact.put(TAG_POSTSUBJECT, postsubject);
contact.put(TAG_POSTTEXT, posttext);
// adding contact to contact list
NewsList.add(contact);
}

Related

json parsing in android working with kimono api

I am working with a parsing json and fetching my json data from kimono.I am fetching json from following url:
http://www.brankart.com/test/tra.json
My mainactivity goes as follows:
public class MainActivity extends ListActivity {
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "http://www.brankart.com/test/tra.json";
// JSON Node names
private static final String lnk = "href";
private static final String d1 = "text";
private static final String dt = "property2";
// contacts JSONArray
JSONArray contacts = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactList = 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.name))
.getText().toString();
String cost = ((TextView) view.findViewById(R.id.email))
.getText().toString();
String description = ((TextView) view.findViewById(R.id.mobile))
.getText().toString();
// Starting single contact activity
Intent in = new Intent(getApplicationContext(),
SingleContactActivity.class);
in.putExtra(lnk, name);
in.putExtra(dt, cost);
in.putExtra(d1, description);
startActivity(in);
}
});
// Calling async task to get json
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
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);
JSONObject nsb = jsonObj.getJSONObject("results");
// Getting JSON Array node
contacts = nsb.getJSONArray("collection1");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
JSONObject p1 = c.getJSONObject("property1");
String link = p1.getString(lnk);
String descp = p1.getString(d1);
String detail = p1.getString(dt);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(lnk, link);
contact.put(d1, descp);
contact.put(dt, detail);
// 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");
}
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, contactList,
R.layout.list_item, new String[] { d1, dt,
lnk }, new int[] { R.id.name,
R.id.email, R.id.mobile });
setListAdapter(adapter);
}
}
}
I am still not able to fetch my json in listview.Please help
Try change doInBackground like below
#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);
JSONObject nsb = jsonObj.getJSONObject("results");
// Getting JSON Array node
contacts = nsb.getJSONArray("collection1");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
JSONObject p1 = c.getJSONObject("property1");
String link = p1.getString(lnk);
String descp = p1.getString(d1);
//change here !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
String detail = c.getString(dt);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(lnk, link);
contact.put(d1, descp);
contact.put(dt, detail);
// 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");
}
return null;
}

JSON data is read but cannot be converted to JSONArray

I'm developing an app which reads JSON data. Json Data is parsed but it is not viewing in the listview. Logcat says about a type mismatch. I'm not that much familiar in Json.
http://api.openweathermap.org/data/2.5/forecast/daily?lat=6.421465&lon=81.332396&cnt=10&mode=json
This is my logcat and code. Please hemp me with this.
org.json.JSONException: Index 1 out of range [0..1)
org.json.JSONArray.get(JSONArray.java:263)
org.json.JSONArray.getString(JSONArray.java:421)
com.is.parsej.ParseJ$GetContacts.doInBackground(ParseJ.java:141)
com.is.parsej.ParseJ$GetContacts.doInBackground(ParseJ.java:1)
android.os.AsyncTask$2.call(AsyncTask.java:287)
java.util.concurrent.FutureTask.run(FutureTask.java:234)
android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
public class ParseJ extends ListActivity {
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "http://api.openweathermap.org/data/2.5/forecast/daily?lat=6.421465&lon=81.332396&cnt=10&mode=json";
// JSON Node names
private static final String TAG_COd = "list"; //edited
private static final String TAG_ID = "dt"; //edited
private static final String TAG_WEATHER = "weather";
private static final String TAG_MAIN = "main";
private static final String TAG_DESC = "description";
private static final String TAG_TEMP = "temp";
private static final String TAG_DAY = "day";
private static final String TAG_MIN = "min";
private static final String TAG_MAX = "max";
private static final String TAG_NIGHT = "night";
private static final String TAG_MORN= "morn";
private static final String TAG_HUMIDITY = "humidity";
// contacts JSONArray
JSONArray contacts = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_parse_j);
contactList = 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 weather = ((TextView) view.findViewById(R.id.main))
.getText().toString();
String Temp = ((TextView) view.findViewById(R.id.Descrption))
.getText().toString();
String Humidity = ((TextView) view.findViewById(R.id.temp))
.getText().toString();
// Starting single contact activity
Intent in = new Intent(getApplicationContext(),
SingleContactActivity.class);
in.putExtra(TAG_WEATHER, weather);
in.putExtra(TAG_TEMP, Temp);
in.putExtra(TAG_HUMIDITY, Humidity);
startActivity(in);
}
});
// Calling async task to get json
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(ParseJ.this);
pDialog.setMessage("Please wait...");
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
contacts = jsonObj.getJSONArray(TAG_COd);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString(TAG_ID);
String humidity = c.getString(TAG_HUMIDITY);
// Phone node is JSON Object
JSONObject temp = c.getJSONObject(TAG_TEMP);
String day = temp.getString(TAG_DAY);
String maxTemp = temp.getString(TAG_MAX);
String minTemp = temp.getString(TAG_MIN);
String morningTemp = temp.getString(TAG_MORN);
//edited
JSONArray weather = c.getJSONArray(TAG_WEATHER);
String main = weather.getString(1);
String desc = weather.getString(2);
// 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_DAY, day);
contact.put(TAG_DESC, desc);
contact.put(TAG_HUMIDITY, humidity);
// 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");
}
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(
ParseJ.this, contactList,
R.layout.list_item, new String[] { TAG_DAY, TAG_DESC,
TAG_HUMIDITY }, new int[] { R.id.temp,
R.id.main, R.id.Descrption });
setListAdapter(adapter);
}
}
}
based on your JSON it is just a list of element. Arrays have [ at the beginning and ] at the end. look closely at your JSON you may find some array elements there that has [].
weather only has 1 element
"weather":[{"id":803,"main":"Clouds","description":"broken clouds","icon":"04d"}]
index out of bounds because you are using
JSONArray weather = c.getJSONArray(TAG_WEATHER);
String main = weather.getString(1);
String desc = weather.getString(2);
where there is no 1 and 2 in your json array weather, since the weather seems to have only 1 element put it in another json object
JSONObject weather = c.getJSONArray(TAG_WEATHER).getJSONObject(0);
String main = weather.getString("main");
String desc = weather.getString("description");
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
contacts = jsonObj.getJSONArray("list");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
}
change this in your code and let me know, if any issue.
the json is here
{"cod":"200","message":0.2809,"city":{"id":1244926,"name":"Hambantota","coord":{"lon":81.1185,"lat":6.1241},"country":"LK","population":0},"cnt":10,"list":[{"dt":1409896800,"temp":{"day":301.95,"min":300.47,"max":302.12,"night":301.31,"eve":301.87,"morn":300.47},"pressure":1020.63,"humidity":88,"weather":[{"id":803,"main":"Clouds","description":"broken
clouds","icon":"04d"}],"speed":6.47,"deg":243,"clouds":56},{"dt":1409983200,"temp":{"day":301.11,"min":299.62,"max":301.29,"night":299.62,"eve":300.76,"morn":300.13},"pressure":1021.53,"humidity":92,"weather":[{"id":802,"main":"Clouds","description":"scattered
clouds","icon":"03d"}],"speed":6.66,"deg":249,"clouds":48},{"dt":1410069600,"temp":{"day":300.9,"min":299.36,"max":300.9,"night":299.58,"eve":300.2,"morn":299.36},"pressure":1022.25,"humidity":90,"weather":[{"id":803,"main":"Clouds","description":"broken
clouds","icon":"04d"}],"speed":7.21,"deg":242,"clouds":80},{"dt":1410156000,"temp":{"day":299.47,"min":298.71,"max":300.44,"night":299.5,"eve":299.96,"morn":298.71},"pressure":1023.27,"humidity":98,"weather":[{"id":802,"main":"Clouds","description":"scattered
clouds","icon":"03d"}],"speed":5.83,"deg":252,"clouds":44},{"dt":1410242400,"temp":{"day":301.38,"min":297.39,"max":301.38,"night":298.36,"eve":300.82,"morn":297.39},"pressure":1012.02,"humidity":0,"weather":[{"id":500,"main":"Rain","description":"light
rain","icon":"10d"}],"speed":3.87,"deg":250,"clouds":76,"rain":0.38},{"dt":1410328800,"temp":{"day":301.77,"min":297.49,"max":301.77,"night":299.44,"eve":301.13,"morn":297.49},"pressure":1011.84,"humidity":0,"weather":[{"id":500,"main":"Rain","description":"light
rain","icon":"10d"}],"speed":4.88,"deg":259,"clouds":27,"rain":0.82},{"dt":1410415200,"temp":{"day":302.15,"min":299.15,"max":302.15,"night":299.43,"eve":300.52,"morn":299.15},"pressure":1011.1,"humidity":0,"weather":[{"id":500,"main":"Rain","description":"light
rain","icon":"10d"}],"speed":6.3,"deg":257,"clouds":64,"rain":1.82},{"dt":1410501600,"temp":{"day":301.52,"min":299.16,"max":301.52,"night":299.36,"eve":300.59,"morn":299.16},"pressure":1011.05,"humidity":0,"weather":[{"id":500,"main":"Rain","description":"light
rain","icon":"10d"}],"speed":8.05,"deg":257,"clouds":50,"rain":2.38},{"dt":1410588000,"temp":{"day":301.26,"min":298.74,"max":301.26,"night":299.53,"eve":300.43,"morn":298.74},"pressure":1010.43,"humidity":0,"weather":[{"id":500,"main":"Rain","description":"light
rain","icon":"10d"}],"speed":7.69,"deg":258,"clouds":33,"rain":1.34},{"dt":1410674400,"temp":{"day":300.01,"min":298.37,"max":300.01,"night":298.48,"eve":298.37,"morn":298.87},"pressure":1010.17,"humidity":0,"weather":[{"id":501,"main":"Rain","description":"moderate
rain","icon":"10d"}],"speed":8.36,"deg":253,"clouds":55,"rain":8.91}
and then you get object with tag "cod"
contacts = jsonObj.getJSONArray(TAG_COd)
"cod":"200"
you will get "200"
how can "200" be converted to JSONArray?
the array structure is just like this
[{"dt":1409896800},{"dt":1409896800},{"dt":1409896800},{"dt":1409896800}]
starts with "[" and end with "]"
Exception is self Explaining
org.json.JSONException: Value 200 at cod of type java.lang.String cannot be converted to JSONArray
You are converting String to JSONArray here,
contacts = jsonObj.getJSONArray(TAG_COd);
cod is a String while you're converting it to JSONArray
String cod = jsonObj.getJSONString(TAG_COd);

No value error in json parsing

This is my
I want to parse it but i am getting no value for theater how can i solve this problem?
My code is:
CustomizedListView.java
public class CustomizedListView extends Activity {
// All static variables
static final String URL ="";
// XML node keys
JSONArray theaters = null;
JSONObject json = null;
ListView list;
LazyAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
json=new JSONObject();
try {
// Getting Array of Contacts
theaters = json.getJSONArray(KEY_SONG);
// looping through All Contacts
for(int i = 0; i < theaters.length(); i++){
JSONObject c = theaters.getJSONObject(i);
// Storing each json item in variable
String name = c.getString(KEY_TITLE);
String distance = c.getString(KEY_DURATION);
String pincode = c.getString(KEY_ARTIST);
//String image = c.getString(TAG_MOVIEIMAGE);
// Phone number is agin JSON Object
// creating new HashMap
HashMap<String, String> map1 = new HashMap<String, String>();
// adding each child node to HashMap key => value
map1.put(KEY_TITLE,distance);
map1.put(KEY_DURATION,pincode);
map1.put(KEY_ARTIST,name);
//map.put(TAG_MOVIEIMAGE, image);
// adding HashList to ArrayList
songsList.add(map1);
}
} catch (JSONException e) {
e.printStackTrace();
System.out.println("this is error" +e);
}
// adding HashList to ArrayList
list=(ListView)findViewById(R.id.list);
// Getting adapter by passing xml data ArrayList
adapter=new LazyAdapter(this, songsList);
list.setAdapter(adapter);
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
}
}
I want to parse it but i am getting no value for theater how can i solve this problem?
My code is:I want to parse it but i am getting no value for theater how can i solve this problem?
My code is:
pl help me to resolve error..
You are not assigning any value to the json object, you have to do it in Async Task to fetch the feed from your service.
As #Abed El Majeed K has already said, you need to do it as an async task.
i've found that any downloading, or internet actions are required to be preformed on a separate thread & not on the MainUI.
An example:
public class task extends AsyncTask<String, Void, String>{
private StringBuilder inputStreamToString(InputStream is){
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedRead rd = new Buffer3edReader(new InputStreamReader(is));
while((rLine = rd.readLine()) != null){
answer.append(rLine);
}
return answer;
}
protected String doInBackground(String... param){
String uRL = "http://example.com";
URL url = new URL(uRL);
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
String jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
return jsonResult;
}
protected void onPostExecute(String result){
JSONObject jsonResponse = new JSONObject(result);
JSONArray jsonNode = jsonResponse.getJSONArray(whatever_your_json_stream_is_called);
for(int i = 0; i < jsonMainNode.length(); i++){
JSONObject jsonchild = jsonNode.getJSONObject(i);
String some_value = jsonchild.getString(some_key);
...
}
}
}
by running requests on AsyncTask, you are not causing the MainUiThread to pause, or wait for the download to complete.
With that said, the JSON source you are using is incorrect.
JSON structure is like this:
{"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]}
here might help: http://json.org/

JSON Data stored to SQLite

I am following this to store JSON parsed data into SQLite Database, but whenever i use my app offline not getting stored data into ListView.
Is there anything left to implement in my existing code ?
MainActivity.java:-
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
databaseHelper=new CategoryHelper(MainActivity.this);
contactList = 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) {
}
});
// Calling async task to get json
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
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
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);
databaseHelper.saveCategoryRecord(id,name);
// 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);
// 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");
}
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, contactList,
R.layout.list_item, new String[] { TAG_NAME }, new int[] { R.id.name });
setListAdapter(adapter);
}
}
I don't know what that ServiceHandler thing is, but I'm guessing the call to makeServiceCall() returns null when you're offline. This means you aren't populating the contactList, which means it's empty when you're creating the ListAdapter.
I'm guessing what you want to do, is add an else clause to if (jsonStr != null) that populates contactList with records from your DB. How to do this depends on the implementation details of CategoryHelper.
Using shared preference would be a better approach for that. Follow these steps:
search and download GSON library. This will simplify our task for saving and retrieving JSON to/from shared preferences and let your app use the GSON library
example:
SharedPreferences prefs = getSharedPreferences("mySharedPreferenceKey");
Editor editor = prefs.edit();
Gson gson = new Gson();
//convert your object to string and save it to shared preference
ArrayList<Integer> myIntArrs = new ArrayList<Integer>();
editor.putString("myJSONKey", new Gson().toJson(myIntArrs)).commit();
//get your json string from shared preferences
public final Type ARRAYLIST_INTEGER = new TypeToken<ArrayList<Integer>>(){}.getType();
ArrayList<Integer> intArrs = gson.fromJson(prefs.getString("myJSONKey", "{}"), ARRAYLIST_INTEGER);
//do something with your intArrs
Hope this helps!

Loading image in ListView from Array ID Android

I currently have a ListAdapter set up that is passed information pulled from a MYSQL database via JSON. I'm trying to display an image I have stored in the drawable folder based on the ID of the product. e.g For Product 1 R.drawable.img1 is shown in and so on..
public class GetProducts extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSON jParser = new JSON();
Functions uf = new Functions();
ArrayList<HashMap<String, Object>> productsList;
// url to get all products list
private static String url_all_products = "http://jumpto.be/api/get_all_products.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
private static final String TAG_IMGURL = "image";
// products JSONArray
JSONArray products = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_products);
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, Object>>();
new GetProductsFromDB().execute();
// Loading products in Background Thread
// Get listview
ListView lv = getListView();
// on seleting single product
// launching Edit Product Screen
/*lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String pid = ((TextView) view.findViewById(R.id.pid)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
OrderBuild.class);
// sending pid to next activity
in.putExtra(TAG_PID, pid);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});*/
}
class GetProductsFromDB extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(GetProducts.this);
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url_all_products, params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
String ImgUrl = c.getString(TAG_PID);
// creating new HashMap
HashMap<String, Object> map = new HashMap<String, Object>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_NAME, name);
String imageLink = "R.drawable.img"+id;
map.put(TAG_IMGURL, imageLink);
// adding HashList to ArrayList
productsList.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
ListAdapter adapter = new SimpleAdapter(
GetProducts.this, productsList,
R.layout.list_item, new String[] { TAG_PID,
TAG_NAME, TAG_IMGURL},
new int[] { R.id.pid, R.id.name, R.id.img });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
The current code I have just tells me it cannot find the directory. I have looked at URI but I can't figure out how I run them in the array / for loop.
Many Thanks
R.drawable.img1 is actually just an int value defined in your automatically generated R.java file, so you cannot use it directly.
However, you can retrieve your drawable using the following:
Resources resources = getResources();
int resId = resources.getIdentifier("img" + id, "drawable", getPackageName());
Drawable myDrawable = resources.getDrawable(resId);
Alternatively, you can place your image files in your assets directory and load them from there using the filename.
InputStream inputStream = getAssets().open("img" + id + ".jpg");
Drawable drawable = Drawable.createFromStream(inputStream, null);
mImageView.setImageDrawable(drawable);
You can set int value for drawable in hashmap. It is easy to bind in list adapter.
int imageLink = R.drawable.img1;
map.put(TAG_IMGURL, imageLink);

Categories

Resources