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.
Related
I'm following tutorial from this link to create a listview containing data from database. It consists of a picture (by default - switched off light bulb) and two texts - name (room) and status (on/off) of the database record. At the end of AsyncTask which loads data from database I want to scan through the list and change the picture for every position where status equals "1" to switched on light bulb.
But the image doesn't change. As if the listview wasn't refreshing.
Every help would be appreciated.
public class LightingActivity extends ListActivity {
private ProgressDialog pDialog;
JSONParser jParser = new JSONParser();
JSONArray status = null;
ArrayList<HashMap<String, String>> statusList;
private static String address_getall = "http://192.168.2.112/db_lighting_getall.php";
private static String address_update = "http://192.168.2.112/db_lighting_change.php";
private static final String SID_SUCCESS = "success";
private static final String SID_ARRAY = "Lighting";
private static final String SID_ID = "light_id";
private static final String SID_NAME = "name";
private static final String SID_STATUS = "value";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.lighting_activity);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
statusList = new ArrayList<HashMap<String, String>>();
new LoadData().execute();
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// ...Listener...
}
});
}
class LoadData extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(LightingActivity.this);
pDialog.setMessage("Downloading...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
JSONObject json = jParser.makeHttpRequest(address_getall, "GET", params);
try {
int success = json.getInt(SID_SUCCESS);
if (success == 1) {
status = json.getJSONArray(SID_ARRAY);
for (int i = 0; i < status.length(); i++) {
JSONObject data = status.getJSONObject(i);
String light_id = data.getString(SID_ID);
String light_name = data.getString(SID_NAME);
String light_status = data.getString(SID_STATUS);
HashMap<String, String> map = new HashMap<String, String>();
map.put(SID_ID, light_id);
map.put(SID_NAME, light_name);
map.put(SID_STATUS, light_status);
statusList.add(map);
}
} else {
// Error
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
ListAdapter adapter = new SimpleAdapter(
LightingActivity.this, statusList,
R.layout.lighting_list, new String[]{SID_ID, SID_STATUS, SID_NAME},
new int[]{R.id.light_id, R.id.light_status, R.id.light_name});
setListAdapter(adapter);
// I tried doing it like this:
ListView lv = getListView();
for (int i = 0; i < lv.getCount(); i++) {
View v = lv.getAdapter().getView(i, null, null);
TextView light_status = (TextView) v.findViewById(R.id.light_status);
String status = light_status.getText().toString();
if (status.equals("1")) {
// Everything works till here - I checked with Toasts
ImageView img = (ImageView) v.findViewById(R.id.light_icon);
img.setImageResource(R.drawable.light_on);
lv.invalidateViews();
lv.refreshDrawableState();
}
}
}
});
}
}
Please be tolerant, I'm new to java :)
There are so many things wrong in your code that it's beyond saving! I suggest you google about how to load data to a ListView using AsyncTask. There are many examples. With a quick search this looks close to your needs.
http://android-er.blogspot.gr/2010/07/load-listview-in-background-asynctask.html
just a few pointers
1) onPostExecute, onProgressUpdate and onPreExceute of AsyncTask are executed
in the UI thread so the runOnUiThread(new Runnable() {}) is not necessary.
Only the doInBackground method is executed in another thread;
2) Put all the logic about what each rows shows like inside the getView method
of the adapter.
3) To update the views of a listView you change the data in the ArrayList and then
call notifyDataSetChanged() on the ListView 's adapter. This causes all of the views
to be re-drawn. And because all the logic is in the getView method your views
are showing what the data contains.
I have a listView that can get data from MySql using AsyncTask, but my problem is when i add some buttons and images in the ListView. I added some buttons but i can use it and the image won't display.
here's my code...
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
studentList = new ArrayList<HashMap<String, String>>();
new Loadstudent().execute();
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i = new Intent(getApplicationContext(), Maindetail.class);
String sidlist = ((TextView) view.findViewById(R.id.tid)).getText().toString();
String namelist = ((TextView) view.findViewById(R.id.sname)).getText().toString();
i.putExtra(TAG_ID, sidlist);
i.putExtra(TAG_NAME, namelist);
startActivity(i);
}
});
}
class Loadstudent extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Loading students. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
JSONObject json = jParser.makeHttpRequest(url_student, "GET", params);
Log.d("ALL student: ", json.toString());
try {
int success = json.getInt(TAG_SUCCESS);
if(success == 1) {
student = json.getJSONArray(TAG_STUDENT);
for (int i=0; i<student.length(); i++) {
JSONObject c = student.getJSONObject(i);
sid = c.getString(TAG_ID);
name = c.getString(TAG_NAME);
photo = c.getString(TAG_PHOTO);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_ID, sid);
map.put(TAG_NAME, name);
map.put(TAG_PHOTO, photo);
studentList.add(map);
}
}else {
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, studentList,
R.layout.list_main, new String[] {
TAG_PHOTO,TAG_ID, TAG_NAME},
new int [] { R.id.imageviewlist, R.id.tid, R.id.sname });
setListAdapter(adapter);
}
});
}
}
I student the lazyadapter from the net, but got a problem combining it to code.
there's any tutorial or link that can solved my problem would be a great help. Thanks in advance.
hey try below approach-
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent i = new Intent(getApplicationContext(), Maindetail.class);
HashMap<String, String> data = studentList.get(position);
String sidlist = data.get(TAG_ID);
String namelist = data.get(TAG_NAME);
i.putExtra(TAG_ID, sidlist);
i.putExtra(TAG_NAME, namelist);
startActivity(i);
}
});
You have to create your own adapter for the listview if you want to add extra components in every row layout.
It's not easy, but it's all here coded by me few time ago --> ListView Custom Adapter getView
I hope this helps you!
I'm fresher to android. I created android ListView using JSON WebService. I want old ListView data to be clear and reset again new data when getdata button is clicked again . Help me, thanks in advance.
setContentView(R.layout.activity_main);
CargoTracklist = 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, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
Status = (TextView)findViewById(R.id.textView2);
Id= (TextView)findViewById(R.id.textView1);
DateTime = (TextView)findViewById(R.id.textView3);
JobNo =(EditText)findViewById(R.id.editText1);
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();
ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
params.clear();
params.add(new BasicNameValuePair("JobNo",JobNo.getText().toString()));
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url,params);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
if (JobNo.getText().toString().equals(""))
{
Toast.makeText(MainActivity.this, "You did not enter a JobNo", Toast.LENGTH_SHORT).show();
}
else {
// Getting JSON Array from URL
Cargo = json.getJSONArray(TAG_CargoTrack);
for(int i = 0; i < Cargo.length(); i++){
JSONObject c = Cargo.getJSONObject(i);
// Storing JSON item in a Variable
String Status = c.getString(TAG_Status);
String Id = c.getString(TAG_Id);
String DateTime = c.getString(TAG_DateTime); HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_Status, Status);
map.put(TAG_Id, Id);
map.put(TAG_DateTime, DateTime);
CargoTracklist.add(map);
list=(ListView)findViewById(R.id.listView1);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, CargoTracklist,
R.layout.listview,
new String[] { TAG_Status,TAG_Id, TAG_DateTime }, new int[] {
R.id.textView2,R.id.textView1, R.id.textView3});
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 "+CargoTracklist.get(+position).get("Id"), Toast.LENGTH_SHORT).show();
}
});
Whenever you want to update your list clear the old data by
if(CargoTracklist != null){
CargoTracklist.clear();
// Add new Data to CargoTracklist
CargoTracklist.add("new data");
if(adapter != null){
adapter.notifyDataChaned();
}
}
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.
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.