i want to populate listview with json parser. but i have following error:
12-12 22:49:39.812: ERROR/JSON Parser(1254): Error parsing data org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject
JSONParse:
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;
}
}
UpdateFromSite:
public class UpdateFromSite extends Activity {
ListView list;
TextView name;
TextView description;
TextView price;
Button Btngetdata;
ArrayList<HashMap<String, String>> newItemlist = new ArrayList<HashMap<String, String>>();
//URL to get JSON Array
private static String url = "http://www.karocellen.com/newItem.json";
//JSON Node Names
private static final String TAG_ITEM = "NewItem";
private static final String TAG_NAME = "name";
private static final String TAG_DESCRIPTION = "description";
private static final String TAG_PRICE = "price";
JSONArray NewItem = null;
#Override
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.updateapp);
newItemlist = new ArrayList<HashMap<String, String>>();
Btngetdata = (Button)findViewById(R.id.getdata);
Btngetdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//check internet connection
Boolean isInternetPresent = false;
ConnectionDetector cd;
cd = new ConnectionDetector(getApplicationContext());
isInternetPresent = cd.isConnectingToInternet();
if (isInternetPresent) {
new JSONParse().execute(); }
else {
Toast.makeText(getApplicationContext(),"You don't have internet connection.",Toast.LENGTH_SHORT).show();
}
}
});
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
name = (TextView)findViewById(R.id.nameNewItem);
description = (TextView)findViewById(R.id.descriptionNewItem);
price = (TextView)findViewById(R.id.priceNewItem);
pDialog = new ProgressDialog(UpdateFromSite.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
try {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
} catch (Exception ex){
Toast.makeText(getApplicationContext(),"network problem",Toast.LENGTH_SHORT).show();
return null;
}
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array from URL
NewItem = json.getJSONArray(TAG_ITEM);
for(int i = 0; i < NewItem.length(); i++){
JSONObject c = NewItem.getJSONObject(i);
// Storing JSON item in a Variable
String name = c.getString(TAG_NAME);
String description = c.getString(TAG_DESCRIPTION);
int price = c.getInt(TAG_PRICE);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_NAME, name);
map.put(TAG_DESCRIPTION, description);
map.put(TAG_PRICE, Integer.toString(price));
newItemlist.add(map);
list=(ListView)findViewById(R.id.listupdate);
ListAdapter adapter = new SimpleAdapter(UpdateFromSite.this, newItemlist,
R.layout.updateapprow,
new String[] { TAG_NAME,TAG_DESCRIPTION, TAG_PRICE }, new int[] {
R.id.nameNewItem,R.id.descriptionNewItem, R.id.priceNewItem});
list.setAdapter(adapter);
});
}
}
catch (Exception e) {
Toast.makeText(getApplicationContext(),"network problem",Toast.LENGTH_SHORT).show();
}
}
}
}
myJSON:
{"NewItem":[{"name":"Roast Ground Coffee","description":"Folgers Medium Classic Roast Ground Coffee 339 oz","price":8},{"name":"Seattle coffee","description":"Seattles Best Coffee Level 3 Whole Bean 12oz","price":10},{"name":"Medium Roast Bean Coffee","description":"Dunkin Donuts Original Blend Medium Roast Whole Bean Coffee 12 oz","price":6},{"name":"Espresso coffee","description":"Starbucks Dark Espresso Roast Whole Bean Coffee 12 oz","price":12},
{"name":"China Green Tea","description":"Tazo China Green Tips Tea 20 filterbags","price":8},{"name":"China Organic Green","description":"Uncle Lees Legends of China Organic Green Tea 100 Tea Bags","price":15},{"name":"Black Tea","description":"Tazo Earl Grey Black Tea 20 count","price":10},{"name":"Chai Spiced Black Tea","description":"Tazo Decaf Chai Spiced Black Tea Latte Concentrate 32 oz","price":5},
{"name":"Passion Tea","description":"Tazo Iced Passion Tea 6ct","price":11},{"name":"Peach Iced Tea","description":"Lipton Diet Peach Iced Tea Mix 2.9 oz","price":12}]}
Error parsing data org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject
Looks like what you get is a String and you are trying to convert it into a JSONObject
You do a HttpPost instead of HttGet
HttpPost httpPost = new HttpPost(url);
Should be
HttpGet httpget = new HttpGet(url);
Your json
{ // json object node
"NewItem": [ // json array NewItem
{ // json object node
"name": "Roast Ground Coffee", // string
"description": "Folgers Medium Classic Roast Ground Coffee 339 oz",
"price": 8
},
Second Mistake
catch (Exception ex){
Toast.makeText(getApplicationContext(),"network problem",Toast.LENGTH_SHORT).show();
return null;
Displaying toast in doInbackground. you cannot update ui indoInbackground
Complete Example with Snap Shot:
test.java
public class test extends Activity {
ListView list;
Button Btngetdata;
ProgressDialog pDialog;
ArrayList<HashMap<String, String>> newItemlist = new ArrayList<HashMap<String, String>>();
private static final String TAG_ITEM = "NewItem";
private static final String TAG_NAME = "name";
private static final String TAG_DESCRIPTION = "description";
private static final String TAG_PRICE = "price";
#Override
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.test);
pDialog = new ProgressDialog(test.this);
pDialog.setMessage("Getting Data ...");
newItemlist = new ArrayList<HashMap<String, String>>();
Btngetdata = (Button)findViewById(R.id.button1);
Btngetdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new JSONParse().execute();
}
});
}
private class JSONParse extends AsyncTask<String, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog.show();
}
#Override
protected Void doInBackground(String... args) {
try {
Log.i("...............","Hello..............");
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpPost = new HttpGet("http://www.karocellen.com/newItem.json");
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
String jsonstring = EntityUtils.toString(httpEntity);
Log.i("...............",jsonstring);
JSONObject json = new JSONObject(jsonstring);
JSONArray newitem = json.getJSONArray(TAG_ITEM);
for(int i = 0; i < newitem.length(); i++){
JSONObject c = newitem.getJSONObject(i);
String name = c.getString(TAG_NAME);
String description = c.getString(TAG_DESCRIPTION);
String price = c.getString(TAG_PRICE);
Log.i("...............",name);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_NAME, name);
map.put(TAG_DESCRIPTION, description);
map.put(TAG_PRICE, price);
newItemlist.add(map);
}
} catch (Exception ex){
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
pDialog.dismiss();
list=(ListView)findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(test.this, newItemlist,
R.layout.second,
new String[] { TAG_NAME,TAG_DESCRIPTION, TAG_PRICE }, new int[] {
R.id.textView1,R.id.textView2, R.id.textView3});
list.setAdapter(adapter);
}
}
}
test.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/button1"
/>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="Button" />
</RelativeLayout>
second.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="16dp"
android:text="TextView" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_below="#+id/textView1"
android:layout_marginTop="50dp"
android:text="TextView" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView2"
android:layout_below="#+id/textView2"
android:layout_marginTop="56dp"
android:text="TextView" />
</RelativeLayout>
Snap
Your page is not generating the JSON correctly,
"<!DOCTYPE"
seems you are feeding in some HTML before outputting your JSON string.
Change your json response should be for price like...
{
"NewItem": [
{
"name": "Roast Ground Coffee",
"description": "Folgers Medium Classic Roast Ground Coffee 339 oz",
"price": "8"
}
]
}
get price value as string and then you can cast it into (Integer value) in your code.
Related
I'm trying to get the values from my mySql database and display them in a listView. However when I click the button to display them I get the following error message : org.json.JSONException: No value for establishments.
I know that the TAG_RESULTS is empty but I don't know what I'm supposed to put in to it.
Here is my code
public class SecondPage extends AppCompatActivity {
String myJSON;
//There is no value for this TAG_RESULTS ON LINE 116
private static final String TAG_RESULTS="establishments";
private static final String TAG_NAME = "name";
private static final String TAG_PICTURE = "picture";
JSONArray establishments_JSON = null;
ArrayList<HashMap<String, String>> establishmentsList;
//JSONArray establishments = null;
//Array establishments = null;
ListView listView ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.current_location_listview);
listView = (ListView) findViewById(R.id.listView);
establishmentsList = new ArrayList<HashMap<String,String>>();
getData();
}
public void getData(){
//changed the middle parameter to a string from a void
class GetDataJSON extends AsyncTask<String, Void, String> {
protected String doInBackground(String... params) {
Log.d("GETTING JSON DATA", "HERE....");
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://10.102.11.109/findandeat_xampp_data/get_all_establishments.php");
//String loginDetails = ServerConnection.RUSH_SERVER_ADDRESS + "login.php?userName=" + userNameInput + "&password=" + passwordInput;
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
Log.d("STARTING INPUT STREAM", "HERE....");
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);
}
result = sb.toString();
} catch (Exception e) {
// Oops
Log.d("CATCH ANY ERRORS", "HERE....");
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
#Override
protected void onPostExecute(String result){
myJSON=result;
Log.d("myjson",myJSON);
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
protected void showList(){
try {
Log.d("myjson",myJSON);
JSONObject jsonObj = new JSONObject(myJSON);
establishments_JSON = jsonObj.getJSONArray(TAG_RESULTS);
for(int i=0;i<establishments_JSON.length();i++){
JSONObject c = establishments_JSON.getJSONObject(i);
String pizzeriaName = c.getString(TAG_NAME);
String pizzeriaPicture = c.getString(TAG_PICTURE);
String chineseName = c.getString(TAG_NAME);
String chinesePicture = c.getString(TAG_PICTURE);
String cafeName = c.getString(TAG_NAME);
String cafePicture = c.getString(TAG_PICTURE);
String indianName = c.getString(TAG_NAME);
String indianPicture = c.getString(TAG_PICTURE);
String ChipShopName = c.getString(TAG_NAME);
String ChipShopPicture = c.getString(TAG_PICTURE);
//Error im getting is that there is no value for the result
//with the JSON
HashMap<String,String> establishment_items = new HashMap<String,String>();
establishment_items.put(TAG_NAME,pizzeriaName);
establishment_items.put(TAG_PICTURE,pizzeriaPicture);
establishment_items.put(TAG_NAME,chineseName);
establishment_items.put(TAG_PICTURE,chinesePicture);
establishment_items.put(TAG_NAME,cafeName);
establishment_items.put(TAG_PICTURE,cafePicture);
establishment_items.put(TAG_NAME,indianName);
establishment_items.put(TAG_PICTURE,indianPicture);
establishment_items.put(TAG_NAME,ChipShopName);
establishment_items.put(TAG_PICTURE,ChipShopPicture);
establishmentsList.add(establishment_items);
}
ListAdapter adapter = new SimpleAdapter(
SecondPage.this, establishmentsList, R.layout.activity_current_location_items,
new String[]{TAG_NAME,TAG_PICTURE},
new int[]{R.id.establishment_name, R.id.establishment_picture}
);
listView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
XMLdatabase column names
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/listView" />
column name in database
The other types of restuarants have the same naming system applied
It will generate this error because there is the parameter you want. So you can validate:
//if exists
if(jsonObj.has(TAG_RESULTS)){
}
The same should do to verify certain parameters exist or not in the JSON object, so you save trouble with exceptions.
use .has(String) and isNull(String)
.has(String) checks if the JSONObject contains a specific key
.isNull(String) checks if the value associated with the key is null or if there is no value
So , your code will be
if (jsonObj.has(TAG_RESULTS) && !jsonObj.isNull(TAG_RESULTS)) {
establishments_JSON = jsonObj.getJSONArray(TAG_RESULTS);
}
I hope to be helpful for you .
I've a problem with parsing json from facebook graph api.
When I'm using facebook URL:https://graph.facebook.com/interstacjapl/feed?access_token=MyTOKEN to grab json it's no working, but when I copied that json (it works in browser) and paste to my webiste http://mywebsite/fb.json and change site URL in the code, it works good.
When I'm using fb graph URL it shows error:
W/System.err(5534): org.json.JSONException: No value for data
Is this problem with parsing from https or URL or code?
JSONParser.java
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;
}
}
MainActivity
public class MainActivity extends Activity {
ListView list;
TextView ver;
TextView name;
TextView api;
Button Btngetdata;
ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
//URL to get JSON Array
private static String url = "https://graph.facebook.com/interstacjapl/feed?access_token=CAACEdEose0cBANLR...";
//JSON Node Names
private static final String TAG = "data";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "message";
private static final String TAG_API = "type";
JSONArray android = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
oslist = new ArrayList<HashMap<String, String>>();
Btngetdata = (Button)findViewById(R.id.getdata);
Btngetdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new JSONParse().execute();
}
});
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
ver = (TextView)findViewById(R.id.vers);
name = (TextView)findViewById(R.id.name);
api = (TextView)findViewById(R.id.api);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array from URL
android = json.getJSONArray(TAG);
for(int i = 0; i < android.length(); i++){
JSONObject c = android.getJSONObject(i);
// Storing JSON item in a Variable
String ver = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String api = c.getString(TAG_API);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_ID, ver);
map.put(TAG_NAME, name);
map.put(TAG_API, api);
oslist.add(map);
list=(ListView)findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, oslist,
R.layout.list_v,
new String[] { TAG_ID,TAG_NAME, TAG_API }, new int[] {
R.id.vers,R.id.name, R.id.api});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, "You Clicked at "+oslist.get(+position).get("name"), Toast.LENGTH_SHORT).show();
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
This works
String reply = "";
BufferedReader inStream = null;
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpRequest = new HttpGet(url);
try {
HttpResponse response = httpClient.execute(httpRequest);
inStream = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent()));
StringBuffer buffer = new StringBuffer("");
String line = "";
while ((line = inStream.readLine()) != null) {
buffer.append(line);
}
inStream.close();
reply = buffer.toString();
} catch (Exception e) {
//Handle Execptions
}
I'm trying to get JSON value by EditText.
At first I had a bunch of nullpointer exceptions, solved that. But now my function just isn't working. Been wrapping my brain over this...
I tried to create a EditText, get that value to a String, and get it over to the JSON Object. Don't know what I'm doing wrong... Or am I forgetting something?
public class MyActivity extends Activity {
TextView uid;
TextView name1;
TextView email1;
EditText edt;
Button Btngetdata;
//URL to get JSON Array
private static String url = "*";
//JSON Node Names
private static final String TAG_TAG = "tag";
private static final String TAG_ID = "id";
private static final String TAG_LAST_NAME = "last_name";
private static final String TAG_EMAIL = "country";
JSONArray user = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
Btngetdata = (Button)findViewById(R.id.getdata);
edt = (EditText)findViewById(R.id.edittext);
Btngetdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new JSONParse().execute();
}
});
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
uid = (TextView)findViewById(R.id.uid);
name1 = (TextView)findViewById(R.id.name);
email1 = (TextView)findViewById(R.id.email);
pDialog = new ProgressDialog(MyActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array
user = json.getJSONArray(TAG_TAG);
JSONObject c = user.getJSONObject(0);
String xyz = edt.getText().toString();
// Storing JSON item in a Variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_LAST_NAME);
String email = c.getString(TAG_EMAIL);
//Set JSON Data in TextView
uid.setText(id);
name1.setText(name);
email1.setText(email);
edt.setText(xyz);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
{"tag":[{"id":"1","first_name":"Philip","last_name":"Porter","email":"pporter0#admin.ch","country":"China","ip_address":"26.83.255.206"},{"id":"2","first_name":"Nancy","last_name":"Martin","email":"nmartin1#google.ca","country":"Colombia","ip_address":"160.93.80.1"},{"id":"3","first_name":"Ann","last_name":"Peterson","email":"apeterson2#utexas.edu","country":"China","ip_address":"251.254.74.162"},{"id":"4","first_name":"Rachel","last_name":"Clark","email":"rclark3#mayoclinic.com","country":"Brazil","ip_address":"58.218.248.5"},{"id":"5","first_name":"Heather","last_name":"Burton","email":"hburton4#creativecommons.org","country":"Ethiopia","ip_address":"244.69.119.16"},{"id":"6","first_name":"Ruth","last_name":"Lane","email":"rlane5#va.gov","country":"Brazil","ip_address":"18.173.102.54"},{"id":"7","first_name":"Andrew","last_name":"Turner","email":"aturner6#devhub.com","country":"United States","ip_address":"13.119.240.234"},{"id":"8","first_name":"Wanda","last_name":"Medina","email":"wmedina7#pagesperso-orange.fr","country":"Netherlands","ip_address":"151.139.21.237"},{"id":"9","first_name":"Robert","last_name":"Elliott","email":"relliott8#joomla.org","country":"United States","ip_address":"34.200.249.109"},{"id":"10","first_name":"Kevin","last_name":"Harrison","email":"kharrison9#nih.gov","country":"Brazil","ip_address":"106.84.164.86"}]}
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;
}
}
EDIT
JSONObject c = user.getJSONObject(Integer.parseInt(xyz));
I Modified to this, im getting a response other than default 1 when base value was getJSONObject(0), but now im entering 1 and im getting 2, entering 4 getting 5..
Does anyone know how to solve this one?
If you are trying to parse the whole json array then use this.In you post execute
List<String> allid = new ArrayList<String>();
JSONArray obj= jsonResponse.getJSONArray("tag");
for (int i=0; i<obj.length(); i++) {
JSONObject actor = cast.getJSONObject(i);
String id= actor.getString("id");
allNames.add(id);
}
Then you can use a for loop to get the id in the list accordingly.
Otherwise you can do this parsing Using the Gson Library(you can download Gson library here
Just create a class in your package
public class DetailArray {
public boolean status;
public List<Detail_User> details;
public class Detail_User {
public String id;
public String first_name;
public String last_name;
public String email;
public String country;
}
}
In your post execute
Where response is the json response
DetailArray detail1 = (new Gson()).fromJson(response.toString(),
DetailArray.class);
Now Suppose , if you want to set the names in a list view then
//return a arraylist
private ArrayList<String> getName(DetailArray detail) {
ArrayList name = new ArrayList<String>();
for (int i=0;i< detail.details.size();i++) {
name.add(splitStr[i]);
}
return names;
}
Setting the array adapter and setting it to a list
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
this,
android.R.layout.simple_list_item_1,
getName(detail);
listview.setAdapter(arrayAdapter);
For a particular position try like this
int positionToShow = Integer.parseInt(edt.getText().toString()) - 1;
user = json.getJSONArray(TAG_TAG);
for(int i = 0; i < user.length(); i++) {
if(positionToShow == i) {
JSONObject c = user.getJSONObject(i);
// Storing JSON item in a Variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_LAST_NAME);
String email = c.getString(TAG_EMAIL);
uid.setText(id);
name1.setText(name);
email1.setText(email);
}
}
i've parse your json ...acc to number entered ..and it shows exact result....refer this....
final EditText no=(EditText)findViewById(R.id.editText1);
final Button click=(Button)findViewById(R.id.button1);
click.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
try
{
Toast.makeText(MainActivity.this, no.getText().toString(), 0).show();
HttpClient client=new DefaultHttpClient();
HttpGet request=new HttpGet("http://192.168.0.30/test.js");
HttpResponse response=client.execute(request);
HttpEntity entity=response.getEntity();
String json=EntityUtils.toString(entity);
JSONObject j1=new JSONObject(json);
JSONArray ja1=j1.getJSONArray("tag");
JSONObject j2=ja1.getJSONObject(Integer.parseInt(no.getText().toString())-1);
Toast.makeText(MainActivity.this, j2.getString("first_name").toString() , 0).show();
entity.consumeContent();
}
catch(Exception e)
{
e.getStackTrace();
Toast.makeText(MainActivity.this, e.toString() , 0).show();
}
}
});
I am getting the response from server in json format. How can i show a response in listview.
Code :
public class MainActivity extends Activity {
private static String url = "http://api.androidhive.info/contacts/";
#SuppressLint("NewApi")
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
InputStream is = null;
StrictMode.setThreadPolicy(policy);
new JSONParse().execute();
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
}
}
}
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();
System.out.println("sb:"+sb);
} 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;
}
}
This is no need for
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
InputStream is = null;
StrictMode.setThreadPolicy(policy);
Also #SuppressLint("NewApi") indicates you suppressed a lint warning. Some features are available on new api's only. Do check your min sdk versions.
to display it the response in a list you need to listview
activity_main.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="id/list" // id is list
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
Then in onCreate
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv= (ListView) findViewById(R.id.list);
new JSONParse().execute();
}
Change this
private class JSONParse extends AsyncTask<String, String, JSONObject>
to
private class JSONParse extends AsyncTask<String, String, ArrayList<HashMap<String, String>>>
Make sure you have these
public class MainActivity extends Activity {
private static String url = "http://api.androidhive.info/contacts/";
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";
In doInbackground you need to parse the json
#Override
protected ArrayList<HashMap<String, String>> doInBackground(String... args) {
ArrayList<HashMap<String, String>> contactList= new ArrayList<HashMap<String,String>>();
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
contacts = json.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);
}
} catch (JSONException e) {
e.printStackTrace();
}
return contactList;
}
Then
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, result,
R.layout.list_item, new String[] { TAG_NAME, TAG_EMAIL,
TAG_PHONE_MOBILE }, new int[] { R.id.name,
R.id.email, R.id.mobile });
lv.setAdapter(adapter);
}
list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="10dp"
android:paddingLeft="10dp"
android:paddingRight="10dp" >
<!-- Name Label -->
<TextView
android:id="#+id/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" />
<!-- Email label -->
<TextView
android:id="#+id/email"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:textColor="#acacac" />
<!-- Mobile number label -->
<TextView
android:id="#+id/mobile"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="left"
android:text="Mobile: "
android:textColor="#5d5d5d"
android:textStyle="bold" />
</LinearLayout>
I have an activity in which I have to populate a listview. The activity posts to an url and receives a JSON in response. I have parsed the JSON to display in a listview, but the listview is not getting populated.
The complete code for the activity:
public class RegisterFirstActivity extends ListActivity {
private static final String TAG_CODE = "Code";
private static final String TAG_ID = "Id";
private static final String TAG_LAT = "Lat";
private static final String TAG_LON = "Lon";
private static final String TAG_NAME = "Name";
static String response_str=null;
static String response_code=null;
String ac_code;
String ac_id;
String ac_lat;
String ac_lon;
String ac_name;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register_first);
sendPostRequest();
}
//sending async post request---------------------------------------------------------------------------------------
private void sendPostRequest() {
class SendPostReqAsyncTask extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
String result = "";
HttpClient hc = new DefaultHttpClient();
String message;
//HttpPost p = new HttpPost("http://192.168.1.60/tr/MobileService/GetAC");
HttpPost p = new HttpPost("http://bumba27.byethost16.com/xxxxxxx/");
JSONObject object = new JSONObject();
try {
//object.put("Id",deviceid);
//object.put("StringValue",value);
// object.put("last_name", lastname);
// object.put("first_name", firstname);
// object.put("email", email);
} catch (Exception ex) {
}
try {
message = object.toString();
p.setEntity(new StringEntity(message, "UTF8"));
p.setHeader("Content-type", "application/json");
HttpResponse resp = hc.execute(p);
response_code=""+ resp.getStatusLine().getStatusCode();
Log.d("Response Code: ", "" + response_code);
InputStream inputStream = resp.getEntity().getContent();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
while((bufferedStrChunk = bufferedReader.readLine()) != null){
stringBuilder.append(bufferedStrChunk);
}
response_str= stringBuilder.toString();
parse_json_str(response_str);
if (resp != null) {
if (resp.getStatusLine().getStatusCode() == 204)
result = "true";
makeAToast("Response: "+resp.toString());
}
Log.d("Status line", "" + resp.getStatusLine().getStatusCode());
} catch (Exception e) {
e.printStackTrace();
Log.i("Error in response: ",e.getMessage());
}
return result;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
//writeToFile(result, "record.txt");
Log.i("RESPONSE",result);
}
}
SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
sendPostReqAsyncTask.execute();
}
//-----------------------------------------------------------------------------------------------
public void parse_json_str(String json_str)
{
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
JSONArray lJSONArray;
String jString = json_str;
try
{
lJSONArray = new JSONArray( jString );
JSONObject lJSONObject;
for ( int i = 0; i < lJSONArray.length(); i++ )
{
lJSONObject = lJSONArray.getJSONObject( i );
// PARSE FIELD HERE
ac_code = lJSONObject.getString( TAG_CODE );
Log.i("Code: ",ac_code);
ac_id=lJSONObject.getString( TAG_ID );
Log.i("Id: ",ac_id);
ac_lat=lJSONObject.getString( TAG_LAT );
Log.i("Lat: ",ac_lat);
ac_lon=lJSONObject.getString( TAG_LON );
Log.i("Lon: ",ac_lon);
ac_name=lJSONObject.getString( TAG_NAME );
Log.i("Name: ",ac_name);
// ETC
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_CODE, ac_code);
map.put(TAG_ID, ac_id);
map.put(TAG_LAT, ac_lat);
map.put(TAG_LON, ac_lon);
map.put(TAG_NAME, ac_name);
Log.d("map","haeflloter putting");
Log.d("map",map+"");
// adding HashList to ArrayList
contactList.add(map);
//Log.d("tag name", contactList+"");
}
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(this, contactList,R.layout.list_item,new String[] { TAG_NAME }, new int[] {R.id.name});
Log.d("tag name", contactList+"");
setListAdapter(adapter);
}
catch( Exception e )
{
Log.d("catch", e+"");
}
}
public void makeAToast(String str) {
//yet to implement
Toast toast = Toast.makeText(this,str, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
}
The layout file activity_register_first :
<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>
The list_item.xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<!-- Name Label -->
<TextView
android:id="#+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#43bd00"
android:textSize="16sp"
android:textStyle="bold"
android:paddingTop="6dip"
android:paddingBottom="2dip" />
<!-- Description label -->
</LinearLayout>
</LinearLayout>
The error which I am getting is:
02-15 19:26:46.154: D/catch(1429): android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
I have followed this tutorial for listview.
Where am I going wrong? How to solve the issue?
In an AsyncTask, only onPreExecute(), onProgressUpdate() and onPostExecute() are executed in the UI Thread.
doInBackground() is executed in a background Thread.
You should store your data from doInBackground(), then update your UI in onPostExecute().
Edit:
Make your contactList a member of your AsyncTask, and add this code (not tested):
protected void onPostExecute(String result) {
super.onPostExecute(result);
if(mContactList != null) {
ListAdapter adapter = new SimpleAdapter(this, contactList,R.layout.list_item,new String[] { TAG_NAME }, new int[] {R.id.name});
Log.d("tag name", contactList+"");
setListAdapter(adapter);
}
Log.i("RESPONSE",result);
}
UI changes have to be done in the UI thread. that is what onPostExecute() is for, that runs in the UI thread.