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/
My project works without error, but upon loading, images are not loaded in the Listview.
Here is a sample image
sample at the first working image
But after dragging ListView, all images loads.
sample draggened image load
Please Help. Sorry bad english.
Categoryadapter.java
package com.medyasef.dernek.tjod;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.http.AndroidHttpClient;
import android.os.AsyncTask;
import android.util.Log;
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 org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* Created by olkunmustafa on 26.09.2013.
*/
public class CategoryAdapter extends BaseAdapter {
private String LOG_NAME = "HATA";
private List<Categoryicerikler> list_view;
private HashMap<Integer,Bitmap> bitmaplist;
private Context mContext;
private Categories categories = new Categories();
public CategoryAdapter(List<Categoryicerikler> list_view, Context mContext) {
this.list_view = list_view;
this.mContext = mContext;
bitmaplist = new HashMap<Integer, Bitmap>();
for (int i = 0; i < list_view.size() ; i++) {
Categoryicerikler bitmap_icerikler = list_view.get(i);
setBitmapFromURL(bitmap_icerikler.getCategory_post_image(),i);
}
}
/*
Burada resimleri çekmek için thread oluşturuyoruz.
Resim linkini ve ImageView'i veriyoruz ve ekrana basmasını sağlıyoruz.
*/
public void setBitmapFromURL(final String src,final int value) {
new Thread(
new Runnable()
{
#Override
public void run() {
HttpURLConnection connection= null;
try {
URL url = new URL(src);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.connect();
InputStream input = connection.getInputStream();
final Bitmap myBitmap = BitmapFactory.decodeStream(input);
try {
bitmaplist.put(value,myBitmap);
}
catch (Exception e){
Log.d(LOG_NAME,e.getMessage());
Log.d(LOG_NAME,"Resim ekleme işlemi başarısız.");
}
} catch (IOException e) {
e.printStackTrace();
}
finally {
connection.disconnect();
}
}
}).start();
}
#Override
public int getCount() {
return list_view.size();
}
#Override
public Object getItem(int position) {
return list_view.get(position);
}
#Override
public long getItemId(int position) {
return list_view.indexOf(getItem(position));
}
#Override
public View getView(int position, View convertview, ViewGroup viewGroup) {
Categoryicerikler categoryicerikler = list_view.get(position);
ViewHolder holder = null;
if(convertview==null){
Log.d(LOG_NAME,"sonuc");
convertview = LayoutInflater.from(mContext).inflate(R.layout.categories,viewGroup,false);
holder = new ViewHolder();
holder.txtTitle = (TextView) convertview.findViewById(R.id.category_posttitle);
holder.txtDate = (TextView) convertview.findViewById(R.id.category_postdate);
holder.imageView = (ImageView) convertview.findViewById(R.id.category_image);
convertview.setTag(holder);
Categories.categoryAdapter.notifyDataSetChanged();
}
else {
holder = (ViewHolder) convertview.getTag();
}
holder.txtTitle.setText(categoryicerikler.getCategory_posttitle());
holder.txtDate.setText(categoryicerikler.getCategory_postdate());
try {
holder.imageView.setImageBitmap(bitmaplist.get(position));
}
catch (Exception e){
}
return convertview;
}
/*private view holder class*/
private class ViewHolder {
ImageView imageView;
TextView txtTitle;
TextView txtDate;
}
}
Categoryicerikler.java
package com.medyasef.dernek.tjod;
import android.graphics.Bitmap;
import android.widget.ImageView;
/**
* Created by olkunmustafa on 26.09.2013.
*/
public class Categoryicerikler {
private String category_posttitle;
private String category_postdate;
private String category_post_content;
private String category_post_image;
public Categoryicerikler( String category_posttitle, String category_postdate, String category_post_content,String post_image) {
this.category_posttitle = category_posttitle;
this.category_postdate = category_postdate;
this.category_post_content = category_post_content;
this.category_post_image = post_image;
}
public String getCategory_posttitle() {
return category_posttitle;
}
public void setCategory_posttitle(String category_posttitle) {
this.category_posttitle = category_posttitle;
}
public String getCategory_postdate() {
return category_postdate;
}
public void setCategory_postdate(String category_postdate) {
this.category_postdate = category_postdate;
}
public String getCategory_post_content() {
return category_post_content;
}
public void setCategory_post_content(String category_post_content) {
this.category_post_content = category_post_content;
}
public String getCategory_post_image() {
return category_post_image;
}
public void setCategory_post_image(String category_post_image) {
this.category_post_image = category_post_image;
}
}
Categories.java
package com.medyasef.dernek.tjod;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.text.Html;
import android.util.Log;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONException;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
/**
* Created by olkunmustafa on 25.09.2013.
*/
public class Categories extends Activity {
private List<Categoryicerikler> content_list;
public static CategoryAdapter categoryAdapter;
private ListView main_category;
private static HashMap<Integer,Bitmap> bitmaplist;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_categories);
main_category = (ListView) findViewById(R.id.main_category);
new GetCategory().execute();
}
private class GetCategory extends AsyncTask<Void,Void,String> {
#Override
protected void onPreExecute() {
Toast.makeText(Categories.this, "İslem Baslıyor Bekleyiniz", Toast.LENGTH_SHORT).show();
}
#Override
protected String doInBackground(Void... voids) {
/*
Burada internete bağlanıp json veriyi string cinsinden çekiyoruz.
*/
InternetConnection internetcon = new InternetConnection();
String json_result = internetcon.get_json_data();
return json_result;
}
#Override
protected void onPostExecute(String data) {
/*
Gelen string veriyi json_to_list_view metoduna veriyorum
Bu metot gelen json verisinin içeriklerini doldurarak bana birt liste dönderir.
*/
try {
content_list = GetJson.json_to_list_view(data);
} catch (JSONException e) {
Log.d("Json_Error","Json çekilirken hata oluştu");
}
categoryAdapter = new CategoryAdapter(content_list,Categories.this);
main_category.setAdapter(categoryAdapter);
}
}
}
If you simply want to load images in a list view, I would recommend you to use Picasso
Its simple, fast and does nearly everything automatically for you. You also don't have to care about canceling request on activity destroy. So I guess this would be the best start for you, if you simply want to load images into a ImageView in a ListView.
for instance in your adapter you could use:
Picasso.with(context)
.load(url)
.placeholder(R.drawable.placeholder)
.error(R.drawable.error)
.into(imageView);
Where imageview is the ImageView of your listview cell
Use universal image loader library and then following way
---------------------------------------------------------
1 - options = new DisplayImageOptions.Builder()
.showStubImage(R.drawable.physicalgift_normal)
.cacheInMemory()
.cacheOnDisc()
.displayer(new RoundedBitmapDisplayer(10))
.build();
imageLoader=ImageLoader.getInstance();
ImageLoaderConfiguration imgconfig=ImageLoaderConfiguration.createDefault(context);
imageLoader.init(imgconfig);
----------------------------------------------------------
2 - String url=list.get(position).getThumbUrl();
if(url != null && url !="")
imageLoader.displayImage(Utils.getEncodedUrl(url), holder.img, options);
------------------------------------------------------------
3 - SubCatAdapter adapter = new SubCatAdapter(SubCategoryActivity.this,
mlist);
list.setAdapter(adapter);
------------------------------------------------------------
full example is here
public class SubCatAdapter extends BaseAdapter {
private ArrayList<SubcategoryData> list;
private LayoutInflater inflator;
public ImageLoader imageLoader;
private DisplayImageOptions options;
public SubCatAdapter(Context context, ArrayList<SubcategoryData> mlist) {
super();
this.list = mlist;
this.inflator = LayoutInflater.from(context);
options = new DisplayImageOptions.Builder()
.showStubImage(R.drawable.physicalgift_normal)
.cacheInMemory()
.cacheOnDisc()
.displayer(new RoundedBitmapDisplayer(10))
.build();
imageLoader=ImageLoader.getInstance();
ImageLoaderConfiguration imgconfig=ImageLoaderConfiguration.createDefault(context);
imageLoader.init(imgconfig);
}
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return list.get(position);
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View view = convertView;
ViewHolder holder = null;
if (convertView == null) {
view = inflator.inflate(R.layout.row_subcat, null);
holder = new ViewHolder();
holder.txt_Name = (TextView) view.findViewById(R.id.txt_name);
holder.img=(ImageView)view.findViewById(R.id.img_row);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.txt_Name.setText(list.get(position).getName());
String url=list.get(position).getThumbUrl();
if(url != null && url !="")
imageLoader.displayImage(Utils.getEncodedUrl(url), holder.img, options);
return view;
}
static class ViewHolder {
TextView txt_Name;
ImageView img;
}
}
I have an adapter that gets a list of items from an API and then puts it in a listview. This is the first time that Im working with adapters and list views and so far Im struggling quite a lot!
Why am I getting this error? Is my context wrong or something?
package com.example.tvrplayer;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class HiddenChannelsListAdapter extends BaseAdapter {
private Context mContext;
private ArrayList mItems;
private LayoutInflater mInflater;
public HiddenChannelsListAdapter(Context ctx, ArrayList list) {
mItems = list;
mContext = ctx;
mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return mItems.size();
}
#Override
public HashMap getItem(int position) {
return (HashMap) mItems.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
System.out.println("getView " + position + " " + convertView);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.channel_item, parent, false);
} else {
((TextView) convertView.findViewById(R.id.channel_text)).setText("Testing");
}
return convertView;
}
public static class ViewHolder {
public TextView textView;
}
}
Asyntask to get the items from the server:
package com.example.tvrplayer;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
class ChannelPair {
public ListView lv;
public ArrayList channelList;
public Context ctx;
}
public class ChannelHandler extends AsyncTask<Object, Integer, ChannelPair> {
#Override
protected ChannelPair doInBackground(Object... params) {
ChannelPair p = new ChannelPair();
String apiurl = (String) params[0];
String linkid = (String) params[1];
String username = (String) params[2];
String channelID = null;
View vw = (View) params[3];
ListView lv = (ListView) vw.findViewById(R.id.list);
p.lv = lv;
JSONArray channels;
ArrayList< HashMap < String, String > > channelList = new ArrayList < HashMap < String, String > > ();
try {
channels = Json.getJson(apiurl + "/rest/channel/"+ username +"/"+ linkid, "GET");
Log.i("CHANNELS", channels.toString());
for (int i=0; i < channels.length(); i++) {
JSONObject json_data = channels.getJSONObject(i);
String name = json_data.getString("Name");
String channelid = json_data.getString("ChannelID");
HashMap<String, String> channelObject = new HashMap<String, String>();
// if ( json_data.getString("ParentPath") == "" ) {
channelObject.put("id", channelid);
channelObject.put("name", name);
channelList.add(channelObject);
// }
}
Log.i("ROOT CHANNELS", channelList.toString());
p.channelList = channelList;
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return p;
}
#Override
protected void onPostExecute(final ChannelPair p) {
HiddenChannelsListAdapter adapter = new HiddenChannelsListAdapter(p.ctx, p.channelList);
p.lv.setAdapter(adapter);
}
}
The error is in this line:
HiddenChannelsListAdapter.java:28
mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
The full error code:
java.lang.NullPointerException
at com.example.tvrplayer.HiddenChannelsListAdapter.<init>(HiddenChannelsListAdapter.java:28)
at com.example.tvrplayer.ChannelHandler.onPostExecute(ChannelHandler.java:71)
at com.example.tvrplayer.ChannelHandler.onPostExecute(ChannelHandler.java:1)
at android.os.AsyncTask.finish(AsyncTask.java:602)
at android.os.AsyncTask.access$600(AsyncTask.java:156)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:615)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4514)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
at dalvik.system.NativeStart.main(Native Method)