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.
Related
Im pulling images from the server with asyncTask and drawing them on imageViews. The problem is that Images sometimes get "shuffled" and it takes them couple of seconds to deploy proper image. And it can get laggy too. Is there any easier way to do that? Am I doing something wrong?
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(RecipeActivity.this);
dialog.setMessage("Loading, please wait");
dialog.setTitle("Connecting to 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 array = jsono.getJSONArray("recepies");
JSONArray array = new JSONArray(data);
for (int i = 0; i < array.length(); i++) {
JSONObject object = array.getJSONObject(i);
Recepies rec = new Recepies();
rec.setName(object.getString("name"));
rec.setPciture(object.getString("picture"));
receptis.add(rec);
}
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();
}
}
and this is the MainActivity:
ArrayList<Recepies> recepies;
String nameRecepie, ingredients, priprema, picture;
Toolbar toolbar;
RecipesAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recipes_activity);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
setTitle("Dog recepies");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
receptis = new ArrayList<Recepti>();
new JSONAsyncTask().execute("url");
ListView listview = (ListView) findViewById(R.id.list);
adapter = new RecipesAdapter(getApplicationContext(), R.layout.row, receptis);
listview.setAdapter(adapter); //onclick listener ->
and my Adapter class
public class RecipesAdapter extends ArrayAdapter<Recepti> {
ArrayList<Recepti> receptisList;
LayoutInflater vi;
int Resource;
ViewHolder holder;
public RecipesAdapter(Context context, int resource, ArrayList<Recepti> objects) {
super(context, resource, objects);
vi = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Resource = resource;
receptisList = 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.tvName = (TextView) v.findViewById(R.id.tvName);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
new DownloadImageTask(holder.imageview).execute(receptisList.get(position).getSlika());
holder.tvName.setText(receptisList.get(position).getNaziv());
return v;
}
static class ViewHolder {
public TextView tvName;
public ImageView imageview;
}
protected 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);
}
}
}
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 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'm using the staggered grid view to display my information that I get via a webservice. when i displayed it in format portrait there is no problem.( I have 2 grids). In landscape mode I have 3 grids. The problem is here, the textview change the size and became bigger and when I scroll to the end, I will have 2 or 1 grids (not 3) and sometime no grid.
This is the adapter code:
public class StaggeredAdapterVraiCategorie extends ArrayAdapter<VraiCategorie> {
ArrayList<VraiCategorie> categorieList;
LayoutInflater vi;
int Resource;
private ImageLoader mLoader;
Context context;
public StaggeredAdapterVraiCategorie(Context context, int resource,ArrayList<VraiCategorie> objects) {
super(context, resource, objects);
categorieList = objects;
Resource = resource;
this.context=context;
vi = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mLoader = new ImageLoader(context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
LayoutInflater layoutInflator = LayoutInflater.from(getContext());
convertView = layoutInflator.inflate(R.layout.vrai_list_item_sample,null);
holder = new ViewHolder();
holder.imageView = (DynamicHeightImageView)convertView.findViewById(R.id.image);
holder.namecateg = (TextView)convertView.findViewById(R.id.namecateg);
holder.reftype = (TextView)convertView.findViewById(R.id.reftype);
holder.myid = (TextView)convertView.findViewById(R.id.myid);
convertView.setTag(holder);
}
// else {
holder =(ViewHolder)convertView.getTag();
// }
holder.namecateg.setText(categorieList.get(position).getNamecateg());
holder.reftype.setText(categorieList.get(position).getReftype());
holder.myid.setText(categorieList.get(position).getMyid());
String imgget=categorieList.get(position).getImagecateg();
if(!imgget.equals("null")){
String mylink="http://myserver/images/";
String imgexe=mylink+imgget;
new DownloadImageTask(holder.imageView).execute(imgexe);
}
else if (imgget.equals("null")){
holder.imageView.setHeightRatio(1.0); //ta3mel prob fel staggered
holder.imageView.setImageResource(R.drawable.nophoto);
}
if(!categorieList.get(position).getImagecateg().equals("null")) {
String mylink = "http://myserver/images/";
// holder = (ViewHolder) convertView.getTag();
mLoader.DisplayImage(mylink + categorieList.get(position).getImagecateg(), holder.imageView);
}
return convertView;
}
static class ViewHolder {
public DynamicHeightImageView imageView;
public TextView namecateg;
public TextView reftype;
public TextView myid;
}
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);
}
}
}
This is the main class:
public class VraiCateg extends BaseFragment implements StaggeredGridView.OnItemClickListener {
ArrayList<VraiCategorie> categorieList;
StaggeredAdapterVraiCategorie adapter;
StaggeredGridView staggeredGridView;
String passtitle="";
SharedPreferences sharedpreferences;
public static final String MyPREFERENCES="My profile info";
public static final String keyidhotel="idH";
private String myidhotel="";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.vrai_main, container, false);
Main activity = (Main) getActivity();
String myDataFromActivity = activity.getData();
myidhotel = myDataFromActivity;
final String url = "http://myserver/api/type_etablissement/categories/id/"+myidhotel;
//url = url + myidhotel;
Toast.makeText(getActivity().getApplicationContext(), "Adresse categ URL "+url, Toast.LENGTH_LONG).show();
staggeredGridView = (StaggeredGridView) view.findViewById(R.id.grid_view);
// myidhotel = getArguments().getString("idH");
int margin = getResources().getDimensionPixelSize(R.dimen.margin);
staggeredGridView.setPadding(margin, 0, margin, 0);
if(!(MySuperScaler.scaled))
MySuperScaler.scaleViewAndChildren(view, MySuperScaler.scale);
categorieList = new ArrayList<VraiCategorie>();
new CategorieAsyncTask().execute(url);
staggeredGridView.setOnItemClickListener(this);
return view;
}
class CategorieAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(getActivity());
dialog.setMessage("Loading, please wait");
dialog.setTitle("Connecting server");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
dialog.cancel();
if (result == false){
//show a msg to user that data not parsed
Toast.makeText(getActivity().getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}
else {
//call etab adapter and create now adapter
StaggeredAdapterVraiCategorie adapter = new StaggeredAdapterVraiCategorie(getActivity().getApplicationContext(),R.layout.vrai_list_item_sample,categorieList);
staggeredGridView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
#Override
protected Boolean doInBackground(String... params) {
try {
HttpClient client = new DefaultHttpClient();
//HttpPost post = new HttpPost(uri); //uri in oncreate method
HttpGet get = new HttpGet(params[0]);
HttpResponse response = client.execute(get);
int status = response.getStatusLine().getStatusCode();
if(status ==200){
//get the response and pars it
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jObj = new JSONObject(data);
JSONArray jArray = jObj.getJSONArray("categories");
for(int i=0;i<jArray.length();i++ ){
VraiCategorie categ = new VraiCategorie();
JSONObject jRealObject = jArray.getJSONObject(i);
categ.setImagecateg(jRealObject.getString("image_categorie"));
categ.setNamecateg(jRealObject.getString("description_type"));
//ref_type=jRealObject.getString("ref_type");
categ.setReftype(jRealObject.getString("ref_type"));
categ.setMyid(jRealObject.getString("my_id"));
categorieList.add(categ);
}
return true; //verifie the parse
}
}catch (ClientProtocolException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
catch (JSONException e) {
e.printStackTrace();
}
//http call
return false;
}
}
#Override
public void onItemClick(StaggeredGridView parent, View view, int position, long id) {
final String ref_type= categorieList.get(position).getReftype();
Fragment newFragment = new VraiRela();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
Bundle args=new Bundle();
args.putString("ref_type",ref_type);
args.putString("idH",myidhotel);
// Toast.makeText(getActivity().getApplicationContext(), "ref_type"+ref_type+"idH"+myidhotel, Toast.LENGTH_LONG).show();
newFragment.setArguments(args);
transaction.replace(R.id.frame_container, newFragment);
transaction.addToBackStack(null);
transaction.commit();
/* myidhotel="";
sharedpreferences = getActivity().getApplicationContext().getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
myidhotel="";
editor.putString(keyidhotel, myidhotel);
editor.commit();*/
}
}
Hi I need to store items in custom adapter but I got issue while creating custom adapter. Please help me to resolve.
private class Cast extends AsyncTask<Object, Void, ArrayList<String>> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialog=new ProgressDialog(Detailed_View.this);
dialog.setMessage("Loading, please wait");
dialog.setTitle("Connecting server");
dialog.show();
dialog.setCancelable(false);
}
private final String KeY = "";
private static final String DEBUG_TAG = "TM";
#Override
protected ArrayList<String> doInBackground(Object... params) {
try {
return getCast();
} catch (IOException e) {
return null;
}
}
#Override
protected void onPostExecute(ArrayList<String> results_Cast) {
updateListOfCast(results_Cast);
dialog.cancel();
};
public ArrayList<String> getCast() throws IOException {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("https://themovie/3/movie/" + id
+ "/credit");
stringBuilder.append("?key=" + key);
URL url = new URL(stringBuilder.toString());
// Log.d("urlstring",stringBuilder.toString() );
InputStream stream = null;
try {
// Establish a connection
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.addRequestProperty("Accept", "application/json"); // Required
// to
// get
// TMDB
// to
// play
// nicely.
conn.setDoInput(true);
conn.connect();
int responseCode = conn.getResponseCode();
Log.d(DEBUG_TAG, "The response code is: " + responseCode + " "
+ conn.getResponseMessage());
stream = conn.getInputStream();
return parseCast(stringify(stream));
} finally {
if (stream != null) {
stream.close();
}
}
}
private ArrayList<String> parseCast(String result) {
String streamAsString = result;
ArrayList<String> results_Cast = new ArrayList<String>();
try {
JSONObject jsonObject = new JSONObject(streamAsString);
JSONArray array = (JSONArray) jsonObject.get("cast");
Log.d("array view", array.toString());
for (int i = 0; i < array.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject jsonMovieObject = array.getJSONObject(i);
results_Cast.add(jsonMovieObject.getString("name"));
ids=jsonMovieObject.getString("id");
results_Cast.add(jsonMovieObject.getString("character"));
}
} catch (JSONException e) {
Log.d("e", e.toString());
Log.d(DEBUG_TAG, "Error parsing JSON. String was: "
+ streamAsString);
}
// Log.d("resulted", results_Cast.toString());
return results_Cast;
}
public String stringify(InputStream stream) throws IOException,
UnsupportedEncodingException {
Reader reader = null;
reader = new InputStreamReader(stream, "UTF-8");
BufferedReader bufferedReader = new BufferedReader(reader);
return bufferedReader.readLine();
}
}
// displays cast
public void updateListOfCast(ArrayList<String> result) {
ListView listView = (ListView) findViewById(R.id.cast_details);
//Log.d("updateViewWithResults", result.toString());
// Add results to listView.
listView.setAdapter(adapter);
Helper.getListViewSize(listView);
gridAdapter = new GridAdapter(this, R.layout.test_row, result); // here I have issue.
listView.setAdapter(gridAdapter);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long idss) {
// TODO Auto-generated method stub
String name = (String) parent.getItemAtPosition(position);
Toast.makeText(Detailed_View.this, name+"Id"+ids, Toast.LENGTH_SHORT)
.show();
}
});
public class GridAdapter extends BaseAdapter {
public GridAdapter(Activity a, int resource, ArrayList<String> result) { // here it displays error as The blank final field itemLists may not have been initialized
layoutInflater = (LayoutInflater) a
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Resource = resource;
results=result;
activity=a;
loader=new ImageLoader(a.getApplicationContext());
}
}
How to get items of name, id and character to display in custom adapter?
You have to overide all methods..
Example
public class CustomBaseAdapter extends BaseAdapter {
Context context;
List<RowItem> rowItems;
public CustomBaseAdapter(Context context, List<RowItem> items) {
this.context = context;
this.rowItems = items;
}
/*private view holder class*/
private class ViewHolder {
ImageView imageView;
TextView txtTitle;
TextView txtDesc;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
LayoutInflater mInflater = (LayoutInflater)
context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item, null);
holder = new ViewHolder();
holder.txtDesc = (TextView) convertView.findViewById(R.id.desc);
holder.txtTitle = (TextView) convertView.findViewById(R.id.title);
holder.imageView = (ImageView) convertView.findViewById(R.id.icon);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
RowItem rowItem = (RowItem) getItem(position);
holder.txtDesc.setText(rowItem.getDesc());
holder.txtTitle.setText(rowItem.getTitle());
holder.imageView.setImageResource(rowItem.getImageId());
return convertView;
}
#Override
public int getCount() {
return rowItems.size();
}
#Override
public Object getItem(int position) {
return rowItems.get(position);
}
#Override
public long getItemId(int position) {
return rowItems.indexOf(getItem(position));
}
}