lundi 9 mars 2015

Android parsing Json error



I having an error while parsing json array in my android application.


My json object is in the following form: {"post":[ [{"0":"all the best to every one...!!","post":"all the best to every one...!!"}, {"0":"hello every one...","post":"hello every one..."}] ]}


My java file in android is as follows:



public class Newsactivity extends ListActivity {

private static final String TAG_SUCCESS = "";

private ProgressDialog pDialog;


JSONParser jParser = new JSONParser();

ArrayList<HashMap<String, String>> postsList;


private static String url_all_products = "myurl";


private static final String TAG_POST = "post";



JSONArray posts = null;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.allposts);


postsList = new ArrayList<HashMap<String, String>>();


new LoadAllProducts().execute();


ListView lv = getListView();


}





class LoadAllProducts extends AsyncTask<String, String, String> {


@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Newsactivity.this);
pDialog.setMessage("Loading posts. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}


protected String doInBackground(String... args) {

List<NameValuePair> params = new ArrayList<NameValuePair>();

JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);


Log.d("All Posts: ", json.toString());

try {

posts = json.getJSONArray(TAG_POST);


for (int i = 0; i < posts.length(); i++) {
JSONObject c = posts.getJSONObject(i);


String post = c.getString(TAG_POST);

HashMap<String,String> map = new HashMap<String,String>();


map.put(TAG_POST, post);

postsList.add(map);
}

} catch (JSONException e) {
e.printStackTrace();
}

return null;
}


protected void onPostExecute(String file_url) {

pDialog.dismiss();

runOnUiThread(new Runnable() {
public void run() {

ListAdapter adapter = new SimpleAdapter(
Newsactivity.this, postsList,
R.layout.singlepost, new String[] { TAG_POST},
new int[] { R.id.pid});

setListAdapter(adapter);
}
});

}

}







@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_newsactivity, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

int id = item.getItemId();


if (id == R.id.action_settings) {
return true;
}

return super.onOptionsItemSelected(item);
}


}


I am getting a fatal exception starting this activity. This code is modified code of an online tutorial on json parsing. As I am new to android I am unable to find where the id is. So, please help me. Thank you.




Aucun commentaire:

Enregistrer un commentaire