Nothing is populated from ArrayList to ListView - java

I am trying to populate some items from PHP to Android using ListView
public class ChooseCategory extends ListActivity {
private ListView lv;
ArrayAdapter<FoodStores> arrayAdapter;
private static final String TAG = MainActivity.class.getSimpleName();
private ArrayList<FoodStores> storefoodList;
// JSON parser class
JSONParser jsonParser = new JSONParser();
//ids
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
private String URL_STORES = "http://www.123.com/get_stores.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
//lv = (ListView) findViewById(R.id.list_item);
lv = (ListView)findViewById(android.R.id.list);
storefoodList = new ArrayList<FoodStores>();
new GetFoodStores().execute();
arrayAdapter = new ArrayAdapter<FoodStores> (this,R.layout.restaurant_list,storefoodList );
private class GetFoodStores extends AsyncTask<Void,Void,Void> {
#Override
protected void onPreExecute(){
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandlerFood jsonParserFood = new ServiceHandlerFood();
String json = jsonParserFood.makeServiceCall(URL_STORES, ServiceHandlerFood.GET);
Log.e("Response: ", " > " + json);
if(json != null){
try{
JSONObject jsonObj = new JSONObject(json);
if(jsonObj != null){
JSONArray storeListFood = jsonObj.getJSONArray("storelistfood");
for(int i = 0; i < storeListFood.length(); i++){
JSONObject storeFoodObj = (JSONObject) storeListFood.get(i);
FoodStores foodStores = new FoodStores(storeFoodObj.getInt("id"),storeFoodObj.getString("STORENAME"));
storefoodList.add(foodStores);
}
}
}catch(JSONException e){
e.printStackTrace();
}
}else{
Log.e("JSON Data", "No data received from server");
}
return null;
}
#Override
protected void onPostExecute(Void result){
super.onPostExecute(result);
lv.setAdapter(arrayAdapter);
}
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="{relativePackage}.${activityClass}" >
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</RelativeLayout>
restaurant_list.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >
<ImageView
android:id="#+id/icon"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginBottom="5dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="5dp"
android:src="#drawable/nasilemak2" />
<TextView
android:id="#+id/Itemname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:paddingTop="5dp"/>
</LinearLayout>
The error that I got is that it only shows blank screen and it crashed after a minute. I would like to populate the ListView using ArrayList from PHP.

You didn't provide all classes so some classes are provided by me.
Here you are:
ChooseCategory.java:
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class ChooseCategory extends ListActivity {
private ListView lv;
ArrayAdapter<FoodStores> arrayAdapter;
private static final String TAG = "XXX";
private ArrayList<FoodStores> storefoodList;
// JSON parser class
// JSONParser jsonParser = new JSONParser();
// ids
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
private String URL_STORES = "http://echo.jsontest.com/id/1/STORENAME/Perogi";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(android.R.id.list);
storefoodList = new ArrayList<FoodStores>();
new GetFoodStores().execute();
arrayAdapter = new ArrayAdapter<FoodStores>(this,
R.layout.restaurant_list, R.id.Itemname, storefoodList);
lv.setAdapter(arrayAdapter);
}
private class GetFoodStores extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandlerFood jsonParserFood = new ServiceHandlerFood();
String json = jsonParserFood.makeServiceCall(URL_STORES,
"TEST");
//ServiceHandlerFood.GET);
Log.e("Response: ", " > " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
if (jsonObj != null) {
JSONArray storeListFood = jsonObj
.getJSONArray("storelistfood");
for (int i = 0; i < storeListFood.length(); i++) {
JSONObject storeFoodObj = (JSONObject) storeListFood
.get(i);
FoodStores foodStores = new FoodStores(
storeFoodObj.getInt("id"),
storeFoodObj.getString("STORENAME"));
storefoodList.add(foodStores);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "No data received from server");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
lv.setAdapter(arrayAdapter);
}
}
}
Foodstores.java:
public class FoodStores {
int id;
String name;
public FoodStores(int id, String string) {
this.id=id;
name=string;
}
#Override
public String toString(){
return name;
}
}
ServiceHandlerFood.java:
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
public class ServiceHandlerFood {
public static final String GET = "GET";
public String makeServiceCall(String uRL_STORES, String get2) {
if ("TEST".equals(get2))
return "{'storelistfood':[{'id':1, 'STORENAME':'Arbys'},{'id':2, 'STORENAME':'Perogi'},{'id':3, 'STORENAME':'McDonalds'}]}";
DefaultHttpClient httpclient = new DefaultHttpClient(
new BasicHttpParams());
HttpPost httppost = new HttpPost(uRL_STORES);
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(
inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
// Oops
} finally {
try {
if (inputStream != null)
inputStream.close();
} catch (Exception squish) {
}
}
return result;
}
}
The rest of files was untouched.

Move this line in onPost method:
arrayAdapter = new ArrayAdapter<FoodStores> `(this,R.layout.restaurant_list,storefoodList );`
Like this
#Override
protected void onPostExecute(Void result){
super.onPostExecute(result);
arrayAdapter = new ArrayAdapter<FoodStores> (this,R.layout.restaurant_list,storefoodList );
lv.setAdapter(arrayAdapter);
}
Edit :
And change "this" to getApplicationContext() like this
arrayAdapter = new ArrayAdapter<FoodStores> (getApplicationContext(),R.layout.restaurant_list,storefoodList );
Edit 1:
Replace the following to
lv = (ListView)findViewById(android.R.id.list);
this
lv = (ListView)findViewById(R.id.list);

The main problem with your code is, the default implementation of the ArrayAdapter needs a TextView in which it will display its list items as strings. If not provided, it will throw exception like
06-22 21:22:42.535: E/AndroidRuntime(6531): FATAL EXCEPTION: main
06-22 21:22:42.535: E/AndroidRuntime(6531):
java.lang.IllegalStateException: ArrayAdapter requires the resource ID
to be a TextView 06-22 21:22:42.535: E/AndroidRuntime(6531): at
android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:386)
06-22 21:22:42.535: E/AndroidRuntime(6531): at
android.widget.ArrayAdapter.getView(ArrayAdapter.java:362)
The simplest solution will be to just replace
arrayAdapter = new ArrayAdapter<FoodStores> (this,R.layout.restaurant_list,storefoodList );
with
arrayAdapter = new ArrayAdapter<FoodStores> (this,R.layout.restaurant_list,R.id.Itemname,storefoodList);
Please note the additional parameter R.id.Itemname which is the TextView in your layout that the ArrayAdapter needs to display the content.
Please also remember to override the toString() method in your FoodStores to return some logical string like the name if not done already (as suggested by #Alex above).
Hope this helps.

I`m not sure about it, but this line is not good,because:
storefoodList = new ArrayList<FoodStores>();
new GetFoodStores().execute();
arrayAdapter = new ArrayAdapter<FoodStores> (this,R.layout.restaurant_list,storefoodList );
You give an empty arrayList to the adapter, because AsyncTaks is still loading the content. So in this case, the adapter cache an empty list, and its going to provide to the listview when you call the lw.setAdapter(adapter) at onPostExecute.
If you wouldnt like to change the architecture of your app then,You should call notifydatasetchanged() after you set the adapter in onPostExecute.
OR you can initialize the adapter with the updated list, onPostExecute, and set it to the ListView.

I see 3 problems here
you need to create a custom adapter that extends from
ArrayAdapter
you cannot use ArrayAdapter directly [enter link description here][1] [1]:
http://developer.android.com/reference/android/widget/ArrayAdapter.html
either need to create the array adapter in onPostExecute or you
need to tell your adapter that arraylist haschanged
if your
activity extends listactivity then as you did listview's id in xml
should be #android:id/list but then ListView lv = getListView() or
your activity just extends Activity and listview's id is in xml
should be #+id/list then ListView lv =
(ListView)findViewById(R.id.list)

try to implement image with Picasso and do more one thing that please do have any other web service so please check this web service in this code so it will clear that the code will working correctly or not. After that that will be more easily for you. do let me know if any.

Related

Unable to parse json and set it to recyclerview [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
Hi I am learning Android App Development. For this, I wanted to make myself a simple wallpaper app. Hence, I wrote something roughly which is presented here. I want to get wallpaper urls from json. Unfortunately, I am unable to get data from my server. java.lang.NullPointerException: Attempt to read from null array
How do I get the data correctly from the jsonParse asynctask?
I am stuck on this the whole day. What could have gone wrong here?
Here is my code:
myjson.json:
{
"walls":[
{"ourUrl":"http://www.hdbloggers.net/wp-content/uploads/2016/01/Wallpapers-for-Android.jpg"},
{"ourUrl":"http://androidwallpape.rs/content/02-wallpapers/131-night-sky/wallpaper-2707591.jpg"},
{"ourUrl":"http://androidwallpape.rs/content/02-wallpapers/155-starrynight/starry-night-sky-star-galaxy-space-dark-9-wallpaper.jpg"}
]
}
MainActivity.java:
package regalstreak.me.wallpapers;
import android.app.Activity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
public class MainActivity extends Activity {
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
RecyclerView.Adapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView)findViewById(R.id.recycler_view);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
adapter = new RecyclerAdapter(this);
recyclerView.setAdapter(adapter);
}
}
RecyclerAdapter.java:
package regalstreak.me.wallpapers;
import android.content.Context;
import android.os.AsyncTask;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import org.apache.commons.io.IOUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;
// This is a recycleradapter which will set the correct images to the correct position in the recyclerview.
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
private Context myCtx1;
String[] arr;
String[] arrurl;
String jsonURL = "http://dev.regalstreak.me/myjson.json";
public RecyclerAdapter(Context ctx) {
this.myCtx1 = ctx;
}
public ImageView Image;
private String[] mText = {
"Text 1",
"Text 2",
"Text 3"
};
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView Text;
public ViewHolder(View itemView) {
super(itemView);
Image = (ImageView) itemView.findViewById(R.id.image_view);
Text = (TextView) itemView.findViewById(R.id.text_view);
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.wallpapers_list, viewGroup, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, int i) {
viewHolder.Text.setText(mText[i]);
new jsonParse().execute();
new DownloadImageTask(Image).execute(arrurl[i]);
}
#Override
public int getItemCount() {
return mText.length;
}
class jsonParse extends AsyncTask<String, Void, String[]> {
protected String[] doInBackground(String[] urls) {
String myText = null;
String url = urls[0];
String ourUrl;
try {
InputStream in = new java.net.URL(jsonURL).openStream();
myText = IOUtils.toString(in, "utf-8");
in.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
// Parse the json
List<String> allUrls = new ArrayList<String>();
JSONObject jsonObjectRoot = new JSONObject(myText);
JSONArray jsonArray = jsonObjectRoot.getJSONArray("walls");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
ourUrl = jsonObject.getString("ourUrl");
allUrls.add(ourUrl);
}
arr = allUrls.toArray(new String[allUrls.size()]);
} catch (JSONException e) {
e.printStackTrace();
}
return arr;
}
protected void onPostExecute(String[] result){
arrurl = result;
}
}
}
DownloadImageTask.java:
package regalstreak.me.wallpapers;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ImageView;
import java.io.InputStream;
// Here, we will download the wallpapers obtained from jsonData with an asynctask.
public class DownloadImageTask extends AsyncTask<String, Void, Bitmap>{
ImageView bmImage;
public DownloadImageTask(ImageView bmImage){
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
in.close();
} catch (Exception e) {
Log.e("Error getting images.", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result){
bmImage.setImageBitmap(result);
}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="regalstreak.me.wallpapers.MainActivity">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/recycler_view" />
</RelativeLayout>
wallpaper_list.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/relative"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="5dp">
<ImageView
android:id="#+id/image_view"
android:layout_width="match_parent"
android:layout_height="150dp" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignBottom="#id/image_view"
android:alpha="0.6"
android:background="#color/colorDivider"
android:padding="9dp">
<TextView
android:id="#+id/text_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAlignment="center"
android:textColor="#color/colorPrimaryText" />
</RelativeLayout>
</RelativeLayout>
I have used HttpURLConnection class here for quick response and features like cache. The data received from the URL is being added to an input stream which we then convert to a String builder to get a string object which we can further use with the JSON classes.
PS - Add the AsyncTask code to your MainActivity itself, don't make a separate java file for this.
Tip - Always verify the json using this tool - jsonlint.com
MainActivity
/*
your code
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
new MyAsyncTask().execute("");
}
class MyAsyncTask extends AsyncTask<String, String, Void> {
private ProgressDialog progressDialog = new ProgressDialog(StartScreen.this);
InputStream inputStream = null;
String result = "";
ArrayList<String> list;
protected void onPreExecute() {
progressDialog.setTitle("Downloading JSON Data");
progressDialog.show();
// above code makes a dialog with a progress bar
}
#Override
protected Void doInBackground(String... params) {
ArrayList<String> param = new ArrayList<String>();
URL url, url2;
try{
url = new URL("http://dev.regalstreak.me/myjson.json");
// link to your json file
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setUseCaches(false);
inputStream = new BufferedInputStream(urlConnection.getInputStream());
}catch (MalformedURLException malle){
Log.e("Mal", ""+malle);
malle.printStackTrace();
}catch (IOException ioe){
Log.e("IO", ""+ioe);
ioe.printStackTrace();
}
// Convert response to string using String Builder
try {
BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"), 8);
StringBuilder sBuilder = new StringBuilder();
String line = null;
while ((line = bReader.readLine()) != null) {
sBuilder.append(line + "\n");
}
inputStream.close();
result = sBuilder.toString();
} catch (Exception e) {
Log.e("StringBuilding", "Error converting result " + e.toString());
}
return null;
}
protected void onPostExecute(Void v) {
//parse JSON data
try {
JSONObject jobj = new JSONObject(result);
//Taking a JSON Array from the JSONObject created above
String url = jobj.getString("ourUrl");
// We are adding this string to the ArrayList
list.add(url);
progressDialog.dismiss();
Context con = ListLoader.this.getApplication();
adapter = new RecyclerAdapter(list,con);
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
Log.e("JSONException", "Error: " + e.toString());
} // catch (JSONException e)
}
}
/*
your code
*/
Now to display the images more effectively in the list, use the repo Universal image loader. It has a lot of features. You can get it here - https://github.com/nostra13/Android-Universal-Image-Loader
And then add this kind of code to display the images. Put it inside the onBindViewHolder
Adapter
#Override
public void onBindViewHolder(DataHolder holder, int position) {
ImageLoaderConfiguration config;
config = new ImageLoaderConfiguration.Builder(mContext).build();
ImageLoader.getInstance().init(config);
imageLoader = ImageLoader.getInstance();
DisplayImageOptions options = new DisplayImageOptions.Builder()
.showImageForEmptyUri(R.drawable.ic_error_black_48dp) // displays this image not found
.showImageOnFail(R.drawable.ic_error_black_48dp) // Displays this on failure
.showImageOnLoading(R.drawable.white) // Displays while loading
.cacheInMemory(false)
.cacheOnDisk(true)
.build();
imageLoader.displayImage(list.get(position), holder.imageView, options);
// We are feeding the urls here.
}

JSONException:<String>cannot be converted to JSONObject with helps of JSON Array

$ Error:: JSONException:json string cannot be converted to
JSONObject with helps of JSON Array
This is Import libraries
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
activity_main.xml file
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="14dp" >
</ListView>
Internet Permission is Here
<uses-permission android:name="android.permission.INTERNET" />
error Please give me Answer How to get Multiple Values Using this Code and show into my ListView
This Is my MainActivity.java class file.
public class MainActivity extends Activity
{
private String jsonResult;
private String url = "YOUR_PHP_FILE_URL";
private ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView1);
accessWebService();
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
// Async Task to access the web
#SuppressLint("NewApi")
private class JsonReadTask extends AsyncTask<String, Void, String>
{
#Override
protected String doInBackground(String... params)
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try
{
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
}
catch (ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is)
{
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try
{
while ((rLine = rd.readLine()) != null)
{
answer.append(rLine);
Log.d(answer.toString(), "String Builder Class in IF Loop");
}
}
catch (IOException e)
{
// e.printStackTrace();
Toast.makeText(getApplicationContext(),"Error..." + e.toString(), Toast.LENGTH_LONG).show();
Log.d(answer.toString(), "String Builder Class in Else Part");
}
return answer;
}
#Override
protected void onPostExecute(String result)
{
ListDrwaer();
}
}// end async task
public void accessWebService()
{
JsonReadTask task = new JsonReadTask();
// passes values for the urls string array
task.execute(new String[] { url });
}
// build hash set for list view
public <jsonResult> void ListDrwaer()
{
ArrayList<Map<String,String>> userList = new ArrayList<Map<String, String>>();
Log.d(userList.toString(), "Starting JSONObject");
try
{
Log.d("Starting Try Block", "Before JSONObject");
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.getJSONArray("user_info");
Log.d(jsonMainNode.toString(), "Starting JSONObject");
for (int i = 0; i < jsonMainNode.length(); i++)
{
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String id = jsonChildNode.optString("Id:");
String name = jsonChildNode.optString("Name:");
String email = jsonChildNode.optString("Email:");
String phone = jsonChildNode.optString("Phone:");
String password = jsonChildNode.optString("Password");
String outPut = id + "-" + name+ "-" + email+ "-" + phone+ "-" + password;
userList.add(createEmployee("user_info", outPut));
Log.d(jsonChildNode.toString(), "Starting JSONObject inside For Loop");
}
}
catch (JSONException e)
{
Toast.makeText(getApplicationContext(), "Error" + e.toString(),Toast.LENGTH_SHORT).show();
Log.e("log_tag", "Failed data was:\n" + jsonResult);
}
SimpleAdapter simpleAdapter = new SimpleAdapter(this, userList,android.R.layout.simple_list_item_1,new String[] { "user_info" }, new int[] { android.R.id.text1 });
listView.setAdapter(simpleAdapter);
}
private HashMap<String, String> createEmployee(String name, String number)
{
HashMap<String, String> employeeNameNo = new HashMap<String, String>();
employeeNameNo.put(name, number);
return employeeNameNo;
}
}
ok the error you are getting is very generic, error itself tells what you are doing wrong
$ Error:: JSONException:json string cannot be converted to JSONObject with helps of JSON Array,
I believe you have string in the JSON data, "dummy data" as it is in double quotes which you are trying to read as a JSONObject.
It is not a JSONObject but a String primitive type,
while parsing JSON you need to pay attention to what is a Object, Array and primitive-type
JSONObject
will always be enclosed in { } so this represents that data inside a parentheses is a JSONObject,
Example===>
JSONObject json = jsonArray.getJSONObject(i)
or
JSONObject json = new JSONObject("JSON DATA");
JSONArray
will always be enclosed in [ ] so this represents that data inside a square bracket is a JSONArray,
Example==> `json.getJSONArray("name of jsonArray");
Primitive-type
Boolean would like this
"isSelected":true
or
"isSelected":false
Integer would like this
"someInt":12
String would like this
"someString":"String value"
as you can see where your problem is, you need to distinguish between JSON String from JSON Object
Remove this line because you convert Json String to Json Object
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);

Showing data from Arraylist of Hashmap

I'm getting json data and putting it in hashmap and hashmap into an arraylist. All is happening in fragment extending ListFragment
protected String doInBackground(String... urls) {
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("full_name", etUserSearch.getText().toString());
responseReceive = JsonPostClient.SendHttpPost(urls[0],
jsonObject);
} catch (JSONException e) {
e.printStackTrace();
}
try {
Success = responseReceive.getJSONArray("Success");
for (int i = 0; i < Success.length(); i++) {
JSONObject c = Success.getJSONObject(i);
String full_name = c.getString(TAG_FULL_NAME);
String user_name = c.getString(TAG_USER_NAME);
String user_id = c.getString(TAG_USER_ID);
HashMap<String, String> friends = new HashMap<String, String>();
// adding each child node to HashMap key => value
friends.put(TAG_FULL_NAME, full_name);
friends.put(TAG_USER_NAME, user_name);
friends.put(TAG_USER_ID, user_id);
// adding contact to contact list
FriendSearchList.add(friends);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
Log.d("hello", "");
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
printFriends();
};
I'm checking that data is valid by printFriends() method and wanna show only 'TAG_FULL_NAME' data in a listview. My ListView initialization
View rootView = inflater.inflate(R.layout.tab_add_friends, container,
false);
lv = (ListView) rootView.findViewById(R.id.listView);
Method for checking data and loading in ListView
public void printFriends() {
int len = FriendSearchList.size();
for (int i = 0; i < len; i++) {
String f_name = FriendSearchList.get(i).get(TAG_FULL_NAME);
String u_name = FriendSearchList.get(i).get(TAG_USER_NAME);
String u_id = FriendSearchList.get(i).get(TAG_USER_ID);
Log.d("full_name", f_name);
Log.d("user_name", u_name);
Log.d("user_id", u_id);
}
ListAdapter adapter = new SimpleAdapter(getActivity(),
FriendSearchList, R.layout.tab_addfriend_list,
new String[] { TAG_FULL_NAME }, new int[] { R.id.full_name });
setListAdapter(adapter);
}
tab_add_friends xml layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
tab_addfriend_list xml layout
<?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"
android:padding="10dp"
android:paddingLeft="10dp"
android:paddingRight="10dp" >
<!-- Name Label -->
<TextView
android:id="#+id/full_name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:paddingTop="6dip"
android:textColor="#43bd00"
android:textSize="16sp"
android:textStyle="bold" />
</LinearLayout>
There is no error showing just nothing is showing into listview. Need suggestion or clue to get rid of this problem.
I have the same problem once
the problem is you are feeding the data using simple adapter but you may be inflate the rowView outside the ui thread and feed the from the post execute . thtas why your view dont getting the data . actually you dont have to inflate the rowview here is the hole code for you .Another thing print friend method also useless just initialize the simple adapter in the onPostExecute() method.
`public class MainActivity extends ListActivity {
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "http://api.androidhive.info/contacts/";
// 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";
private static final String TAG_ADDRESS = "address";
private static final String TAG_GENDER = "gender";
private static final String TAG_PHONE = "phone";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";
private boolean isConnection = false;
// contacts JSONArray
JSONArray contacts = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
ArrayList<HashMap<String, String>> oflineContactList;
private MyContactDataSource dataSource;
List<Contatcs> oflineContatcs;
// private ListAdapter adapter1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dataSource = new MyContactDataSource(MainActivity.this);
dataSource.open();
contactList = new ArrayList<HashMap<String,String>>();
oflineContactList = dataSource.getContatcs();
Log.i("data", oflineContactList.toString());
ListView lv = getListView();
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, oflineContactList,
R.layout.list_item, new String[] { TAG_NAME, TAG_EMAIL,
TAG_PHONE_MOBILE }, new int[] { R.id.email,
R.id.name, R.id.mobile });
setListAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// getting values from selected ListItem
String name = ((TextView) arg1.findViewById(R.id.name))
.getText().toString();
String cost = ((TextView) arg1.findViewById(R.id.email))
.getText().toString();
String description = ((TextView) arg1.findViewById(R.id.mobile))
.getText().toString();
// Starting single contact activity
Intent intent = new Intent(MainActivity.this, SingleListItemActivity.class);
intent.putExtra(TAG_NAME, name);
intent.putExtra(TAG_EMAIL, cost);
intent.putExtra(TAG_PHONE_MOBILE, description);
startActivity(intent);
}
});
new GetContacts().execute();
}
private class GetContacts extends AsyncTask<Void, Void, Void>{
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Data is loading...please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Creating service handler class instance
ServiceHandler mHandler = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = mHandler.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if(jsonStr != null){
try {
JSONObject jsonObject = new JSONObject(jsonStr);
//Getting JSON Array node
contacts = jsonObject.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);
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_NAME, name);
contact.put(TAG_EMAIL, email);
contact.put(TAG_PHONE_MOBILE, mobile);
// adding contact to contact list
contactList.add(contact);
}
dataSource.creareContacts(contactList);
dataSource.close();
} 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, TAG_EMAIL,
TAG_PHONE_MOBILE }, new int[] { R.id.name,
R.id.email, R.id.mobile });
setListAdapter(adapter);
}
}
}`
The problem is that you are passing an Arraylist of HashMap where SimpleAdapter wont have any idea on which data is to put in the layout of the ListView items.
You can use this to implement items in your ListView
sample:
ListAdapter adapter = new SimpleAdapter(getActivity(),
FriendSearchList, R.layout.tab_addfriend_list,
new String[] { TAG_FULL_NAME }, new int[] { R.id.full_name }){
#Override
public int getCount() {
return FriendSearchList.size();
}
#Override
public View getView(int position,View convertView,ViewGroup parent) {
View v;
if(convertView == null)
{
v = getActivity().getLayoutInflater().inflate(R.layout.tab_addfriend_list, parent);
TextView tx = (TextView) v.findViewById(R.id.full_name);
tx.setText(FriendSearchList.get(i).get(TAG_FULL_NAME));
} else
v = convertView;
return v;
}
};

Why my android app cannot get data from JSON url?

I am trying to run an app based on WorlBank API. I have a JSON URL to get data about a country and then show it in TextViews. Simple. But as soon as I run the app in closes.
Here are my files:
Main Activity:
public class MainActivity extends Activity {
//URL to get JSON Array
private static String url = "http://api.worldbank.org/countries/ir?format=json";
//JSON node Names
private static final String PAGE = "page";
private static final String VALUE = "value";
private static final String NAME = "name";
private static final String GEO = "region";
JSONArray page = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Creating new JSON Parser
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
try{
//Getting JSON Array
page = json.getJSONArray(PAGE);
JSONObject c = page.getJSONObject(0);
//Sorting JSON item in a Variable
String value = c.getString(VALUE);
String name = c.getString(NAME);
String geo = c.getString(GEO);
//Importing to TextView
final TextView id1 = (TextView) findViewById(R.id.id);
final TextView name1 = (TextView) findViewById(R.id.name);
final TextView geo1 = (TextView) findViewById(R.id.geo);
//set JSON Data in TextView
id1.setText(value);
name1.setText(name);
geo1.setText(geo);
} catch (JSONException e){
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
JSONParser:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
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, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
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 {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
XML:
<TextView
android:id="#+id/id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/name"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/id"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/geo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/id"
android:layout_alignParentTop="true"
android:layout_marginTop="76dp"
android:textAppearance="?android:attr/textAppearanceLarge" />
Any idea?
world bank api: http://data.worldbank.org/node/18
UPDATE:
android:minSdkVersion="8"
android:targetSdkVersion="18"
FATAL EXCEPTION: main
E/AndroidRuntime(966): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.jsonsyctask/com.example.jsonsyctask.Main}: android.os.NetworkOnMainThreadException
E/AndroidRuntime(966): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
E/AndroidRuntime(966): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
E/AndroidRuntime(966): at android.app.ActivityThread.access$600(ActivityThread.java:141)
E/AndroidRuntime(966): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
E/AndroidRuntime(966): at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(966): at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime(966): at android.app.ActivityThread.main(ActivityThread.java:5103)
E/AndroidRuntime(966): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(966): at java.lang.reflect.Method.invoke(Method.java:525)
E/AndroidRuntime(966): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
The problem is happening because you are trying to perform network operations on the UI thread. You need to use a background thread for network operations.
Use an AsyncTask as follows:
public class MainActivity extends Activity {
//URL to get JSON Array
private static String url = "http://api.worldbank.org/countries/ir?format=json";
//JSON node Names
private static final String PAGE = "page";
private static final String VALUE = "value";
private static final String NAME = "name";
private static final String GEO = "region";
JSONArray page = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new GetJSONTask().execute(url);
// do not parse here..
...
...
}
...
...
class GetJSONTask extends AsyncTask<String, Void, JSONObject> {
protected JSONObject doInBackground(String... urls) {
try {
JSONParser jParser = new JSONParser();
return jParser.getJSONFromUrl(urls[0]);
} catch (Exception e) {
return null;
}
}
protected void onPostExecute(JSONObject json) {
// do all the parsing here:
try {
//Getting JSON Array
page = json.getJSONArray(PAGE);
JSONObject c = page.getJSONObject(0);
//Sorting JSON item in a Variable
String value = c.getString(VALUE);
String name = c.getString(NAME);
String geo = c.getString(GEO);
//Importing to TextView
final TextView id1 = (TextView) findViewById(R.id.id);
final TextView name1 = (TextView) findViewById(R.id.name);
final TextView geo1 = (TextView) findViewById(R.id.geo);
//set JSON Data in TextView
id1.setText(value);
name1.setText(name);
geo1.setText(geo);
}
catch (JSONException e)
{
e.printStackTrace();
}
}
}
}
Ref: http://developer.android.com/reference/android/os/AsyncTask.html
update another bug spotted, update XML
<TextView
android:id="#+id/id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/name"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge" />
...
...
You cannot have two views and say A below B, then B below A that will cause problems!
You can greatly simplify everything you are doing using droidQuery:
$.ajax(new AjaxOptions().url(url).success(new Function() {
#Override
public void invoke($ d, Object... args) {
JSONObject json = (JSONObject) args[0];
JSONArray page = json.getJSONArray(PAGE);
JSONObject c = page.getJSONObject(0);
$.with(MyActivity.this, R.id.id).text(c.getString(VALUE))
.id(R.id.name).text(c.getString(NAME))
.id(geo).text(c.getString(GEO));
}
}));
I used Kevin Sawicki's HTTP Request Library which is very helpful, find the working example bellow. Don't forget to add android permission
<uses-permission android:name="android.permission.INTERNET" />
Retrieved json value from http://api.worldbank.org/countries/ir?format=json
package com.javasrilankansupport.testhttps;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.github.kevinsawicki.http.HttpRequest;
import com.github.kevinsawicki.http.HttpRequest.HttpRequestException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new DownloadTask().execute("http://api.worldbank.org/countries/ir?format=json");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private class DownloadTask extends AsyncTask<String, Long, Boolean> {
protected Boolean doInBackground(String... urls) {
try {
// kevinsawicki's HttpRequest from github
HttpRequest request = HttpRequest.get(urls[0])
.trustAllCerts() // for HTTPS request
.trustAllHosts() // to trust all hosts
.acceptJson(); // to accept JSON objects
if (request.ok()) {
JSONObject jsonObject;
try {
String s = request.body();
Log.d("MyApp",
"Downloaded json data: "+ s);
// change parameters according to your JSON
jsonObject = new JSONObject(s);
JSONArray jsonArray = jsonObject
.getJSONArray("categories");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObj = jsonArray.getJSONObject(i);
Log.d("MyApp",
"Downloaded json data: "
+ jsonObj.getString("id") + " "
+ jsonObj.getString("slug"));
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
System.out.print("error");
}
} catch (HttpRequestException e) {
e.printStackTrace();
return false;
}
return true;
}
protected void onProgressUpdate(Long... progress) {
// progress bar here
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
}
}
}
Getting data from server require following steps :
make sure your generated json string is in correct format.You can find it on various site.
while requesting from server you must use AsyncTask.
Following example can be helpful to understand the logic
package com.example.sonasys.net;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.sonaprintersd.R;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;
public class SingleContactActivity extends Activity {
private static final String TAG_CONTACTS = "Contacts";
private static final String TAG_POSTLINE = "PostLine";
private static final String TAG_Post_Img = "Post_Img";
private static final String TAG_Post_Img_O = "Post_Img_O";
private static String url;
TextView uid, pid;
JSONArray contacts = null;
private ProgressDialog pDialog;
String details;
// String imagepath = "http://test2.sonasys.net/Content/WallPost/b3.jpg";
String imagepath = "";
Bitmap bitmap;
ImageView image;
String imagepath2;
ArrayList<HashMap<String, String>> contactList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single_contact);
url = "http://test2.sonasys.net/MobileApp/GetSinglePost?UserId="
+ uid.getText() + "&Post_ID=" + pid.getText();
contactList = new ArrayList<HashMap<String, String>>();
new GetContacts().execute();
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(SingleContactActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
// pDialog.setTitle("Post Details");
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
JSONObject c = contacts.getJSONObject(0);
details = c.getString(TAG_POSTLINE);
imagepath = c.getString(TAG_Post_Img);
imagepath2 = c.getString(TAG_Post_Img_O);
} 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();
/**/
TextView Details = (TextView) findViewById(R.id.details);
// Details.setText(details);
Details.setText(android.text.Html.fromHtml(details));
}
}
public class ServiceHandler {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public ServiceHandler() {
}
/*
* Making service call
* #url - url to make request
* #method - http request method
* */
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
/*
* Making service call
* #url - url to make request
* #method - http request method
* #params - http request params
*
* */
public String makeServiceCall(String url, int method,List<NameValuePair> params) {
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
// appending params to url
if (params != null) {
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
My guess is that this is because you're attempting network activity on the main thread. That's a no-no.
Perhaps adding a default exception handler and a breakpoint there will help-
Thread.setDefaultUncaughtExceptionHandler( new Thread.UncaughtExceptionHandler() {
#Override
public void uncaughtException(Thread thread, Throwable throwable) {
throwable.printStackTrace();
}
});

json array shows in logacat with no errors but does not show in android view

A large part of my app is grabbing data from a website. The data shows in my logcat, green with no errors but will not display in my android view. Ive tried and searched for a week or and have had no luck.
here is my class.
public class Json extends ListActivity {
ArrayList<HashMap<String, String>> jsonParser = new ArrayList<HashMap<String, String>>();
ListView lv ;
private static final String jsonFilePath = "http://xda.olinksoftware.com/leaderboard/all";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.json);
new ProgressTask(Json.this).execute();
}
private class ProgressTask extends AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog;
public ProgressTask(Json json) {
Log.i("1", "Called");
context = json;
dialog = new ProgressDialog(context);
}
private Context context;
protected void onPreExecute() {
this.dialog.setMessage("Progress start");
this.dialog.show();
}
#Override
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing()) {
dialog.dismiss();
}
ListAdapter adapter = new SimpleAdapter(context, jsonParser,
R.layout.listitem, new String[] { TAG_NAME, TAG_SCORE,
}, new int[] {
R.id.score, R.id.name,
});
setListAdapter(adapter);
// selecting single ListView item
lv = getListView();
}
#Override
protected Boolean doInBackground(final String... args) {
new JSONParser();
try {
BufferedReader reader = null;
String jsonString = "";
StringBuffer buffer = new StringBuffer();
try{
URL url = new URL(jsonFilePath);
reader = new BufferedReader(new InputStreamReader(url.openStream()));
int read;
char[] chars = new char[1024];
while ((read = reader.read(chars)) != -1)
buffer.append(chars, 0, read);
}finally {
if (reader != null)
reader.close();
}
jsonString = buffer.toString();
try{
JSONParser jsonParser = new JSONParser();
JSONArray leaderboard = (JSONArray)jsonParser.parse(jsonString);
for(int i = 0;i<leaderboard.size();i++){
JSONObject user = (JSONObject)leaderboard.get(i);
System.out.println((i+1) + ". " + user.get("forumName") + " (" + user.get("score") + ")");
}
}catch(ParseException pe){
System.out.println("position: " + pe.getPosition());
System.out.println(pe);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}}
}
and here are my 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="fill_parent"
android:orientation="vertical">
<!-- Main ListView
Always give id value as list(#android:id/list)
-->
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
<?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">
<!-- Product id (pid) - will be HIDDEN - used to pass to other activity -->
<TextView
android:id="#+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:visibility="gone" />
<!-- Name Label -->
<TextView
android:id="#+id/score"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingTop="6dp"
android:paddingLeft="6dp"
android:textSize="17sp"
android:textStyle="bold"/>
</LinearLayout>
any help is greatly appreciated. I know I am doing something wrong with my listview as it also works as a straight java application run in eclipse.
here is the data i am grabbing, i am only taking two values at this time. "forumUser" and "score"
[{"userId":"3579348","userURL":"http:\/\/forum.xda-developers.com\/member.php?u=3579348","forumName":"newtoroot","totalPosts":"5074","postsPerDay":"5.14","totalThanks":"18302","joinDate":"2011-01-29","yearsJoined":"2","referrals":"4","friendCount":"38","recognizedDeveloper":"1","recognizedContributor":"0","recognizedThemer":"0","moderator":"0","recognizedEliteDeveloper":"0","romCount":"48","kernelCount":"0","tutorialCount":"0","modCount":"1","themeCount":"0","score":"302","userName":"","password":""},{"userId":"1596076","userURL":"http:\/\/forum.xda-developers.com\/member.php?u=1596076","forumName":"il Duce","totalPosts":"16335","postsPerDay":"9.75","totalThanks":"15799","joinDate":"2009-02-25","yearsJoined":"4","referrals":"2","friendCount":"83","recognizedDeveloper":"1","recognizedContributor":"0","recognizedThemer":"0","moderator":"1","recognizedEliteDeveloper":"0","romCount":"1","kernelCount":"1","tutorialCount":"0","modCount":"0","themeCount":"0","score":"132","userName":"","password":""},{"userId":"2930301","userURL":"http:\/\/forum.xda-developers.com\/member.php?u=2930301","forumName":"fernando sor","totalPosts":"8967","postsPerDay":"7.93","totalThanks":"4549","joinDate":"2010-09-07","yearsJoined":"3","referrals":"2","friendCount":"29","recognizedDeveloper":"0","recognizedContributor":"0","recognizedThemer":"1","moderator":"0","recognizedEliteDeveloper":"0","romCount":"1","kernelCount":"0","tutorialCount":"5","modCount":"2","themeCount":"15","score":"120","userName":"fernando sor","password":""},{"userId":"3220669","userURL":"http:\/\/forum.xda-developers.com\/member.php?u=3220669","forumName":"1975jamie","totalPosts":"582","postsPerDay":"0.56","totalThanks":"127","joinDate":"2010-11-23","yearsJoined":"2","referrals":"0","friendCount":"0","recognizedDeveloper":"1","recognizedContributor":"0","recognizedThemer":"0","moderator":"0","recognizedEliteDeveloper":"0","romCount":"4","kernelCount":"0","tutorialCount":"0","modCount":"0","themeCount":"0","score":"46","userName":"1975jamie","password":""},{"userId":"2552854","userURL":"http:\/\/forum.xda-developers.com\/member.php?u=2552854","forumName":"jeffsanace","totalPosts":"2797","postsPerDay":"2.25","totalThanks":"2836","joinDate":"2010-05-05","yearsJoined":"3","referrals":"0","friendCount":"12","recognizedDeveloper":"0","recognizedContributor":"1","recognizedThemer":"0","moderator":"0","recognizedEliteDeveloper":"0","romCount":"0","kernelCount":"0","tutorialCount":"0","modCount":"0","themeCount":"0","score":"37","userName":"","password":""},{"userId":"2067958","userURL":"http:\/\/forum.xda-developers.com\/member.php?u=2067958","forumName":"eg1122","totalPosts":"1200","postsPerDay":"0.82","totalThanks":"1695","joinDate":"2009-10-05","yearsJoined":"3","referrals":"0","friendCount":"6","recognizedDeveloper":"0","recognizedContributor":"0","recognizedThemer":"0","moderator":"0","recognizedEliteDeveloper":"0","romCount":"0","kernelCount":"0","tutorialCount":"0","modCount":"2","themeCount":"0","score":"20","userName":"","password":""},{"userId":"3042344","userURL":"http:\/\/forum.xda-developers.com\/member.php?u=3042344","forumName":"dfuse06","totalPosts":"3331","postsPerDay":"3.08","totalThanks":"2270","joinDate":"2010-10-11","yearsJoined":"2","referrals":"1","friendCount":"29","recognizedDeveloper":"0","recognizedContributor":"0","recognizedThemer":"0","moderator":"0","recognizedEliteDeveloper":"0","romCount":"0","kernelCount":"0","tutorialCount":"0","modCount":"1","themeCount":"0","score":"17","userName":"","password":""},{"userId":"1070340","userURL":"http:\/\/forum.xda-developers.com\/member.php?u=1070340","forumName":"chrisloveskaos","totalPosts":"215","postsPerDay":"0.11","totalThanks":"8","joinDate":"2008-07-08","yearsJoined":"5","referrals":"0","friendCount":"7","recognizedDeveloper":"0","recognizedContributor":"0","recognizedThemer":"0","moderator":"0","recognizedEliteDeveloper":"0","romCount":"1","kernelCount":"0","tutorialCount":"0","modCount":"0","themeCount":"0","score":"14","userName":"","password":""},{"userId":"2688514","userURL":"http:\/\/forum.xda-developers.com\/member.php?u=2688514","forumName":"GooTz66","totalPosts":"999","postsPerDay":"0.84","totalThanks":"70","joinDate":"2010-06-25","yearsJoined":"3","referrals":"0","friendCount":"7","recognizedDeveloper":"0","recognizedContributor":"0","recognizedThemer":"0","moderator":"0","recognizedEliteDeveloper":"0","romCount":"0","kernelCount":"0","tutorialCount":"0","modCount":"0","themeCount":"0","score":"7","userName":"","password":""},{"userId":"2141845","userURL":"http:\/\/forum.xda-developers.com\/member.php?u=2141845","forumName":"Kush.Kush\u00c2\u0099","totalPosts":"86","postsPerDay":"0.06","totalThanks":"0","joinDate":"2009-11-09","yearsJoined":"3","referrals":"0","friendCount":"16","recognizedDeveloper":"0","recognizedContributor":"0","recognizedThemer":"0","moderator":"0","recognizedEliteDeveloper":"0","romCount":"0","kernelCount":"0","tutorialCount":"0","modCount":"0","themeCount":"0","score":"6","userName":"","password":""}]
Why is this line
setListAdapter(adapter);
Before this
// selecting single ListView item
lv = getListView();
Also, the LogCat you posted is showing the results using the "info" filter only. Try looking at the verbose view to make sure no exceptions that you're missing.
what i did to solve this was pretty much start over. i added a JSONParser class
public class JSONParser {
static InputStream is = null;
static JSONArray jarray = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONArray getJSONFromUrl(String url) {
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} else {
Log.e("==>", "Failed to download file");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// try parse the string to a JSON object
try {
jarray = new JSONArray( builder.toString());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jarray;
and a JsonActivity
public class MainActivity extends ListActivity {
private static String url = "website";
private static final String TAG_VTYPE = "forumName";
private static final String TAG_VCOLOR = "score";
private static final String TAG_THANKS = "totalThanks";
private static final String TAG_POSTS = "totalPosts";
private static final String TAG_JOIN_DATE = "joinDate";
private static final String TAG_ROM_COUNT = "romCount";
private static final String TAG_THEME_COUNT = "themeCount";
private static final String TAG_MOD_COUNT = "modCount";
private static final String TAG_KERNEL_COUNT = "kernelCount";
private static final String TAG_TUTORIAL_COUNT = "tutorialCount";
private static final String TAG_DEV = "recognizedDeveloper";
private static final String TAG_THEMER = "recognizedThemer";
private static final String TAG_MODERATOR = "moderator";
private static final String TAG_RDEV = "recognizedEliteDeveloper";
private static final String TAG_RCOD = "recognizedContributor";
ArrayList<HashMap<String, String>> jsonlist = new ArrayList<HashMap<String, String>>();
private View header;
ListView lv ;
LayoutInflater Inflater;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_view);
Inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
new ProgressTask(MainActivity.this).execute();
}
private class ProgressTask extends AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog;
private ListActivity activity;
// private List<Message> messages;
public ProgressTask(ListActivity activity) {
this.activity = activity;
context = activity;
dialog = new ProgressDialog(context);
}
/** progress dialog to show user that the backup is processing. */
/** application context. */
private Context context;
protected void onPreExecute() {
this.dialog.setMessage("Progress start");
this.dialog.show();
}
#Override
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing()) {
dialog.dismiss();
}
View header = Inflater.inflate(R.layout.header_view_name, null);
ListAdapter adapter = new SimpleAdapter(context, jsonlist,
R.layout.list_item, new String[] { TAG_VTYPE, TAG_VCOLOR, TAG_THANKS, TAG_POSTS, TAG_JOIN_DATE, TAG_ROM_COUNT,
TAG_THEME_COUNT, TAG_MOD_COUNT, TAG_KERNEL_COUNT, TAG_DEV, TAG_TUTORIAL_COUNT, TAG_THEMER, TAG_MODERATOR, TAG_RDEV, TAG_RCOD,
}, new int[] {
R.id.vehicleType, R.id.vehicleColor, R.id.totalThanks, R.id.totalPosts, R.id.joinDate, R.id.romCount,
R.id.themeCount, R.id.kernelCount, R.id.modCount, R.id.tutorialCount, R.id.moderator, R.id.rThemer, R.id.rDev,
R.id.rCon, R.id.rEliteDev,
});
lv = getListView();
lv.addHeaderView(header);
setListAdapter(adapter);
// selecting single ListView item
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener() {
;
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// getting values from selected ListItem
String forumName = ((TextView) view.findViewById(R.id.vehicleType)).getText().toString();
String score = ((TextView) view.findViewById(R.id.vehicleColor)).getText().toString();
String totalThanks = ((TextView) view.findViewById(R.id.totalThanks)).getText().toString();
String totalPosts = ((TextView) view.findViewById(R.id.totalPosts)).getText().toString();
String joinDate = ((TextView) view.findViewById(R.id.joinDate)).getText().toString();
String romCount = ((TextView) view.findViewById(R.id.romCount)).getText().toString();
String themeCount = ((TextView) view.findViewById(R.id.themeCount)).getText().toString();
String kernelCount = ((TextView) view.findViewById(R.id.kernelCount)).getText().toString();
String modCount = ((TextView) view.findViewById(R.id.modCount)).getText().toString();
String tutorialCount = ((TextView) view.findViewById(R.id.tutorialCount)).getText().toString();
String moderator = ((TextView) view.findViewById(R.id.moderator)).getText().toString();
String recognizedThemer = ((TextView) view.findViewById(R.id.rThemer)).getText().toString();
String recognizedDeveloper = ((TextView) view.findViewById(R.id.rDev)).getText().toString();
String recognizedContributor = ((TextView) view.findViewById(R.id.rCon)).getText().toString();
String recognizedEliteDeveloper = ((TextView) view.findViewById(R.id.rEliteDev)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(TAG_VTYPE, forumName);
in.putExtra(TAG_VCOLOR, score);
in.putExtra(TAG_THANKS, totalThanks);
in.putExtra(TAG_POSTS, totalPosts);
in.putExtra(TAG_JOIN_DATE, joinDate);
in.putExtra(TAG_ROM_COUNT, romCount);
in.putExtra(TAG_THEME_COUNT, themeCount);
in.putExtra(TAG_MOD_COUNT, modCount);
in.putExtra(TAG_KERNEL_COUNT, kernelCount);
in.putExtra(TAG_TUTORIAL_COUNT, tutorialCount);
in.putExtra(TAG_DEV, recognizedDeveloper);
in.putExtra(TAG_THEMER, recognizedThemer);
in.putExtra(TAG_MODERATOR, moderator);
in.putExtra(TAG_RDEV, recognizedEliteDeveloper);
in.putExtra(TAG_RCOD, recognizedContributor);
startActivity(in);
}});}
protected Boolean doInBackground(final String... args) {
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONArray json = jParser.getJSONFromUrl(url);
for (int i = 0; i < json.length(); i++) {
try {
JSONObject c = json.getJSONObject(i);
String forumName = c.getString(TAG_VTYPE);
String score = c.getString(TAG_VCOLOR);
String totalThanks = c.getString(TAG_THANKS);
String totalPosts = c.getString(TAG_POSTS);
String joinDate = c.getString(TAG_JOIN_DATE);
String romCount = c.getString(TAG_ROM_COUNT);
String themeCount = c.getString(TAG_THEME_COUNT);
String modCount = c.getString(TAG_MOD_COUNT);
String kernelCount = c.getString(TAG_KERNEL_COUNT);
String tutorialCount = c.getString(TAG_TUTORIAL_COUNT);
String recognizedDeveloper = c.getString(TAG_DEV);
String recognizedThemer = c.getString(TAG_THEMER);
String moderator = c.getString(TAG_MODERATOR);
String recognizedEliteDeveloper = c.getString(TAG_RDEV);
String recognizedContributor = c.getString(TAG_RCOD);
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_VTYPE, forumName);
map.put(TAG_VCOLOR, score);
map.put(TAG_THANKS, totalThanks);
map.put(TAG_POSTS, totalPosts);
map.put(TAG_JOIN_DATE, joinDate);
map.put(TAG_ROM_COUNT, romCount);
map.put(TAG_THEME_COUNT, themeCount);
map.put(TAG_MOD_COUNT, modCount);
map.put(TAG_KERNEL_COUNT, kernelCount);
map.put(TAG_TUTORIAL_COUNT, tutorialCount);
map.put(TAG_DEV, recognizedDeveloper);
map.put(TAG_THEMER, recognizedThemer);
map.put(TAG_MODERATOR, moderator);
map.put(TAG_RDEV, recognizedEliteDeveloper);
map.put(TAG_RCOD, recognizedContributor);
jsonlist.add(map);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}}}
and tied it together with a list view and xml for all my values. turned out really cool. i added an onclick on each value to show more individual data

Categories