I am trying to retrieve values from a json api and displaying then in a listView. The listView contains 3 elements and I am also implementing onItemClickListner() and when an Item is clicked it will display a detailed view related to that item. I am using an ArrayList to store all the json values. Now I want to retrieve a value from that ArrayList so that the OnClickListner() will get that value and from that value the detailed view will be displayed..
I am using AsyncTask to retrieve all the json values
#Override
protected String doInBackground(String... DATA) {
if(rqst_type.equals("top5"))
{
String url = DATA[1];
JsonParser jParser = new JsonParser();
JSONObject json = jParser.getJSONfromUrl(url);
try
{
JSONArray top5 = json.getJSONArray(TAG_TOP5);
public static ArrayList<HashMap<String, String>> top5List = new ArrayList<HashMap<String, String>>();
top5List.clear();
for(int i=0; i<top5.length(); i++)
{
Log.v(TAG_LOG, "Value of i: "+String.valueOf(i));
JSONObject t = top5.getJSONObject(i);
course_id = t.getString(TAG_CRSID);
created_date = t.getString(TAG_CRTDATE);
golfcourse_name = t.getString(TAG_GLFCRSNAME);
facilities = t.getString(TAG_FCLTY);
holes = t.getString(TAG_HOLES);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_CRSID, course_id);
map.put(TAG_CRTDATE, created_date);
map.put(TAG_GLFCRSNAME, golfcourse_name);
map.put(TAG_FCLTY, facilities);
map.put(TAG_HOLES, holes);
top5List.add(map);
Log.v(LoadingScreen.TAG_LOG, "top5List: "+String.valueOf(top5List));
}
}
catch(JSONException e)
{
Log.v(TAG_LOG, String.valueOf(e));
}
}
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if(rqst_type.equals("top5"))
{
Intent in = new Intent(context, MyTop5.class);
in.putExtra(TAG_CRSID, course_id);
in.putExtra(TAG_CRTDATE, created_date);
in.putExtra(TAG_GLFCRSNAME, golfcourse_name);
in.putExtra(TAG_FCLTY, facilities);
in.putExtra(TAG_HOLES, holes);
Log.v(TAG_LOG, "Valuse to MyTop5: "+course_id+" "+created_date+" "+golfcourse_name+" "+
facilities+" "+holes);
context.startActivity(in);
}
This is the file to where I am displaying the list and the onItenClickListner()..
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.my_top5);
Intent in = getIntent();
golfcourse_name = in.getStringExtra(TAG_GLFCRSNAME);
course_id = in.getStringExtra(TAG_CRSID);
created_date = in.getStringExtra(TAG_CRTDATE);
facilities = in.getStringExtra(TAG_FCLTY);
holes = in.getStringExtra(TAG_HOLES);
Log.v(LoadingScreen.TAG_LOG, "course id: "+String.valueOf(course_id));
ListAdapter adapter = new SimpleAdapter(this, LoadingScreen.top5List, R.layout.top5_list,
new String[] { TAG_GLFCRSNAME, TAG_CRSID, TAG_CRTDATE, TAG_FCLTY, TAG_HOLES },
new int[] { R.id.top_golfname, R.id.top_courseid, R.id.top_createdate, R.id.top_fclty, R.id.top_holes });
setListAdapter(adapter);
Log.v(LoadingScreen.TAG_LOG, "course id: "+String.valueOf(course_id));
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
String url = "http://mygogolfteetime.com/iphone/viewdeal/127";
new LoadingScreen(MyTop5.this).execute("view_detail", url);
}
});
}
In the given URL I want to change the 127 to the value which is stored in the top5List.
String url = "http://mygogolfteetime.com/iphone/viewdeal/127";
The value I am trying to find in the top5List is the value of "course_id"
Thanks in advance..
top5List.get(your position).get(your Key);
With this code you can find the value on which you want to change.
Related
Hello everyone and happy new year
I have JSON class where I retrieve some data that are retrieve from a database. The format of this JSON file is
{"people":[{"id":"15","first_name":"Theo","last_name":"Tziomakas","bio":"Hello from
Theo!!!","created":"2015-01-11 21:48:51"},
{"id":"16","first_name":"Jim","last_name":"Chytas","bio":"Hello from Chytas","created":"2015-01-11
21:53:42"}]}.
The idea is to retrieve the "first_name" and "second_name" in a listview. The "bio" should appear in another activity,but I don't know how to do that:(.
Here is my code.
public class MainActivity extends ActionBarActivity {
ListView list;
TextView fname;
TextView lname;
ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
//URL to get JSON Array
private static String url = "http://xxxxxxx/tutorials/index.php";
//JSON Node Names
private static final String TAG_OS = "people";
private static final String TAG_FIRST_NAME = "first_name";
private static final String TAG_SECOND_NAME = "last_name";
//private static final String TAG_BIO = "bio";
JSONArray android = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
oslist = new ArrayList<HashMap<String, String>>();
new JSONParse().execute();
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
fname = (TextView)findViewById(R.id.first_name);
lname = (TextView)findViewById(R.id.last_name);
//abio = (TextView)findViewById(R.id.bio);
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_OS);
for(int i = 0; i < android.length(); i++){
JSONObject c = android.getJSONObject(i);
// Storing JSON item in a Variable
String first_name = c.getString(TAG_FIRST_NAME);
String last_name = c.getString(TAG_SECOND_NAME);
//String bio = c.getString(TAG_BIO);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_FIRST_NAME, first_name);
map.put(TAG_SECOND_NAME, last_name);
//map.put(TAG_BIO, bio);
oslist.add(map);
list=(ListView)findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, oslist,
R.layout.list_v,
new String[] { TAG_FIRST_NAME,TAG_SECOND_NAME }, new int[] {
R.id.first_name,R.id.last_name});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String bio = ((TextView) view.findViewById(R.id.bio))
.getText().toString();
switch (position) {
case 0:
Intent i = new Intent(MainActivity.this, SingleActivity.class);
i.putExtra("bio", bio);
startActivity(i);
break;
}
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
And finally I have the SecondActivity class,but nothing is shown when I click the first row of list.
public class SingleActivity extends ActionBarActivity {
TextView text;
JSONArray android = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single);
text = (TextView)findViewById(R.id.text);
String bio = getIntent().getStringExtra("bio");
try {
JSONObject profileJSON = new JSONObject(bio);
android = profileJSON.getJSONArray(bio);
text.setText(""+android);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Thank you.
EDIT:The problem I had is fixed. Now I want to do something else. Let us suppose that we update the data in an existing row by changing "first_name,"last_name" and finally bio. It is done very easily in phpmyadmin tool. The problem is that the updated row is not shown in the listview. I have to reinstall the app in order to see it. Any ideas in that?
try this ,
replace onPostExecute with this
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
list=(ListView)findViewById(R.id.list);
// Getting JSON Array from URL
android = json.getJSONArray(TAG_OS);
for(int i = 0; i < android.length(); i++){
JSONObject c = android.getJSONObject(i);
// Storing JSON item in a Variable
String first_name = c.getString(TAG_FIRST_NAME);
String last_name = c.getString(TAG_SECOND_NAME);
//String bio = c.getString(TAG_BIO);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_FIRST_NAME, first_name);
map.put(TAG_SECOND_NAME, last_name);
map.put(TAG_BIO, bio);
oslist.add(map);
}
ListAdapter adapter = new SimpleAdapter(MainActivity.this, oslist,
R.layout.list_v,
new String[] { TAG_FIRST_NAME,TAG_SECOND_NAME }, new int[] {
R.id.first_name,R.id.last_name});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String bio =oslist.get(position).get(TAG_BIO);
// switch (position) {
// case 0:
Intent i = new Intent(MainActivity.this, SingleActivity.class);
i.putExtra("bio", bio);
startActivity(i);
break;
//}
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
and SingleActivity
text = (TextView)findViewById(R.id.text);
String bio = getIntent().getStringExtra("bio");
text.setText(bio );
Pay attention to what you put in the intent.
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String bio = ((TextView) view.findViewById(R.id.bio))
.getText().toString();
switch (position) {
case 0:
Intent i = new Intent(MainActivity.this, SingleActivity.class);
i.putExtra("bio", bio);
startActivity(i);
break;
}
}
notice that you take the text from a text view and add it to and intent.
When you retreive it use it as if its a json object.
If you want the bio string, you could put that in a variable, and then send it to an intent with just the string.
for example
ListAdapter adapter = new SimpleAdapter(MainActivity.this, oslist,
R.layout.list_v,
new String[] { TAG_FIRST_NAME,TAG_SECOND_NAME }, new int[] {
R.id.first_name,R.id.last_name});
list.setAdapter(adapter);
String bio = c.getString("bio");
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
switch (position) {
case 0:
Intent i = new Intent(MainActivity.this, SingleActivity.class);
i.putExtra("bio", bio);
startActivity(i);
break;
}
}
});
when retrieving it its easier to just do it with
public class SingleActivity extends ActionBarActivity {
TextView text;
JSONArray android = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single);
text = (TextView)findViewById(R.id.text);
String bio = getIntent().getStringExtra("bio");
text.settext(bio)
}
}
now there is prob some bugs in these example, since i have not java or android sdk installed on my computer
I am developing android app in that i want to display json data in listview with load more button, but when i click load more button old data is replaceing by new one i want both and old and new data to be displayed.Lihstview should show all data whats wrong in the code below
public class Newjava extends Activity {
JSONObject jsonobject;
JSONArray jsonarray;
CustomAdapter1 adapter2;
CustomAdapter1 adapter;
ProgressDialog mProgressDialog;
ArrayList<FeedAddress> arraylist;
String url = "http://xxxx.vdv.com/api/fvn/page1";
String arraymovie = "all";
public String string;
ListView listView;
int i = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
listView = (ListView) findViewById(R.id.list);
arraylist = new ArrayList<FeedAddress>();
// Retrive JSON Objects from the given website URL in
// JSONfunctions.class
jsonobject = JSONfunctions.getJSONfromURL(url);
try {
// Locate the array name
JSONObject jsonObject1 = jsonobject.getJSONObject("appname");
jsonarray = jsonObject1.getJSONArray("kfnh");
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject post = (JSONObject) jsonarray.getJSONObject(i);
FeedAddress map = new FeedAddress();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.setMovieName(post.getString("movieName"));
map.setName(post.getString("movieActors"));
map.setMovieId(post.getString("movieId"));
String imageUrl = "http://www.xxhbc.com/upload/dv/thumbnail/"
+ post.getString("moviePhoto")
+ post.getString("moviePhotoExt");
map.setImageUrl(imageUrl);
System.out.println("ldhslhdljh " + imageUrl);
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
Button btnLoadMore = new Button(this);
btnLoadMore.setText("Load More");
// Adding Load More button to lisview at bottom
listView.addFooterView(btnLoadMore);
// Getting adapter
adapter = new CustomAdapter1(this, arraylist);
listView.setAdapter(adapter);
/**
* Listening to Load More button click event
* */
btnLoadMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Starting a new async task
i += 1;
new DownloadJSON().execute();
}
});
}
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(Newjava.this);
// Set progressdialog title
mProgressDialog.setTitle("APP Name");
mProgressDialog.setIcon(R.drawable.ic_launcher);
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create the array
arraylist = new ArrayList<FeedAddress>();
// Retrive JSON Objects from the given website URL in
// JSONfunctions.class
String URL = "http://zvzvs.vczx.com/api/v/page"
+ i;
System.out.println("new url " + URL);
jsonobject = JSONfunctions.getJSONfromURL(URL);
try {
// Locate the array name
JSONObject jsonObject1 = jsonobject
.getJSONObject("fvvzx");
jsonarray = jsonObject1.getJSONArray("allmovies");
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject post = (JSONObject) jsonarray.getJSONObject(i);
FeedAddress map = new FeedAddress();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.setMovieName(post.getString("movieName"));
// map.setName(post.getString("movieActors"));
map.setMovieId(post.getString("movieId"));
String imageUrl = "http://www.vsv.com/upload/vc/thumbnail/"
+ post.getString("moviePhoto")
+ post.getString("moviePhotoExt");
map.setImageUrl(imageUrl);
System.out.println("ldhslhdljh " + imageUrl);
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
int currentPosition = listView.getFirstVisiblePosition();
// Appending new data to menuItems ArrayList
adapter = new CustomAdapter1(Newjava.this, arraylist);
listView.setAdapter(adapter);
// Setting new scroll position
listView.setSelectionFromTop(currentPosition + 1, 0);
updateList(string);
}
}
public void updateList(final String string) {
// TODO Auto-generated method stub
listView.setVisibility(View.VISIBLE);
// mProgressDialog.dismiss();
listView.setAdapter(new CustomAdapter1(Newjava.this, arraylist));
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
// Toast.makeText(getApplicationContext(),"position[]" ,
// Toast.LENGTH_SHORT).show();
Object o = listView.getItemAtPosition(position);
FeedAddress newsData = (FeedAddress) o;
System.out.println("hgsh " + string);
System.out.println("next " + newsData.getMovieId());
Intent intent = new Intent(Newjava.this,
SingleMenuItemActivity.class);
intent.putExtra("feed", newsData.getMovieId());
intent.putExtra("actor", newsData.getName());
startActivity(intent);
}
});
}
}
It replaces data because you recreate adapter every time. You should create adapter once and then add to it more data, not recreate it.
im writing an app for a site which uses JSON API. Im trying to parse the JSON but i get:
Error parsing data org.json.JSONException: Value error of type
java.lang.String cannot be converted to JSONArray
This is due its a string, i've tried other methods but i can only get information from the first string, because each string has its own randomly generated "filename/id", you can take a look at the json output:
{"error":"","S8tf":{"infoToken":"wCfhXe","deleteToken":"gzHTfGcF","size":122484,"sha1":"8c4e2bbc0794d2bd4f901a36627e555c068a94e6","filename":"Screen_Shot_2013-07-02_at_3.52.23_PM.png"},"S29N":{"infoToken":"joRm6p","deleteToken":"IL5STLhq","size":129332,"sha1":"b4a03897121d0320b82059c36f7a10a8ef4c113d","filename":"Stockholmsyndromet.docx"}}
Im trying to get it to show both of the "objects" from the json string. How can i make a lopp for it to find all the items or simply make it list all the "objects" contained in the "error" identifier?
My Main Activity:
public class FilesActivity extends SherlockListActivity implements
OnClickListener {
private ProgressDialog mDialog;
ActionBar ABS;
TextView session;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dblist);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Files");
TextView txt = (TextView)findViewById(R.id.nodata);
/**String s = "{menu:{\"1\":\"sql\", \"2\":\"android\", \"3\":\"mvc\"}}";
JSONObject jObject = null;
try {
jObject = new JSONObject(s);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONObject menu = null;
try {
menu = jObject.getJSONObject("menu");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Map<String,String> map = new HashMap<String,String>();
Iterator<String> iter = menu.keys();
while(iter.hasNext()){
String key = (String)iter.next();
String value = null;
try {
value = menu.getString(key);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
map.put(key,value);
txt.setText(value);
} **/
JsonAsync asyncTask = new JsonAsync();
// Using an anonymous interface to listen for objects when task
// completes.
asyncTask.setJsonListener(new JsonListener() {
#Override
public void onObjectReturn(JSONObject object) {
handleJsonObject(object);
}
});
// Show progress loader while accessing network, and start async task.
mDialog = ProgressDialog.show(this, getSupportActionBar().getTitle(),
getString(R.string.loading), true);
asyncTask.execute("http://api.bayfiles.net/v1/account/files?session=" + PreferenceManager.getDefaultSharedPreferences(getBaseContext()).getString("sessionID", "defaultStringIfNothingFound"));
//session = (TextView)findViewById(R.id.textView1);
//session.setText(PreferenceManager.getDefaultSharedPreferences(getBaseContext()).getString("sessionID", "defaultStringIfNothingFound"));
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
private void handleJsonObject(JSONObject object) {
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
String files = null;
try {
int id;
String name;
JSONArray array = new JSONArray("error");
for (int i = 0; i < array.length(); i++) {
JSONObject row = array.getJSONObject(i);
id = row.getInt("id");
name = row.getString("name");
}
//JSONArray shows = object.getJSONArray("");
/*String shows = object.getString("S*");
for (int i = 0; i < shows.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
//JSONObject e = shows.getJSONObject(i);
files = shows;
//map.put("video_location", "" + e.getString("video_location"));
//TextView txt = (TextView)findViewById(R.id.nodata);
//txt.setText(files);
mylist.add(map); *
}*/
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
ListAdapter adapter = new SimpleAdapter(this, mylist, R.layout.dbitems,
new String[] { files, "video_location" }, new int[] { R.id.item_title,
R.id.item_subtitle });
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
#SuppressWarnings("unchecked")
HashMap<String, String> o = (HashMap<String, String>) lv
.getItemAtPosition(position);
//Intent myIntent = new Intent(ListShowsController.this,
// TestVideoController.class);
//myIntent.putExtra("video_title", o.get("video_title"));
//myIntent.putExtra("video_channel", o.get("video_channel"));
//myIntent.putExtra("video_location", o.get("video_location"));
//startActivity(myIntent);
}
});
if (mDialog != null && mDialog.isShowing()) {
mDialog.dismiss();
}
}
}
Any help is much appreciated!
You're trying to get the error field as a JSONArray. Its a string. You can't process a string as an array, it throws that exception. In fact, I don't see any arrays in there at all.
I would look into using a JSon library like Gson (https://code.google.com/p/google-gson/). You are able to deserialize collections, which is much easier than doing it yourself.
When I am clicking on my list items only the 1st item's id is going to the next activity. As I am getting patient name and id in this list fragment and passing the patient id to another activity, only the 1st list item's id is passing through even if I tap on another item... Hope you got my point...
Here is my ListFragment,
public class AllPatient extends ListFragment {
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList = new ArrayList<HashMap<String,String>>();
// url to get all products list
private static String url_all_patients = "http://192.168.44.208/get_all_patients.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_PATIENT_ID = "patient_id";
private static final String TAG_PATIENT_NAME = "patient_name";
JSONArray products = null;
Context ctx;
String pid;
EditText inputSearch = null;
ListAdapter adapter;
ListView lv;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.patient_list, container, false);
//ListView lv;
lv = (ListView)view.findViewById(android.R.id.list);
//ListView v = getListView();
new LoadAllPatients().execute();
return view;
}
#Override
public void onListItemClick(ListView lv, View v, int position, long id) {
// TODO Auto-generated method stub
onAttach(getActivity());
//lv.setAdapter(adapter);
String id1 = ((TextView) getView().findViewById(R.id.pid)).getText().toString();
System.out.println("all patient"+id1);
Bundle bundle = new Bundle();
bundle.putString("TAG_PATIENT_ID",id1 );
System.out.println("bundle"+id1);
Intent i = new Intent(getActivity(),DocPresc.class);
i.putExtras(bundle);
startActivity(i);
//passData(date);
Toast.makeText(
getActivity(),
getListView().getItemAtPosition(position).toString(),
Toast.LENGTH_LONG).show();
}
class LoadAllPatients extends AsyncTask<String, String, String> {
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_patients, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Patients: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
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_PATIENT_ID).toUpperCase();
String name = c.getString(TAG_PATIENT_NAME).toUpperCase();
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PATIENT_ID, id);
map.put(TAG_PATIENT_NAME, name);
// 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
getActivity().runOnUiThread(new Runnable() {
public void run() {
ListAdapter adapter = new SimpleAdapter(
getActivity(), productsList,
R.layout.list_item1, new String[] { TAG_PATIENT_ID,
TAG_PATIENT_NAME},
new int[] { R.id.pid, R.id.name });
// updating listview
//setListAdapter(adapter);
setListAdapter(adapter);
}
});
}
}
}
Try this.
Change this line:
String id1 = ((TextView) getView().findViewById(R.id.pid)).getText().toString();
to
String id1 = ((TextView) v.findViewById(R.id.pid)).getText().toString();
I am unable to display images but the text is displayed.
I have modified the code from http://mobile.dzone.com/news/android-tutorial-how-parse to the code below.
I would prefer using SimpleAdapter only .Is it possible? As I have implemented the same code as below everywhere.
Or little modifications to the below code would be fine.
How do I display images?
public class MainActivity extends ListActivity {
ArrayList<HashMap<String, String>> mylist;
SimpleAdapter adapter;
ProgressDialog pd ;
ListView lv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listplaceholder);
mylist = new ArrayList<HashMap<String, String>>();
new loadingDisplayClass().execute();
}
public class loadingDisplayClass extends AsyncTask<String, Integer, String> {
protected void onPreExecute() {
pd = new ProgressDialog(MainActivity.this);
pd.setTitle("Loading......");
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.show();
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
String url = "https://itunes.apple.com/us/rss/topalbums/limit=50/json";
JSONObject json = JSONfunctions.getJSONfromURL(url);
try {
JSONObject arr2 = json.getJSONObject("feed");
JSONArray arr = arr2.getJSONArray("entry");
for (int i = 0; i < arr.length(); i++) {
JSONObject e1 = arr.getJSONObject(i);
JSONArray jsar = e1.getJSONArray("im:image");
JSONObject jsname = e1.getJSONObject("im:name");
String name = jsname.getString("label");
JSONObject jso = e1.getJSONObject("im:artist");
String lbl = jso.getString("label");
JSONObject e12 = jsar.getJSONObject(0);
String icon = e12.getString("label");
HashMap<String, String> hashmapnew = new HashMap<String, String>();
hashmapnew.put("icons", icon);
hashmapnew.put("name", name);
hashmapnew.put("artist", lbl);
mylist.add(hashmapnew);
publishProgress(((int) ((i + 1 / (float) arr.length()) * 100)));
}
} catch (JSONException e) {
Toast.makeText(getBaseContext(),
"Network communication error!", 5).show();
}
adapter = new SimpleAdapter(getBaseContext(), mylist,
R.layout.list, new String[] {
"icons","name","artist" },
new int[] { R.id.image,R.id.name,R.id.artist });
return null;
}
protected void onProgressUpdate(Integer... integers) {
pd.incrementProgressBy(integers[0]);
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
setListAdapter(adapter);
pd.dismiss();
lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
#SuppressWarnings("unchecked")
HashMap<String, String> o = (HashMap<String, String>) lv
.getItemAtPosition(position);
}
});
}
}
}
I am unable to display images but the text is displayed
Images won't display because you are just passing url to the SimpleAdapter.In order to show images you need to first download the images in the url returned above service .
You need to create a custom Adapter and display images by downloading them
Downloading each image and displaying image in imageView takes lot time and as the listview recycle views your images will always download when the list is scrolled. So what you need to do is to use -Universal-Image-Loader or Lazy List to provide automatic downloading and caching images.