Can not populate listview from async task - android

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.

Related

Android Development - Parsing JSON

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 .

Android clickable listview

I have a android code which that get some data in json format from php file,
I successfully created a listview using those json now I want to create a second activity to show product details when I click on those items.
Here is the code :
public class MainActivity extends Activity {
private String jsonResult;
private String url = "xxxx/get_all_products.php";
private ListView listView;
private static final String TAG_PRODUCTS = "products";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
private static final String TAG_PRICE = "price";
private static final String TAG_FOUND = "found";
private static final String TAG_DESCRIPTION = "description";
ArrayList<HashMap<String, String>> productList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView1);
productList = new ArrayList<HashMap<String, String>>();
accessWebService();
}
// Async Task to access the web
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);
}
}
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>> productList = new ArrayList<Map<String, String>>();
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("products");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String name = jsonChildNode.optString("name");
String price = jsonChildNode.optString("price");
String found = jsonChildNode.optString("found");
// String outPut = name + "-" + number;
// String outPut = name + "-" + price + "-" + found;
// productList.add(createProduct("products", outPut));
HashMap<String, String> product = new HashMap<String, String>();
product.put(TAG_NAME, name);
product.put(TAG_FOUND, found);
product.put(TAG_PRICE, price);
productList.add(product);
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
SimpleAdapter simpleAdapter = new SimpleAdapter(this, productList,
R.layout.list_item, new String[] { TAG_NAME, TAG_PRICE,
TAG_FOUND }, new int[] { R.id.name,
R.id.price, R.id.found });
listView.setAdapter(simpleAdapter);
}
}
and also there are there are two xml layout files.
I read many examples for doing this about setOnItemClickListener whit no success.....
for example tried this with no success :
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String selval = ((TextView) view).getText().toString();
Intent intnt = new Intent(getApplicationContext(), SingleListItem.class);
intnt.putExtra("selval ", selval);
}
Here are the errors :
FATAL EXCEPTION: main
java.lang.ClassCastException: android.widget.LinearLayout cannot be cast to android.widget.TextView
at sig.example.com.sig00.MainActivity$1.onItemClick(MainActivity.java:59)
Here are xml files :
<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" >
<!-- Name Label -->
<!-- android:id="#+id/listView1" -->
<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>
and the list_item.xml is
<?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"
android:gravity="center"/>
<!-- Email label -->
<TextView
android:id="#+id/price"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:textColor="#acacac" />
<!-- Mobile number label -->
<TextView
android:id="#+id/found"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="left"
android:textColor="#5d5d5d"
android:textStyle="bold" />
</LinearLayout>
Replace your code from your setOnItemClickListener() to this one :
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String selval = listview.getItemAtPosition(position).getText().toString();
// Also I've found a solution on SO that a guy solved this problem doing soemthing like this :
// TextView txt = (TextView) parent.getChildAt(position - listview.firstVisiblePosition()).findViewById(R.id.sometextview);
// String keyword = txt.getText().toString();
Intent intnt = new Intent(getApplicationContext(), SingleListItem.class);
intnt.putExtra("selval ", selval);
EDIT
Your error is that in your intent you are putting as extra "selval ", with an BLANK SPACE so if in your next activity you are doing this :
Class SingleListItem extends Activity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.productdetails);
TextView txtProduct = (TextView) findViewById(R.id.product_label);
Intent i = getIntent(); // getting attached intent data
String selval = i.getStringExtra("selval"); // displaying selected product name txtProduct.setText(selval);
}
It never will return your selval string cause you are asking for "sevlal" not from "selval ".
Just remove your unnecessary space and it will work :)
The View in onItemClick is not a TextView, it's the entire row. You should do the following
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//String selval = ((TextView) view.findViewById(R.id.yourId)).getText().toString();
HashMap<String, String> item = parent.getItemAtPosition(position);
String selval = item.get(TAG_PRICE);
Intent intnt = new Intent(getApplicationContext(), SingleListItem.class);
intnt.putExtra("selval ", selval);
}

How can I put photos(from drawable folder) in a listview with the url from a json file

I'm making an app with data from several people with the names, mobile phone number and photograph.
The JSON file is on the assets folder, the photos are on the drawable folder.
Here is the code
public class MainActivity extends ListActivity {
private ProgressDialog pDialog;
public String loadJSONFromAsset(){
String json = null;
try{
InputStream is = getAssets().open("lista.json");
int size = is.available();
byte[] buffer= new byte[size];
is.read(buffer);
is.close();
json= new String (buffer, "UTF-8");
} catch (IOException ex){
ex.printStackTrace();
return null;
}
return json;
}
private static final String TAG_CONTACTS = "pessoas";
private static final String TAG_NAME = "nome";
private static final String TAG_PHONE_MOBILE = "tlm";
private static final String TAG_PHOTO = "photo";
JSONArray contacts = null;
ArrayList<HashMap<String, String>> contactList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String name = ((TextView) view.findViewById(R.id.nome))
.getText().toString();
String description = ((TextView) view.findViewById(R.id.tlm))
.getText().toString();
// My problem is here...how can I do this????
String description = ((TextView) view.findViewById(R.id.photo))
.getText().toString();
Intent in = new Intent(getApplicationContext(),
SingleContactActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_PHONE_MOBILE, description);
in.putExtra(TAG_PHOTO, descripphoto);
startActivity(in);
}
});
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Aguarde um momento...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
String jsonStr = loadJSONFromAsset();
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
contacts = jsonObj.getJSONArray(TAG_CONTACTS);
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String nome = c.getString(TAG_NAME);
String tlm = c.getString(TAG_PHONE_MOBILE);
String photo = c.getString(TAG_PHOTO);
HashMap<String, String> contact = new HashMap<String, String>();
contact.put(TAG_NAME, nome);
contact.put(TAG_PHONE_MOBILE, tlm);
contact.put(TAG_PHOTO, photo);
contactList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Nao se obteve qualquer dado da BD");
}
Collections.sort(contactList, new Comparator<HashMap<String, String>>() {
#Override
public int compare(HashMap<String, String> lhs, HashMap<String, String> rhs) {
return (lhs.get(TAG_NAME).toLowerCase().compareTo(rhs.get(TAG_NAME).toLowerCase()));
}
});
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, contactList,
R.layout.list_item, new String[] { TAG_NAME,
TAG_PHONE_MOBILE,TAG_PHOTO }, new int[] { R.id.nome,
R.id.photo, R.id.tlm, });
setListAdapter(adapter);
}
}
My list_item.xml
<TextView
android:id="#+id/nome"
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" />
<TextView
android:id="#+id/tlm"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="left"
android:textColor="#5d5d5d"
android:textStyle="bold" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/photo"/>
My json file
{
"pessoas":
[
{
"nome":"A",
"tlm":"911911911",
"photo":"drawable/a.png"
},
{
"nome":"B",
"tlm":"911911911",
"photo":"drawable/b.png"
},
{
"nome":"C",
"tlm":"911911911",
"photo":"drawable/c.png"
}
]
}
can some one help me with this ???
Well you can set the resource directly from resource like this
int imageResource = getResources().getIdentifier(#drawable/myresource.png, null, getPackageName());
imageview= (ImageView)findViewById(R.id.imageView);
Drawable res = getResources().getDrawable(imageResource);
imageView.setImageDrawable(res);
Bind it to the list on your adapter !
You use your Adapter for this like this.
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
View rowView = mInflater.inflate(R.layout.dashboard_adapter, null);
TextView textView_area = (TextView) rowView
.findViewById(R.id.textView_area);
ImageView big = (ImageView) rowView.findViewById(R.id.big);
try {
Picasso.with(context).load(dashboard_ArrayList.get(position).getImagepath()).into(big);
textView_area.setText(dashboard_ArrayList.get(position).getCat_name());
}catch (Exception e) {
e.printStackTrace();
}
big.png is the image in the drawable folder.
For this either you need to write conditions, which mapping your photo path to drawable resources
OR
Copy those drawable in Internal or External SD card

how to show the JSON response in a listview

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>

populate listview with json parser

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.

Categories

Resources