Related
Im trying to parse json array data into listview!I searched the whole internet and always was on one point! Json aray must have header something like this
"emp_info":[{"employee name":"Adam","employee no":"101700"},{"employee name":"John","employee no":"101701"},{"employee name":"Paul","employee no":"101702"},{"employee name":"Mark","employee no":"101703"},{"employee name":"Donald","employee no":"101704"},{"employee name":"Brain","employee no":"101705"},{"employee name":"Kevin","employee no":"101706"}]}
Where by my understanding the "emp_info" is the header file by which i must search for rest data inside it in android!My College pretending that i can accept and parse the same data into listview without that header name,but every bit of code where i searched to parse json in android was a single line like this!
JSONObject obj = new JSONObject(jsonString);
JSONArray stations = obj.getJSONArray("emp_inf");
where i just have to put the jsonarray header file as you can see in this piece of code!So please help me is that possible to accept json array without this code?because if i try to remove this code i get nullpointer in my code!Will be very happy if you could at least say yes or no!
Posting Full Codes!
Here is the android class which gets the Json and loads it into List View
private class JsonReadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://54.148.41.171/server/index/dompy");
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);
}
}
catch (IOException e) {
// e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error..." + e.toString(), Toast.LENGTH_LONG).show();
}
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 void ListDrwaer() {
List<Map<String, String>> employeeList = new ArrayList<Map<String, String>>();
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("emp_info");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String name = jsonChildNode.optString("empployee no");
String number = jsonChildNode.optString("etc.");
String outPut = name + "-" + number;
employeeList.add(createEmployee("data", outPut));
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
SimpleAdapter simpleAdapter = new SimpleAdapter(this, employeeList,
android.R.layout.simple_list_item_1,
new String[] { "employee no" }, 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;
}
}
And by this json array im successfully able to fetch the json which type is the next!
{"emp_info":[{"employee name":"Adam","employee no":"101700"},{"employee name":"John","employee no":"101701"},{"employee name":"Paul","employee no":"101702"},{"employee name":"Mark","employee no":"101703"},{"employee name":"Donald","employee no":"101704"},{"employee name":"Brain","employee no":"101705"},{"employee name":"Kevin","employee no":"101706"}]}
And here is the json array which my college pretends that i must accept!
{"data":"123"}
And im Saying that its not possible to load this json into list view just because it dont have header file like mine the emp_info,but hes saying its not matter i just MUST accept!We just on same project and i just cant understand is it even possible to do what he says?
String name = jsonChildNode.optString("empployee no");
String number = jsonChildNode.optString("etc.");
How can you get the data by "etc." tag I could not understand it firstly. It should return "" instead of employee number.
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);
}
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);
Hi in my application I am using jsonurl to displaying text with image.I want to parse the image and text ,But it showing unfortunately error and my application got crashed.can any one please help me.
CustomizedListView.java:
public class CustomizedListView extends Activity {
// All static variables
static final String URL = "http://indianpoliticalleadersmap.com/android/DemoSchool/json/json_item.php";
// XML node keys
static final String TAG_SCHEDULES = "veg_food"; // parent node
static final String TAG_ID = "id";
static final String TAG_TITLE = "itemname";
static final String TAG_THUMB_URL = "image";
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>>();
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML from URL
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(TAG_SCHEDULES);
// looping through all song nodes <song>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
map.put(TAG_ID, parser.getValue(e, TAG_ID));
map.put(TAG_TITLE, parser.getValue(e, TAG_TITLE));
map.put(TAG_THUMB_URL, parser.getValue(e, TAG_THUMB_URL));
// adding HashList to ArrayList
songsList.add(map);
}
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) {
}
});
}
}
There is a difference between JSON and XML parsing. Take a look at the code below. Here I am parsing the date coming from a database into a listview.
Activity class:
public static class EventFragment extends ListFragment {
ArrayList<HashMap<String, String>> eventsList;
private String url_all_events = //url goes here;
private ProgressDialog pDialog;
JSONParser jParser = new JSONParser();
// JSON Node names
private static final String CONNECTION_STATUS = "success";
private static final String TABLE_EVENT = "Event";
private static final String pid = "pid";
private static final String COL_GROUP = "Group";
private static final String COL_NAME = "Event_Name";
private static final String COL_DESC = "Event_Desc";
private static final String COL_DATE = "Event_Date";
private static final String COL_TIME = "Event_Time";
JSONArray Events = null;
public static final String ARG_SECTION_NUMBER = "section_number";
public EventFragment() {
}
public void onStart() {
super.onStart();
eventsList = new ArrayList<HashMap<String, String>>();
new LoadAllEvents().execute();
// selecting single ListView item
ListView lv = getListView();
// Lauching the Event details screen on selecting a single event
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String ID = ((TextView) view.findViewById(R.id.pid))
.getText().toString();
Intent intent = new Intent(view.getContext(),
EventDetails.class);
intent.putExtra(pid, ID);
view.getContext().startActivity(intent);
}
});
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_events,
container, false);
return rootView;
}
class LoadAllEvents extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Just a moment...");
pDialog.setIndeterminate(true);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_events,
"GET", params);
try {
// Checking for SUCCESS TAG
int success = json.getInt(CONNECTION_STATUS);
if (success == 1) {
// products found
// Getting Array of Products
Events = json.getJSONArray(TABLE_EVENT);
// looping through All Contacts
for (int i = 0; i < Events.length(); i++) {
JSONObject evt = Events.getJSONObject(i);
// Storing each json item in variable
id = evt.getString(pid);
group = evt.getString(COL_GROUP);
name = evt.getString(COL_NAME);
desc = evt.getString(COL_DESC);
date = evt.getString(COL_DATE);
time = evt.getString(COL_TIME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(pid, id);
map.put(COL_GROUP, group);
map.put(COL_NAME, name);
map.put(COL_DESC, desc);
map.put(COL_DATE, date);
map.put(COL_TIME, time);
// adding HashList to ArrayList
eventsList.add(map);
}
} else {
// Options are not available or server is down.
// Dismiss the loading dialog and display an alert
// onPostExecute
pDialog.dismiss();
}
} 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
getActivity().runOnUiThread(new Runnable() {
public void run() {
ListAdapter adapter = new SimpleAdapter(getActivity(),
eventsList, R.layout.list_item, new String[] {
pid, COL_GROUP, COL_NAME, COL_DATE, COL_TIME },
new int[] { R.id.pid, R.id.group, R.id.name, R.id.header,
R.id.title2 });
setListAdapter(adapter);
}
});
}
}
}
JSON Parser class
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if (method == "POST") {
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} else if (method == "GET") {
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "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;
}
}
Hope this helps :)
Background : I am trying to develop my first android application which is a student discussion panel. I am good with PHP and MySQL but don't have much experience in android Java.
Issue:
In SelectedQuestionActivity class, if I simply give the URL as http://thewbs.getfreehosting.co.uk/talky/fetchans.php?qid=3, it works just fine and it fetches the corresponding answer to the question.
But if I do it the way I have shown in the code below, the application crashes. I am not sure where I am wrong.
CODE:
AllQuestionActivity.java
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String pid = ((TextView) view.findViewById(R.id.qid)).getText()
.toString();
//pid is the value of the selected question for example www.example.com/fetchans?qid=3 so here pid value is supposed to be 3.
// Starting new intent
Intent in = new Intent(getApplicationContext(),
SelectedQuestionActivity.class);
// sending pid to next activity
in.putExtra(TAG_PID, pid);
startActivity(in);
}
});
Now in SelectedQuestionActivity.java
code:
public class SelectedQuestionActivity extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
Intent intent = getIntent();
String qid = intent.getExtras().getString(TAG_PID);
// url to get all products list
private String url_all_products = "http://thewbs.getfreehosting.co.uk/talky/fetchans.php?qid="+qid;
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "ques";
private static final String TAG_PID = "aid";
private static final String TAG_NAME = "aname";
private static final String TAG_INFO = "answer";
private static final String TAG_DATE = "date";
// products JSONArray
JSONArray products = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_ans);
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
// Get listview
ListView lv = getListView();
}
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SelectedQuestionActivity.this);
pDialog.setMessage("Loading Answers. 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.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Answers: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
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 info = c.getString(TAG_INFO);
String date = c.getString(TAG_DATE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_NAME, name);
map.put(TAG_INFO, info);
map.put(TAG_DATE, date);
// adding HashList to ArrayList
productsList.add(map);
}
}
else {
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
SelectedQuestionActivity.this, productsList,
R.layout.list_selected_ques, new String[] { TAG_PID,
TAG_NAME, TAG_INFO, TAG_DATE },
new int[] { R.id.aid, R.id.aname, R.id.answer, R.id.date});
// updating listview
setListAdapter(adapter);
}
});
}
}
}
JSONparser.java
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET method
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "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;
}
}
Currently you are trying to getIntent outside onCreate of ListActivity so move it inside onCreate method as :
Intent intent;
String qid;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_ans);
// get Intent here
intent = getIntent();
qid = intent.getExtras().getString(TAG_PID);
// your code here
and also no need to use runOnUiThread method for updating UI from onPostExecute because onPostExecute method called on Ui thread we can access UI elements in it
EDIT:-
you are not adding any paramter to NameValuePair inside doInBackground . add quid before sending it to makeHttpRequest as :
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
add quid param here
params.add(new BasicNameValuePair("qid",qid)); //<<<< add here
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(
url_all_products,
"GET",
params);
// your code here
You are passing a string from one activity object to another , while you didn't write code to receive it on the new activity in the right place.
To solve this you should add some code to your onCreate:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_ans);
String url = getIntent().getStringExtra(TAG_PID);
if (url != null)
url_all_products = url;
You should need to get your intent values in onCreate() as below :
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_ans);
Intent intent = getIntent();
String qid = intent.getExtras().getString(TAG_PID);
}