I have gridview for a tab in tabLayout. I load the values from mysql database to fill the textviews of gridview. I see that the JSON parsing runs correctly and returns correct JSON result. But nothing shows up in grid view.
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.mysampleapp.R;
import java.util.ArrayList;
public class GridAdapterStores extends BaseAdapter {
private Context context;
private ArrayList<String> storename=new ArrayList<String>();
private ArrayList<Integer> imagelinks=new ArrayList<Integer>();
public GridAdapterStores(Context c,ArrayList<String> storename, ArrayList<Integer> imagelinks) {
context = c;
this.imagelinks = imagelinks;
this.storename = storename;
}
#Override
public int getCount() {
return storename.size();
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent){
View grid;
if (convertView == null) {
grid = new View(context);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
grid = inflater.inflate(R.layout.grid_stores,parent,false);
}
else {
grid = (View) convertView;
}
TextView textViewStoreName = (TextView) grid.findViewById(R.id.store_name);
ImageView imageViewStoreImage = (ImageView) grid.findViewById(R.id.store_image);
textViewStoreName.setText(storename.get(position));
Integer x=imagelinks.get(position);
imageViewStoreImage.setImageResource(x);
return grid;
}
}
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.app.Fragment;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.widget.AdapterView.OnItemClickListener;
import android.view.View.OnClickListener;
import com.mysampleapp.R;
import java.util.ArrayList;
public class StoresFragment extends Fragment {
private ProgressDialog loading;
private ArrayList<String> storenamefinal=new ArrayList<String>();
private ArrayList<Integer> imagelinksfinal=new ArrayList<Integer>();
#Nullable
#Override
public View onCreateView(LayoutInflater inflater , ViewGroup container,Bundle savedInstanceState){
return inflater.inflate(R.layout.stores_layout,null);
}
#Override
public void onViewCreated(final View view, final Bundle savedInstanceState){
super.onViewCreated(view, savedInstanceState);
GridView gridview=(GridView) getActivity().findViewById(R.id.grid_stores);
getData();
final GridAdapterStores gridadapter= new GridAdapterStores(getActivity(),storenamefinal,imagelinksfinal);
gridview.setAdapter(gridadapter);
gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
/* Intent i=new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(gridadapter.getItem(position).getImageUrlString()));
startActivity(i);}});*/
// Toast.makeText(getActivity(), "You Clicked at " + cat[+position], Toast.LENGTH_SHORT).show();
Intent i = new Intent(getActivity(), stores_show.class);
i.putExtra("storename", storenamefinal.get(position));
getActivity().startActivity(i);
}
});
}
//public class getData extends AsyncTask<String,>>{
//}
private void getData() {
loading = ProgressDialog.show(getActivity(), "Please wait...", "Fetching...", false, false);
String url = Config1.DATA_URL;
Toast.makeText(getActivity(), url, Toast.LENGTH_LONG).show();
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
loading.dismiss();
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(),error.getMessage().toString(),Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
}
private void showJSON(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(Config1.JSON_ARRAY);
Toast.makeText(getActivity(),result.toString(),Toast.LENGTH_LONG).show();
int i=result.length();
Log.i("Result Length",result.toString());
for(int j=0;j<i;j++){
storenamefinal.add(null);
imagelinksfinal.add(null);
}
String temp;
for(int j=0;j<i;j++)
{
JSONObject Data = result.getJSONObject(j);
Log.i("Data",Data.toString());
temp= (Data.getString(Config1.KEY_PRIO));
Log.i("temp", temp.toString());
storenamefinal.set(Integer.parseInt(temp) - 1, Data.getString(Config1.KEY_NAME));
Log.i("Result Length", storenamefinal.toString());
imagelinksfinal.add(R.drawable.sg1);
}
Log.i("Result Length", storenamefinal.toString());
Toast.makeText(getActivity(),storenamefinal.get(0),Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
I have tried searching on Google and stackoverflow , found nothing successful,
{"result":[{"storename":"Flipkart.com","imagelinks":"","mainpriority":"2"},{"storename":"Jabong.com","imagelinks":"","mainpriority":"4"},{"storename":"Myntra.com","imagelinks":"","mainpriority":"5"},{"storename":"Amazon.in","imagelinks":"","mainpriority":"1"},{"storename":"Snapdeal.com","imagelinks":"","mainpriority":"3"},{"storename":"Koovs.in","imagelinks":"","mainpriority":"6"},{"storename":"Limeroad.com","imagelinks":"","mainpriority":"7"},{"storename":"Shopperstop.com","imagelinks":"","mainpriority":"8"},{"storename":"Stalkbuylove.com","imagelinks":"","mainpriority":"9"},{"storename":"Yepme.com","imagelinks":"","mainpriority":"10"},{"storename":"Faballey.com","imagelinks":"","mainpriority":"11"},{"storename":"Fabindia.com ","imagelinks":"","mainpriority":"12"},{"storename":"PrettySecrets.com","imagelinks":"","mainpriority":"13"},{"storename":"AmericanSwan.com","imagelinks":"","mainpriority":"14"},{"storename":"Clovia.com","imagelinks":"","mainpriority":"15"},{"storename":"Bata.in","imagelinks":"","mainpriority":"16"},{"storename":"TrendyBharat.com","imagelinks":"","mainpriority":"17"},{"storename":"Royzez.com","imagelinks":"","mainpriority":"18"}]}
`
Storenamefinal will have entries of storenames from resulting JSON(above)
I tried your code and it crashes the application
after debugging i got that the problem is with the image resources
when i commented below two lines the app works fine.
//check these resources
Integer x=imagelinks.get(position);
imageViewStoreImage.setImageResource(x);
your showJSON() function that i tried
private void showJSON() {
try {
String response ="{\"result\":[{\"storename\":\"Flipkart.com\",\"imagelinks\":\"\",\"mainpriority\":\"2\"},{\"storename\":\"Jabong.com\",\"imagelinks\":\"\",\"mainpriority\":\"4\"},{\"storename\":\"Myntra.com\",\"imagelinks\":\"\",\"mainpriority\":\"5\"},{\"storename\":\"Amazon.in\",\"imagelinks\":\"\",\"mainpriority\":\"1\"},{\"storename\":\"Snapdeal.com\",\"imagelinks\":\"\",\"mainpriority\":\"3\"},{\"storename\":\"Koovs.in\",\"imagelinks\":\"\",\"mainpriority\":\"6\"},{\"storename\":\"Limeroad.com\",\"imagelinks\":\"\",\"mainpriority\":\"7\"},{\"storename\":\"Shopperstop.com\",\"imagelinks\":\"\",\"mainpriority\":\"8\"},{\"storename\":\"Stalkbuylove.com\",\"imagelinks\":\"\",\"mainpriority\":\"9\"},{\"storename\":\"Yepme.com\",\"imagelinks\":\"\",\"mainpriority\":\"10\"},{\"storename\":\"Faballey.com\",\"imagelinks\":\"\",\"mainpriority\":\"11\"},{\"storename\":\"Fabindia.com \",\"imagelinks\":\"\",\"mainpriority\":\"12\"},{\"storename\":\"PrettySecrets.com\",\"imagelinks\":\"\",\"mainpriority\":\"13\"},{\"storename\":\"AmericanSwan.com\",\"imagelinks\":\"\",\"mainpriority\":\"14\"},{\"storename\":\"Clovia.com\",\"imagelinks\":\"\",\"mainpriority\":\"15\"},{\"storename\":\"Bata.in\",\"imagelinks\":\"\",\"mainpriority\":\"16\"},{\"storename\":\"TrendyBharat.com\",\"imagelinks\":\"\",\"mainpriority\":\"17\"},{\"storename\":\"Royzez.com\",\"imagelinks\":\"\",\"mainpriority\":\"18\"}]} ";
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray("result");
Toast.makeText(MainActivity.this, result.toString(), Toast.LENGTH_LONG).show();
int i=result.length();
Log.i("Result Length", result.toString());
for(int j=0;j<i;j++){
storenamefinal.add(null);
imagelinksfinal.add(null);
}
String temp;
for(int j=0;j<i;j++)
{
JSONObject Data = result.getJSONObject(j);
Log.i("Data",Data.toString());
temp= (Data.getString("mainpriority"));
Log.i("temp", temp.toString());
storenamefinal.set(Integer.parseInt(temp) - 1, Data.getString("storename"));
Log.i("Result Length", storenamefinal.toString());
imagelinksfinal.add(R.drawable.ic_launcher);
}
Log.i("Result Length", storenamefinal.toString());
Toast.makeText(MainActivity.this,storenamefinal.get(0),Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
GridAdapterStores.java file
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by mithilesh.izardar on 6/17/2016.
*/
public class GridAdapterStores extends BaseAdapter {
private Context context;
private ArrayList<String> storename=new ArrayList<String>();
private ArrayList<Integer> imagelinks=new ArrayList<Integer>();
public GridAdapterStores(Context c,ArrayList<String> storename, ArrayList<Integer> imagelinks) {
context = c;
this.imagelinks = imagelinks;
this.storename = storename;
}
#Override
public int getCount() {
return storename.size();
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent){
View grid;
if (convertView == null) {
grid = new View(context);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
grid = inflater.inflate(R.layout.grid_stores,parent,false);
}
else {
grid = (View) convertView;
}
TextView textViewStoreName = (TextView) grid.findViewById(R.id.store_name);
ImageView imageViewStoreImage = (ImageView) grid.findViewById(R.id.store_image);
textViewStoreName.setText(storename.get(position));
// Integer x=imagelinks.get(position);
// imageViewStoreImage.setImageResource(x);
return grid;
}
Happy Coding :)
I want to display image to GridView in Android Studio, but it always fail to fetch data. Can you tell me why?
MainActivity.Java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.amobi.picassodemo.Model.GridItem;
import com.amobi.picassodemo.adapter.GridViewAdapter;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends ActionBarActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private GridView mGridView;
private ProgressBar mProgressBar;
private GridViewAdapter mGridAdapter;
private ArrayList<GridItem> mGridData;
private String URL="http://lomapod.azurewebsites.net/readBarang.php?id_penjual=1";
private String FEED_URL = "http://lomapod.esy.es/assets/bronco_turkey.jpg";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mGridView = (GridView) findViewById(R.id.gridView);
mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
//Initialize with empty data
mGridData = new ArrayList<>();
mGridAdapter = new GridViewAdapter(this, R.layout.grid_item_layout, mGridData);
mGridView.setAdapter(mGridAdapter);
//Start download
new AsyncHttpTask().execute(URL);
mProgressBar.setVisibility(View.VISIBLE);
}
public class AsyncHttpTask extends AsyncTask<String, Void, Integer> {
#Override
protected Integer doInBackground(String... params) {
Integer result = 0;
try {
// Create Apache HttpClient
HttpClient httpclient = new DefaultHttpClient();
HttpResponse httpResponse = httpclient.execute(new HttpGet(params[0]));
int statusCode = httpResponse.getStatusLine().getStatusCode();
// 200 represents HTTP OK
if (statusCode == 200) {
String response = streamToString(httpResponse.getEntity().getContent());
parseResult(response);
result = 1; // Successful
} else {
result = 0; //"Failed
}
} catch (Exception e) {
Log.d(TAG, e.getLocalizedMessage());
}
return result;
}
#Override
protected void onPostExecute(Integer result) {
// Download complete. Let us update UI
if (result == 1) {
mGridAdapter.setGridData(mGridData);
} else {
Toast.makeText(MainActivity.this, "Failed to fetch data!", Toast.LENGTH_SHORT).show();
}
mProgressBar.setVisibility(View.GONE);
}
}
String streamToString(InputStream stream) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
String line;
String result = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
// Close stream
if (null != stream) {
stream.close();
}
return result;
}
private void parseResult(String result) {
try {
JSONObject response = new JSONObject(result);
JSONArray posts = response.optJSONArray("posts");
GridItem item;
for (int i = 0; i < posts.length(); i++) {
JSONObject post = posts.optJSONObject(i);
String title = post.optString("title");
item = new GridItem();
item.setBarang(title);
JSONArray attachments = post.getJSONArray("attachments");
if (null != attachments && attachments.length() > 0) {
JSONObject attachment = attachments.getJSONObject(0);
if (attachment != null)
item.setImage(attachment.getString(FEED_URL));
}
mGridData.add(item);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
GridItem.Java
public class GridItem {
private String image;
private String barang;
public GridItem() {
super();
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getBarang() {
return barang;
}
public void setBarang(String barang) {
this.barang = barang;
}
}
GridViewAdapter.Java
package com.amobi.picassodemo.adapter;
import android.app.Activity;
import android.content.Context;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.amobi.picassodemo.Model.GridItem;
import com.amobi.picassodemo.R;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
/**
* Created by Nicky-PC on 4/9/2016.
*/
public class GridViewAdapter extends ArrayAdapter<GridItem> {
private Context mContext;
private int layoutResourceId;
private ArrayList<GridItem> mGridData = new ArrayList<GridItem>();
public GridViewAdapter(Context mContext, int layoutResourceId, ArrayList<GridItem> mGridData) {
super(mContext, layoutResourceId, mGridData);
this.layoutResourceId = layoutResourceId;
this.mContext = mContext;
this.mGridData = mGridData;
}
/**
* Updates grid data and refresh grid items.
* #param mGridData
*/
public void setGridData(ArrayList<GridItem> mGridData) {
this.mGridData = mGridData;
notifyDataSetChanged();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder holder;
if (row == null) {
LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ViewHolder();
holder.titleTextView = (TextView) row.findViewById(R.id.grid_item_title);
holder.imageView = (ImageView) row.findViewById(R.id.grid_item_image);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
GridItem item = mGridData.get(position);
holder.titleTextView.setText(Html.fromHtml(item.getBarang()));
Picasso.with(mContext).load(item.getImage()).into(holder.imageView);
return row;
}
static class ViewHolder {
TextView titleTextView;
ImageView imageView;
}
}
I have the following issue :
I'm having a GridView which displays alot of ImageViews , If I start scrolling the Items randomly start to change so there are wrong images at wrong positions and they start swapping everytime from position to position.
ImageAdapter
package com.zippyscore.pr0gramm.Adapter;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import com.zippyscore.pr0gramm.MainActivity;
import com.zippyscore.pr0gramm.Util.Constants;
import java.io.InputStream;
/**
* Created by Dominik on 16.01.2015.
*/
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return MainActivity.mainPagePostLoader.getPostList().size();
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder vh;
if (convertView == null) {
convertView = new ImageView(mContext);
vh = new ViewHolder();
vh.imageView = (ImageView) convertView;
convertView.setTag(vh);
} else {
vh = (ViewHolder) convertView.getTag();
}
new DownloadImageTask(vh.imageView).execute(MainActivity.mainPagePostLoader.getPosts().get(MainActivity.mainPagePostLoader.getPostList().get(position)).getThumb());
return convertView;
}
protected class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = "http://" + Constants.THUMB_DOMAIN + urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Pr0gramm", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
private class ViewHolder{
public ViewHolder(){}
public ImageView imageView;
//public TextView textView;
//Add any views you want to use in getView here
}
}
MainPagePostLoader(should be irrelevant)
package com.zippyscore.pr0gramm.Network;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.os.AsyncTask;
import android.util.Log;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import com.zippyscore.pr0gramm.CustomViews.ThumbImageView;
import com.zippyscore.pr0gramm.MainActivity;
import com.zippyscore.pr0gramm.Post.MainPagePost;
import com.zippyscore.pr0gramm.Util.GridRow;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* Created by Dominik on 13.01.2015.
*/
public class MainPagePostLoader{
int chunksLoaded;
int lastPromoted;
private HashMap<String, MainPagePost> posts = new HashMap<String, MainPagePost>();
private List<String> postList = new ArrayList<String>();
private NetworkHelper networkHelper;
public MainPagePostLoader(){
chunksLoaded = 0;
lastPromoted = 0;
networkHelper = new NetworkHelper();
}
public HashMap<String, MainPagePost> getPosts(){
return this.posts;
}
public List<String> getPostList(){
return this.postList;
}
public void loadNextChunk(){
if(chunksLoaded==0){
String serverResponse = networkHelper.connect("http://pr0gramm.com/api/items/get?flags=1&promoted=1"); //TODO ADD FLAG SUPPORT
if(serverResponse!=null){
try {
JSONObject serverResponseJSON = new JSONObject(serverResponse);
if(serverResponseJSON.has("items")) {
JSONArray postsJSON = serverResponseJSON.getJSONArray("items");
for(int i = 0; i < postsJSON.length();i++){
JSONObject post = postsJSON.getJSONObject(i);
posts.put(String.valueOf(post.getInt("id")),new MainPagePost(post.getInt("id"),post.getInt("promoted"),post.getInt("up"), post.getInt("down"), post.getLong("created"), post.getString("image"),post.getInt("flags"),post.getInt("mark"), post.getString("source"),post.getString("thumb"),post.getString("user")));
postList.add(String.valueOf(post.getInt("id")));
MainActivity.activity.runOnUiThread(new Runnable() {
#Override
public void run() {
MainActivity.imageAdapter.notifyDataSetChanged();
}
});
//addThumb(i);
}
}
chunksLoaded++;
} catch (JSONException e) {
Log.e("Pr0gramm","JSON Parse error : " + e.getMessage() + "|" + e.getCause());
}
}else{
Log.e("Pr0gramm", "Chunk loading error");
}
}else{
try {
String serverResponse = networkHelper.connect("http://pr0gramm.com/api/items/get?older=" + String.valueOf(posts.get(postList.size() - 1).getID()));
JSONObject serverResponseJSON = new JSONObject(serverResponse);
if(serverResponseJSON.has("items")){
JSONArray postsJSON = serverResponseJSON.getJSONArray("items");
for(int i = 0; i < postsJSON.length();i++){
JSONObject post = postsJSON.getJSONObject(i);
posts.put(String.valueOf(post.getInt("id")),new MainPagePost(post.getInt("id"),post.getInt("promoted"),post.getInt("up"), post.getInt("down"), post.getLong("created"), post.getString("image"),post.getInt("flags"),post.getInt("mark"), post.getString("source"),post.getString("thumb"),post.getString("user")));
postList.add(String.valueOf(post.getInt("id")));
MainActivity.imageAdapter.notifyDataSetChanged();
//addThumb(i + (postList.size()-1));
}
}
chunksLoaded++;
}catch(JSONException e){
Log.e("Pr0gramm", "JSON Parse error : " + e.getMessage() + "|" + e.getCause());
}
}
}
/*
private void addThumb(int id){
int currentRow = MainActivity.gridRows.size() - 1;
Point size = new Point();
MainActivity.defaultDisplay.getSize(size);
if(currentRow!=-1) {
if (MainActivity.gridRows.get(currentRow).getItemCount() < MainActivity.maxItemsPerRow) {
final ThumbImageView thumbImageView = new ThumbImageView(MainActivity.context, id);
thumbImageView.setLayoutParams(new RelativeLayout.LayoutParams(size.x / MainActivity.maxItemsPerRow, size.x / MainActivity.maxItemsPerRow));
thumbImageView.setX(MainActivity.gridRows.get(currentRow).getItemCount() * size.x / MainActivity.maxItemsPerRow);
thumbImageView.setY(currentRow * size.x / MainActivity.maxItemsPerRow);
MainActivity.activity.runOnUiThread(new Runnable() {
#Override
public void run() {
MainActivity.rootLayout.addView(thumbImageView);
}
});
MainActivity.gridRows.get(currentRow).addItem();
} else {
MainActivity.gridRows.add(new GridRow());
addThumb(id);
}
}else{
MainActivity.gridRows.add(new GridRow());
addThumb(id);
}
} */
}
Consider using the Square Picasso library for this rather than rolling your own:
http://square.github.io/picasso/
I have a problem here, this is my customAdapter for ListView.
I was trying to get an XML file and show it using this adapter.
I have few source of XML files and one of them has an image link.
Using this code, I have shown all the images, but somehow it was not placed in the correct imageView.
Can anyone see why this is not working correctly?
package dotmanga.classes;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import example.dotmanga.R;
public class TestAdapter extends BaseAdapter {
private Context con;
private List<Entry> entries;
private LayoutInflater inflater;
private Handler hand = new Handler();
static class ViewHolder {
TextView title;
TextView link;
ImageView imv;
}
public TestAdapter(Context c, List<Entry> e) {
this.con = c;
this.entries = e;
this.inflater = LayoutInflater.from(this.con);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return entries.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return entries.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final ViewHolder holder;
View vi = convertView;
if (convertView == null) {
vi = this.inflater.inflate(R.layout.activity_list_row, null);
holder = new ViewHolder();
holder.title = (TextView) vi.findViewById(R.id.title);
holder.link = (TextView) vi.findViewById(R.id.link);
holder.imv = (ImageView) vi.findViewById(R.id.imageView1);
vi.setTag(holder);
} else {
holder = (ViewHolder) vi.getTag();
}
Entry entry = entries.get(position);
holder.title.setText(entry.title);
holder.link.setText(entry.link);
if (entry.img != null) {
final String myurl = entry.img;
new Thread(new Runnable() {
public void run() {
try {
URL url = new URL(myurl);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
final Bitmap myBitmap = BitmapFactory.decodeStream(input);
hand.post(new Runnable() {
public void run() {
holder.imv.setImageBitmap(myBitmap);
}
});
connection.disconnect();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}
return vi;
}
}
Your issue is probably due to an empty imageView, if some image are empty, getView will display wrong image. You need to catch some "ErrorRessource".
like :
if (entry.img != null) {
//do some stuff
}
else {
holder.imv.setImageResource(R.drawable.theErrorImage);
}
But more deeply, i don't think you use the best practice to display images from Url, i strongly advice you to use some libs like https://github.com/lexs/webimageloader , who allow you to cache these images and do your job in an easy ans useful way.
I am working on an android application in which i have implemented CustomListView having some images and texts. i am feeding data in listview after a webservice call it takes some time to render list and when i scroll the list it's not scrolling smoothly.
here is the code of my List Adapter:
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.TextView;
import com.tv.makamaka.Constant;
import com.tv.makamaka.R;
import com.tv.makamaka.comment.SmileyCommentDialogActivity;
public class MakaMakaProfileListAdapter extends BaseAdapter implements Filterable {
private LayoutInflater mInflater;
private ArrayList<Object> itemList;
private Activity _activity;
String caption="";
String photoPath="";
String comments="";
String commentImage="";
String commentUserId="";
String likersImage="";
String likersType="";
String likersUserId="";
String mediaid="";
String mediaImageUrl="";
String mediaString="";
String mediaStringImage="";
String mediaStringUserId="";
String mediaType="";
String rating="";
String requestCount="";
String userid="";
String userProileImage="";
String withfriends="";
int index,index1,index2;
public MakaMakaProfileListAdapter(Activity activity, ArrayList<Object> itemList) {
this._activity = activity;
this.itemList = itemList;
mInflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return itemList.size();
}
public Object getItem(int position) {
return itemList.get(position);
}
public Filter getFilter() {
return null;
}
public long getItemId(int position) {
return 0;
}
static class ViewHolder {
TextView _commentTxt;
ImageView _userImage;
ImageView _smallUserImage;
ImageView _smallPostedUserImage;
ImageView _transparentImage;
}
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.makamaka_profile_listrow, null);
holder = new ViewHolder();
holder._userImage=(ImageView)convertView.findViewById(R.id.posted_userimage);
holder._smallUserImage=(ImageView)convertView.findViewById(R.id.small_userimage);
holder._smallPostedUserImage=(ImageView)convertView.findViewById(R.id.small_posted_userimage);
holder._transparentImage=(ImageView)convertView.findViewById(R.id.transparent_smiley_image);
holder._commentTxt = (TextView) convertView.findViewById(R.id.comment_txt);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder._commentTxt.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
}
});
holder._transparentImage.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent=new Intent(_activity,SmileyCommentDialogActivity.class);
_activity.startActivity(intent);
}
});
//////////////////SET VALUES ON LIST VIEW///////////////////////////
MakaMakaProfileBean makaMakaProfileBean=(MakaMakaProfileBean)itemList.get(position);
////////////////PARSE CAPTION///////////
caption=makaMakaProfileBean.getCaption();
ArrayList<String> captionList = new ArrayList<String>(Arrays.asList(caption.split(" , ")));
/*int index=caption.indexOf(",");
String caption1=caption.substring(0,index);
int index1=caption.indexOf(",", index+1);
String userName=caption.substring(index,index1+1);
String timeAgo=caption.substring(index1+1);*/
////////////////////////////////////////
////////////////PARSE COMMENTS////////////
comments=makaMakaProfileBean.getComments();
ArrayList<String> commentList = new ArrayList<String>(Arrays.asList(comments.split(" , ")));
//////////////////////////////////////////
////////////////PARSE COMMENT IMAGES//////
commentImage=makaMakaProfileBean.getCommentImage();
ArrayList<String> commentImageList = new ArrayList<String>(Arrays.asList(commentImage.split(" , ")));
//////////////////////////////////////////
////////////////PARSE COMMENT USER ID//////
commentUserId=makaMakaProfileBean.getCommentId();
ArrayList<String> commentUserIdList = new ArrayList<String>(Arrays.asList(commentUserId.split(" , ")));
//////////////////////////////////////////
////////////////PARSE LIKER IMAGES//////
likersImage=makaMakaProfileBean.getlikersImage();
ArrayList<String> likersImageList = new ArrayList<String>(Arrays.asList(likersImage.split(" , ")));
//////////////////////////////////////////
////////////////PARSE LIKER TYPE//////
likersType=makaMakaProfileBean.getComments();
ArrayList<String> likerTypeList = new ArrayList<String>(Arrays.asList(likersType.split(" , ")));
//////////////////////////////////////////
////////////////PARSE LIKER USER ID//////
likersUserId=makaMakaProfileBean.getComments();
ArrayList<String> likerUserIdList = new ArrayList<String>(Arrays.asList(likersUserId.split(" , ")));
//////////////////////////////////////////
////////////////PARSE OTHER PARAS//////
mediaid=makaMakaProfileBean.getmediaId();
mediaImageUrl=makaMakaProfileBean.getMediaImageUrl();
mediaString=makaMakaProfileBean.getMediaString();
mediaStringImage=makaMakaProfileBean.getMediaStringImage();
//mediaStringUserId=makaMakaProfileBean.
mediaType=makaMakaProfileBean.getMediaType();
rating=makaMakaProfileBean.getRating();
requestCount=makaMakaProfileBean.getRequestCount();
userid=makaMakaProfileBean.getUserId();
//userProileImage=makaMakaProfileBean.getUserProfileImage();
withfriends=makaMakaProfileBean.getWithFriends();
//////////////////////////////////////////
photoPath=makaMakaProfileBean.getUserProfileImage();
if(photoPath!=null){
URL url;
try {
url = new URL(photoPath);
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
holder._userImage.setImageBitmap(bmp);
} catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
int i=0;
while(i<captionList.size()){
if(i==0){
holder._commentTxt.setText((String)captionList.get(i));
}else if(i==1){
holder._commentTxt.setText(Html.fromHtml((String)captionList.get(i)));
}else if(i==2){
holder._commentTxt.setText(Html.fromHtml((String)captionList.get(i)));
}
i++;
}
return convertView;
/////////////////////////////////////////////////////////////////////
}
private Handler _handler = new Handler() {
public void dispatchMessage(Message msg) {
switch (msg.arg1) {
case 123:
break;
default:
break;
}
}
};
public void serverResponse(String response, int processid) {
Message msg = new Message();
msg.arg1 = processid;
msg.obj = response;
_handler.dispatchMessage(msg);
}
//SEND EMAIL TO INVITE FRIEND
public void sendEmail(String emailId){
Intent intent = new Intent(Intent.ACTION_SEND);
//intent.setType("text/plain");
intent.setType("message/rfc822");
intent.putExtra(Intent.EXTRA_EMAIL, emailId);
intent.putExtra(Intent.EXTRA_SUBJECT,Constant.EMAIL_SUBJECT);
intent.putExtra(Intent.EXTRA_TEXT, Constant.EMAIL_CONTENT);
_activity.startActivity(Intent.createChooser(intent, "Send Email"));
}
}
Output:
Is there any way to make list with smooth scroll.
You're decoding the image in getView. That's an expensive call, and you're going to be doing it a lot while scrolling. Use an LRUCache to cache images, so you can reuse the results of previous decodes if they exist. Only decode it in getView if its not in the cache.