I would like to know if it is possible to load an image inside a ListView directly from the web, when the URL is stocked inside a json.
Edit : Solved, It is possible to use an AsyncTask
public class ParseImage extends AsyncTask<Object, String, Drawable> {
private ProgressBar pd;
private ImageView imv;
private int position;
public ParseImage(int position, ImageView imv, ProgressBar pd2) {
this.position = position;
this.imv = imv;
this.pd = pd2;
}
#Override
public Drawable doInBackground(Object... params) {
Drawable d = null;
try {
d = Drawable.createFromStream(
(InputStream) new URL(list.get(position).get("Cover"))
.getContent(), "src");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return d;
}
public void onPostExecute(Drawable result) {
if (result != null && imv != null) {
pd.setVisibility(View.INVISIBLE);
imv.setImageDrawable(result);
}
}
}
}
You need to create your own custom Listview to show more than a String.Here is a piece of code you can refer:
MovieAdaptor.java:
public class MovieAdaptor extends ArrayAdapter<Movie> {
Context context;
int layoutResourceId;
ArrayList<Movie> movieArrayList = new ArrayList<Movie>();
public MovieAdaptor(Context context, int layoutResourceId, ArrayList<Movie> movies) {
super(context, layoutResourceId, movies);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.movieArrayList = movies;
}
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
ContactHolder holder = null;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ContactHolder();
holder.thumbnail = (ImageView) row.findViewById(R.id.imageThumbnail);
holder.title = (TextView) row.findViewById(R.id.MovieTitle);
holder.synopsis = (TextView) row.findViewById(R.id.synopsis);
row.setTag(holder);
} else {
holder = (ContactHolder) row.getTag();
}
holder.title.setText(movieArrayList.get(position).title);
holder.synopsis.setText(movieArrayList.get(position).synopsis);
newAsyncDownloadImage(holder.thumbnail).execute(movieArrayList.get(position).posters.get("thumbnail"));
return row;
}
static class ContactHolder {
ImageView thumbnail;
TextView title;
TextView synopsis;
}
}
Activity.class:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
moviesListView = (ListView) findViewById(R.id.list_movies);
moviesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position > HEADER) {
Intent intent = new Intent(getBaseContext(), MovieActivity.class);
intent.putExtra(MOVIE_OBJECT, movieArrayList.get(position - 1));
startActivity(intent);
}
}
});
View header = (View) getLayoutInflater().inflate(R.layout.listview_row_header, null);
moviesListView.addHeaderView(header);
movieAdaptor = new MovieAdaptor(this, R.layout.listview_row_item, movieArrayList);
moviesListView.setAdapter(movieAdaptor);
AsyncDownloadImage.java:
public class AsyncDownloadImage extends AsyncTask<Object, Object, Object> {
ImageView iv;
private HttpURLConnection connection;
private InputStream is;
private Bitmap bitmap;
public AsyncDownloadImage(ImageView mImageView) {
iv = mImageView;
}
#Override
protected Object doInBackground(Object... params) {
URL url;
try {
url = new URL((String) params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
is = connection.getInputStream();
bitmap = BitmapFactory.decodeStream(is);
is.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (is != null) {
is.close();
}
if (connection != null) {
connection.disconnect();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return bitmap;
}
#Override
protected void onPostExecute(Object result) {
super.onPostExecute(result);
if (null != result) {
iv.setImageBitmap((Bitmap) result);
} else {
iv.setBackgroundResource(R.drawable.ic_launcher);
}
}
}
}
Can you send the return of
JSONfunction.getJSONfromURL("http://colmarmagazine.ctai.fr/issues.php");
Please ?
I think it's a bad parting ! Because you have :
Unable to decode stream: java.io.FileNotFoundException: /http:/colmarmagazine.ctai.fr/content/numerodemo/numerodemo.png: open failed: ENOENT (No such file or directory)
and a "/" too much in the url for your cover !
Related
I am building a news app and I want to cache a JSON response to use when there is no network. I tried a lot of ways but it did not work for me.
My async task and my adapter are another side problem when the list loads new items it goes to the top of the screen and after that it adds the items. How can I fix this?
private class jsontask extends AsyncTask<String, String, List<newsmodel>> {
#Override
protected List<newsmodel> doInBackground(String... params) {
BufferedReader reader = null;
HttpURLConnection connection = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finaljson = buffer.toString();
JSONObject parentobject = new JSONObject(finaljson);
JSONArray parentarray = parentobject.getJSONArray("articles");
for (int i = 0; i < parentarray.length(); i++) {
JSONObject finalobject = parentarray.getJSONObject(i);
newsmodel newsmodel = new newsmodel();
newsmodel.setAuthor(finalobject.getString("author"));
if (finalobject.isNull("author")) {
}
newsmodel.setDescription(finalobject.getString("description"));
newsmodel.setTitle(finalobject.getString("title"));
newsmodel.setImage(finalobject.getString("urlToImage"));
newsmodel.setUrl(finalobject.getString("url"));
newsmodel.setPublishedAt(finalobject.getString("publishedAt"));
moviemodelList.add(newsmodel);
}
return moviemodelList;
} catch (MalformedURLException e) {
e.printStackTrace();
return moviemodelList;
} catch (IOException e) {
e.printStackTrace();
return moviemodelList;
} catch (JSONException e) {
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(List<newsmodel> result) {
super.onPostExecute(result);
newsadapter adapter = new newsadapter(getApplicationContext(), R.layout.row, result);
lvnews.setAdapter(adapter);
}
}
public class newsadapter extends ArrayAdapter {
private List<newsmodel> moviemodelList;
private int resource;
private LayoutInflater inflater;
public newsadapter(Context context, int resource, List<newsmodel> objects) {
super(context, resource, objects);
moviemodelList = objects;
this.resource = resource;
inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
viewholder holder = null;
if (convertView == null) {
holder = new viewholder();
convertView = inflater.inflate(resource, null);
holder.newsimage = (ImageView) convertView.findViewById(R.id.imageView2);
holder.title = (TextView) convertView.findViewById(R.id.textView2);
holder.description = (TextView) convertView.findViewById(R.id.textView3);
holder.author = (TextView) convertView.findViewById(R.id.textView4);
holder.publishdate = (TextView) convertView.findViewById(R.id.textView5);
holder.dotsmenu = (ImageButton) convertView.findViewById(R.id.dots);
convertView.setTag(holder);
} else {
holder = (viewholder) convertView.getTag();
}
final ProgressBar progressBar;
progressBar = (ProgressBar) convertView.findViewById(R.id.progressBar);
ImageLoader.getInstance().displayImage(moviemodelList.get(position).getImage(), holder.newsimage, new ImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
progressBar.setVisibility(view.VISIBLE);
}
#Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
progressBar.setVisibility(view.GONE);
}
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
progressBar.setVisibility(view.GONE);
}
#Override
public void onLoadingCancelled(String imageUri, View view) {
progressBar.setVisibility(view.GONE);
}
});
holder.title.setText(moviemodelList.get(position).getTitle());
holder.description.setText(moviemodelList.get(position).getDescription());
holder.author.setText(moviemodelList.get(position).getAuthor());
holder.publishdate.setText(moviemodelList.get(position).getPublishedAt());
final viewholder finalHolder = holder;
holder.dotsmenu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PopupMenu popup = new PopupMenu(page.this, finalHolder.dotsmenu);
//Inflating the Popup using xml file
popup.getMenuInflater().inflate(R.menu.dots_menu, popup.getMenu());
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.share:
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, moviemodelList.get(position).getUrl());
sendIntent.setType("text/plain");
startActivity(sendIntent);
return true;
}
return false;
}
});
popup.show();
}
});
lvnews.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(page.this, webview.class);
intent.putExtra("Link", moviemodelList.get(position).getUrl());
startActivity(intent);
}
});
return convertView;
}
Make a class for testing whether net connection is available or not .
ConnectionDetector.java
public class ConnectionDetector {
public Context context;
public ConnectionDetector(Context context)
{
this.context=context;
}
public boolean isConnecting() {
ConnectivityManager check=(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (check!=null){
NetworkInfo[] infos=check.getAllNetworkInfo();
for (int i=0;i<infos.length;i++)
{
if (infos[i].getState()== NetworkInfo.State.CONNECTED)
return true;
}}
return false;
}
}
Create an object ob of above class .
ConnectionDetector ob=new ConnectionDetector(getApplicationContext());
Declare these variables as global variables :
File httpCacheDir;
long httpCacheSize = 5 * 1024 * 1024;// In place of 5 you can use size in mb
HttpResponseCache cache;
Make a function cacher():
public void cacher()
{
httpCacheDir = getExternalCacheDir();
// Cache Size of 5MB
try {
// Install the custom Cache Implementation
HttpResponseCache.install(httpCacheDir, httpCacheSize);
} catch (Exception e) {
e.printStackTrace();
}
}
Just below the setContentView in onCreate ,add the following code :
cacher();
cache = HttpResponseCache.getInstalled();
if(cache != null) {
// If cache is present, flush it to the filesystem.
// Will be used when activity starts again.
cache.flush();
}
And here comes the final thing , below the url.openConnection line put the following snippet:
if (ob.isConnecting()){
connection.addRequestProperty("Cache-Control", "max-age=0");}
else{
connection.addRequestProperty("Cache-Control", "max-stale=" + 60*60*36);//In place of 36 , you can put hours for which cache is available
connection.setUseCaches(true);
}
I want to parse data and images via url of json.
I have used following code to do same. But i am not getting why the images disappear when i scroll down.
Can Anyone please tell me how can i stop to disappear images when i scroll down ?
Images are loading randomly how can i fix it?
Please find below link of source code :-
http://www.wingnity.com/blog/android-json-parsing-and-image-loading-tutorial/
public class MainActivity extends Activity {
ArrayList<Actors> actorsList;
ActorAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
actorsList = new ArrayList<Actors>();
new JSONAsyncTask().execute("http://milagro.in/wip/apps/n/THDC2.json");
ListView listview = (ListView)findViewById(R.id.list);
adapter = new ActorAdapter(getApplicationContext(), R.layout.row, actorsList);
listview.setAdapter(adapter);
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long id) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), actorsList.get(position).gettata_project_name(), Toast.LENGTH_LONG).show();
}
});
}
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(MainActivity.this);
dialog.setMessage("Loading, please wait");
dialog.setTitle("Connecting server");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
try {
//------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("data");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
Actors actor = new Actors();
actor.settata_project_name(object.getString("tata_project_name"));
actor.setproject_Typology(object.getString("project_Typology"));
actor.setproject_logo_url(object.getString("project_logo_url"));
actor.setprice(object.getString("price"));
actorsList.add(actor);
}
return true;
}
//------------------>>
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
adapter.notifyDataSetChanged();
if(result == false)
Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}
}
}
public class ActorAdapter extends ArrayAdapter<Actors> {
ArrayList<Actors> actorList;
LayoutInflater vi;
int Resource;
ViewHolder holder;
public ActorAdapter(Context context, int resource, ArrayList<Actors> objects) {
super(context, resource, objects);
vi = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Resource = resource;
actorList = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// convert view = design
View v = convertView;
if (v == null) {
holder = new ViewHolder();
v = vi.inflate(Resource, null);
holder.imageview = (ImageView) v.findViewById(R.id.ivImage);
holder.Projectname = (TextView) v.findViewById(R.id.Projectname);
holder.typology = (TextView) v.findViewById(R.id.typology);
holder.price = (TextView) v.findViewById(R.id.price);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
new DownloadImageTask(holder.imageview).execute(actorList.get(position).getproject_logo_url());
holder.imageview.setImageResource(R.drawable.ic_launcher);
//new DownloadImageTask(holder.imageview).execute(actorList.get(position).getproject_logo_url());
holder.Projectname.setText(actorList.get(position).gettata_project_name());
holder.typology.setText(actorList.get(position).getproject_Typology());
holder.price.setText("Price: " + actorList.get(position).getprice());
return v;
}
static class ViewHolder {
public ImageView imageview;
public TextView Projectname;
public TextView typology;
public TextView price;
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
public class Actors {
private String tata_project_name;
private String project_Typology;
private String project_logo_url;
private String price;
public Actors() {
// TODO Auto-generated constructor stub
}
public Actors(String tata_project_name, String project_Typology,String project_logo_url, String price ) {
super();
this.tata_project_name = tata_project_name;
this.project_Typology = project_Typology;
this.project_logo_url = project_logo_url;
this.price = price;
}
public String gettata_project_name() {
return tata_project_name;
}
public void settata_project_name(String tata_project_name) {
this.tata_project_name = tata_project_name;
}
public String getproject_Typology() {
return project_Typology;
}
public void setproject_Typology(String project_Typology) {
this.project_Typology = project_Typology;
}
public String getproject_logo_url() {
return project_logo_url;
}
public void setproject_logo_url(String project_logo_url) {
this.project_logo_url = project_logo_url;
}
public String getprice() {
return price;
}
public void setprice(String price) {
this.price = price;
}
}
try this library Picaso this is the best image loading library from url.
After using Volley library The problem is solved.
I follow this video try to get data from mongodb
get the JsonArray from mongodb , and use debug mode check the class JsonTest.java : ArrayList<JsonSongs> songlist; have 21 data in it , and all correct , and the listview has 21 row show up , but somehow the data did't show on the textview ,
I think the Class JsonTest.java : ˋArrayList songlist;did pass the data to class JsonSongAdapter.java ˋArrayList<JsonSongs> songlist; right?
please help , stuck here for hours
JsonTest.java
public class JsonTest extends Activity {
ListView list;
ArrayList<JsonSongs> songlist;
private TextView test;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.jsonmain);
list = (ListView)findViewById(R.id.JsonlistView);
songlist = new ArrayList<JsonSongs>();
new JsonTalk().execute("http://192.168.1.102:3000/songs");
}
class JsonTalk extends AsyncTask< String , String ,String>{
#Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
// JSONObject parentJsonObject = new JSONObject(finalJson);
JSONArray jsonArray = new JSONArray(finalJson);
JsonSongs jsonSongs = new JsonSongs();
for (int i = 0 ; i < jsonArray.length();i++){
JSONObject finaObject = jsonArray.getJSONObject(i);
jsonSongs.set_id(finaObject.getString("_id"));
jsonSongs.setDecade(finaObject.getString("decade"));
jsonSongs.setArtist(finaObject.getString("artist"));
jsonSongs.setSong(finaObject.getString("song"));
jsonSongs.setWeeksAtOne(finaObject.getInt("weeksAtOne"));
songlist.add(jsonSongs);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}catch (JSONException e){
e.printStackTrace();
}
finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if(result == null){
JsonSonAdapter adapter = new JsonSonAdapter(getApplicationContext(),R.layout.jsonlayout,songlist);
list.setAdapter(adapter);
}else {
Toast.makeText(JsonTest.this,"NOP",Toast.LENGTH_LONG).show();
}
}
}
}
JsonSonAdapter
public class JsonSonAdapter extends ArrayAdapter<JsonSongs> {
ArrayList<JsonSongs> songList;
int Resource;
Context context;
LayoutInflater vi;
public JsonSonAdapter(Context context, int resource, ArrayList<JsonSongs> objects) {
super(context, resource, objects);
songList = objects;
Resource = resource;
this.context = context;
vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null){
convertView = vi.inflate(Resource,null);
holder = new ViewHolder();
holder.textJson_ID=(TextView)convertView.findViewById(R.id.textJson_ID);
holder.textJSONname=(TextView)convertView.findViewById(R.id.textJSONname);
holder.textJsonSong=(TextView)convertView.findViewById(R.id.textJsonSong);
holder.textJsonYear=(TextView)convertView.findViewById(R.id.textJsonYear);
holder.textJsonWeeks=(TextView)convertView.findViewById(R.id.textJsonWeeks);
convertView.setTag(holder);
}else {
holder = (ViewHolder)convertView.getTag();
}
return convertView;
}
static class ViewHolder{
public TextView textJsonYear;
public TextView textJSONname;
public TextView textJsonSong;
public TextView textJsonWeeks;
public TextView textJson_ID;
}
}
JsonSongs
public class JsonSongs {
private String _id;
private String decade;
private String artist;
private String song;
private int weeksAtOne;
public String get_id() {
return _id;
}
public void set_id(String _id) {
this._id = _id;
}
public String getArtist() {
return artist;
}
public void setArtist(String artist) {
this.artist = artist;
}
public String getDecade() {
return decade;
}
public void setDecade(String decade) {
this.decade = decade;
}
public String getSong() {
return song;
}
public void setSong(String song) {
this.song = song;
}
public int getWeeksAtOne() {
return weeksAtOne;
}
public void setWeeksAtOne(int weeksAtOne) {
this.weeksAtOne = weeksAtOne;
}
}
but somehow the data did't show on the textview ,
You set it nowhere so no wonders. You need to call setText() on your EditTexts (in getView()) once you done with convertView to populate it with data.
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null){
convertView = vi.inflate(Resource,null);
holder = new ViewHolder();
holder.textJson_ID=(TextView)convertView.findViewById(R.id.textJson_ID);
...
convertView.setTag(holder);
}else {
holder = (ViewHolder)convertView.getTag();
}
// populate it with data
JsonSongs song = songs.get(position);
holder.textJson_ID.setText(song.getSomething());
...
return convertView;
}
PS: JsonSongs should rather be named JsonSong. And you got quite a mess in naming pattern.
I have a big problem.I'm trying to make a ListView with dynamically loaded images, using an AsyncTask to download the image and then set it into the ListView. My problem is that, while scrolling down, the images get randomly changed.I saw answers but I can't figure.
My Codes:
(Adapter)
public class ActorAdapter extends ArrayAdapter<Actors> {
ArrayList<Actors> actorList;
private static LayoutInflater vi;
int Resource;
ViewHolder holder;
public ActorAdapter(Context context, int resource, ArrayList<Actors> objects) {
super(context, resource, objects);
vi = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Resource = resource;
actorList = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
holder = new ViewHolder();
v = vi.inflate(Resource, null);
holder.imageHaberFoto = (ImageView) v.findViewById(R.id.ivImage);
holder.tvHaberBaslik = (TextView) v.findViewById(R.id.tvHaberBaslik);
holder.tvHaberTarihi = (TextView) v.findViewById(R.id.tvHaberTarihi);
holder.tvKisaTanim = (TextView) v.findViewById(R.id.tvKisaTanim);
holder.tvDetay = (TextView) v.findViewById(R.id.tvDetay);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
new DownloadImageTask(holder.imageHaberFoto).execute(actorList.get(position).getHaberFoto());
holder.tvHaberBaslik.setText(actorList.get(position).getHaberBaslik());
holder.tvKisaTanim.setText(actorList.get(position).getHaberKisatanim());
holder.tvHaberTarihi.setText(actorList.get(position).getHaberTarihi());
holder.tvDetay.setText(actorList.get(position).getDetay());
return v;
}
static class ViewHolder {
public ImageView imageHaberFoto;
public TextView tvHaberBaslik;
public TextView tvHaberTarihi;
public TextView tvKisaTanim;
public TextView tvDetay;
}
private static class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
}
Actor Class :
public class Actors {
private String HaberBaslik;
private String HaberTarihi;
private String HaberKisatanim;
private String HaberlerLink;
private String HaberFoto;
private String Detay;
public Actors() {
}
//Getters and setters
public String getHaberBaslik() {
return HaberBaslik;
}
public void setHaberBaslik(String HaberBaslik) {
this.HaberBaslik = HaberBaslik;
}
public String getHaberTarihi() {
return HaberTarihi;
}
public void setHaberTarihi(String HaberTarihi) {
this.HaberTarihi = HaberTarihi;
}
public String getHaberKisatanim() {
return HaberKisatanim;
}
public void setHaberKisatanim(String HaberKisatanim) {
this.HaberKisatanim = HaberKisatanim;
}
public String getHaberlerLink() {
return HaberlerLink;
}
public void setHaberlerLink(String HaberlerLink) {
this.HaberlerLink = HaberlerLink;
}
public String getDetay() {
return Detay;
}
public void setDetay(String Detay) {
this.Detay = Detay;
}
public String getHaberFoto() {
return HaberFoto;
}
public void setHaberFoto(String HaberFoto) {
this.HaberFoto = "http://www.developers.net/images/"+HaberFoto;
}
}
ListView:
ArrayList actorsList;
ActorAdapter adapter;
new JSONAsyncTask().execute("http://www.developers.net/WebServices/GetJson.aspx?q=Haber");
ListView listview = (ListView) findViewById(R.id.list);
adapter = new ActorAdapter(getApplicationContext(), R.layout.row, actorsList);
listview.setAdapter(adapter);
//JSONAsyncTask
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(haberler.this);
dialog.setMessage("Lütfen bekleyin.");
dialog.setTitle("İçerik Yüklemesi");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
try {
//------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("Haberler");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
Actors actor = new Actors();
actor.setHaberBaslik(object.getString("Baslik"));
actor.setHaberKisatanim(object.getString("Kisa"));
actor.setDetay(object.getString("Detay"));
actor.setHaberTarihi(object.getString("Tarih").replace("00:00:00",""));
actor.setHaberFoto(object.getString("Foto"));
actorsList.add(actor);
}
return true;
}
//------------------>>
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
adapter.notifyDataSetChanged();
if (result == false)
Toast.makeText(getApplicationContext(), "Veri alınamıyor.Lütfen daha sonra tekrar deneyin.", Toast.LENGTH_LONG).show();
}
}
i have a list view that is populated from a database with a customlistview...everything works fine except when i first start activity, the first item on the list view, loops through all images and then sets each image to corresponding item. I cannot figure out what i am doing wrong. pls help. I have gone through al the answers on stackoverflow but nothing works for me. Here is my custom list view:
***Edit:This code is working fine now. I fixed it.
public class FriendsListView extends ArrayAdapter<FriendsRowItem> {
Context context;
ArrayList<FriendsRowItem> infoList;
private LayoutInflater inflater = null;
int Resource;
ViewHolder holder;
public FriendsListView(Context context, int resourceId,
ArrayList<FriendsRowItem> items) {
super(context, resourceId, items);
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Resource = resourceId;
infoList = items;
}
/* private view holder class */
private class ViewHolder {
ImageView imageView;
TextView txtTitle;
}
public int getCount() {
return infoList.size();
}
public RowItem getItem(RowItem position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (vi == null) {
vi = inflater.inflate(R.layout.list_item_3, parent, false);
holder = new ViewHolder();
holder.txtTitle = (TextView) vi.findViewById(R.id.title3);
holder.imageView = (ImageView) vi.findViewById(R.id.icon3);
vi.setTag(holder);
} else {
holder = (ViewHolder) vi.getTag();
}
holder.txtTitle.setText(infoList.get(position).getTitle());
holder.imageView.setImageResource(R.drawable.ic_launcher);
new DownloadImageTask(holder.imageView).execute(infoList.get(position)
.getImage());
return vi;
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
int position;
public DownloadImageTask(ImageView bmImage, int position) {
this.bmImage = bmImage;
this.position = position;
bmImage.setTag(position);
bmImage.setImageBitmap(null);
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon = null;
try {
InputStream in = (InputStream) new java.net.URL(urldisplay)
.getContent();
mIcon = BitmapFactory.decodeStream(in);
} catch (Exception e) {
// Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon;
}
protected void onPostExecute(Bitmap result) {
if (result != null && (bmImage.getTag()).equals(this.position))
bmImage.setImageBitmap(result);
bmImage.setImageBitmap(result);
}
}
And how i populate my list view using JSON:
class RetrieveFriendsTask extends AsyncTask<Void, Void, Void> {
ArrayList<FriendsRowItem> FriendList = new ArrayList<FriendsRowItem>();
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
if (pDialog != null) {
pDialog.dismiss();
}
// Showing progress dialog
else {
pDialog = new ProgressDialog(Friends.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("eposta", email));
pairs.add(new BasicNameValuePair("sifre", pass));
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET, pairs);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
JSONObject jsonObj = null;
try {
jsonObj = new JSONObject(jsonStr);
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
JSONObject obj = jsonObj.getJSONObject("data");
friends = obj.getJSONArray(TAG_EVENTS);
for (int i = 0; i < friends.length(); i++) {
friend = new FriendsRowItem();
JSONObject c = friends.getJSONObject(i);
nick = c.optString("nick");
// friend.setTitle(c.optString("nick"));
img = c.optString("url_resim");
// friend.setImage(c.optString("url_resim"));
friend.setTitle(nick);
friend.setImage(img);
FriendList.add(friend);
}
}
catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
protected void onPostExecute(Void result) {
if (pDialog.isShowing())
pDialog.dismiss();
adapter = new FriendsListView(Friends.this, R.layout.list_item_3,
FriendList);
lvfriends.setAdapter(adapter);
OnItemClickListener myListViewClicked = new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
FriendsRowItem name = (FriendsRowItem) parent
.getItemAtPosition(position);
Intent i = new Intent(Friends.this, FriendsDisplay.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.putExtra("FriendName", name.toString());
startActivity(i);
}
};
lvfriends.setOnItemClickListener(myListViewClicked);
}
}
I would really appreciate the help.