caching images from json in listview? - java

I followed this lesson here which talk about json parsing and image loading in list view the example works good but it has a problem in imageview when scrolling up & down all images reloading so can anyone solve this problem?
this the adapter of listview
package com.wingnity.jsonparsingtutorial;
import java.io.InputStream;
import java.util.ArrayList;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
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.tvName = (TextView) v.findViewById(R.id.tvName);
holder.tvDescription = (TextView) v.findViewById(R.id.tvDescriptionn);
holder.tvDOB = (TextView) v.findViewById(R.id.tvDateOfBirth);
holder.tvCountry = (TextView) v.findViewById(R.id.tvCountry);
holder.tvHeight = (TextView) v.findViewById(R.id.tvHeight);
holder.tvSpouse = (TextView) v.findViewById(R.id.tvSpouse);
holder.tvChildren = (TextView) v.findViewById(R.id.tvChildren);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
holder.imageview.setImageResource(R.drawable.ic_launcher);
new DownloadImageTask(holder.imageview).execute(actorList.get(position).getImage());
holder.tvName.setText(actorList.get(position).getName());
holder.tvDescription.setText(actorList.get(position).getDescription());
holder.tvDOB.setText("B'day: " + actorList.get(position).getDob());
holder.tvCountry.setText(actorList.get(position).getCountry());
holder.tvHeight.setText("Height: " + actorList.get(position).getHeight());
holder.tvSpouse.setText("Spouse: " + actorList.get(position).getSpouse());
holder.tvChildren.setText("Children: " + actorList.get(position).getChildren());
return v;
}
static class ViewHolder {
public ImageView imageview;
public TextView tvName;
public TextView tvDescription;
public TextView tvDOB;
public TextView tvCountry;
public TextView tvHeight;
public TextView tvSpouse;
public TextView tvChildren;
}
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 mIcon = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
}

Used the Android Universal Image-Loader This is best
Declare
private ImageLoader imageLoader1;
On Create
imageLoader1 = ImageLoader.getInstance();
imageLoader1.init(ImageLoaderConfiguration.createDefault(getActivity()));
no_image here a drawable image without any image load in Cache
DisplayImageOptions
options = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisk(true)
.showImageOnLoading(R.drawable.no_image) // resource or drawable
.showImageForEmptyUri(R.drawable.no_image) // resource or drawable
.showImageOnFail(R.drawable.no_image)
.considerExifParams(true)
.bitmapConfig(Bitmap.Config.RGB_565)
.build();
imageLoader1.displayImage(yourpath.replace(" ", "%20"), ivprofile, options);
You Can Use Piccaso Also and Glide also

here is the code after editing it works like a charm
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
public class ActorAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Actors> movieItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public ActorAdapter(Activity activity, List<Actors> movieItems) {
this.activity = activity;
this.movieItems = movieItems;
}
#Override
public int getCount() {
return movieItems.size();
}
#Override
public Object getItem(int location) {
return movieItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.list_item, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
NetworkImageView thumbNail = (NetworkImageView) convertView
.findViewById(R.id.flag);
TextView title = (TextView) convertView.findViewById(R.id.rank);
// getting movie data for the row
Actors m = movieItems.get(position);
// thumbnail image
thumbNail.setImageUrl(m.getImage(), imageLoader);
// title
title.setText(m.getName());
return convertView;
}
}

Related

Attempt to get length of null array - retrieve bitmap image from sqlite DB

I am trying to retrieve an image from an SQLite database. The image is stored as a BLOB and trying to retrieve it using an array. I'm not sure why its doing this. The permissions are all set correctly.
package com.example.joao_.quizathonegroupteamproject.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
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.example.joao_.quizathonegroupteamproject.DatabaseClasses.User;
import com.example.joao_.quizathonegroupteamproject.R;
import java.util.ArrayList;
/**
* Created by Quoc Nguyen on 13-Dec-16.
*/
public class UserListAdapter extends BaseAdapter {
private Context context;
private int layout;
private ArrayList<User> foodsList;
public UserListAdapter(Context context, int layout, ArrayList<User> foodsList) {
this.context = context;
this.layout = layout;
this.foodsList = foodsList;
}
#Override
public int getCount() {
return foodsList.size();
}
#Override
public Object getItem(int position) {
return foodsList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
private class ViewHolder{
ImageView imageView;
}
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
View row = view;
ViewHolder holder = new ViewHolder();
if(row == null){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(layout, null);
holder.imageView = (ImageView) row.findViewById(R.id.imgFood);
row.setTag(holder);
}
else {
holder = (ViewHolder) row.getTag();
}
User food = foodsList.get(position);
byte[] tblUsersImage = food.getImage();
Bitmap bitmap = BitmapFactory.decodeByteArray(tblUsersImage, 0, tblUsersImage.length);
holder.imageView.setImageBitmap(bitmap);
return row;
}
}
You can retrieve BLOB image and stored it in Byte array like this:
byte[] array = cursor.getBlob(columnIndex);
Bitmap bitmap = BitmapFactory.decodeByteArray(array, 0 ,array.length);
and then set it into image view
holder.imageView.setImageBitmap(bitmap);
you didn't provide your SQLite database class but i think , your food.getImage(); return null value .
check dataInsert method OR getData in your SQLite db !

Adding Drawables from assets into ListView

I have added many images in the assets folder and want to get those images from there and add it into a ListView.
When i am executing the app everything is perfect but the image container of the listview appears blank(transparent).
Output
The Java File:
package com.basil.victor;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import java.io.IOException;
import java.io.InputStream;
public class Events extends Fragment {
private ListView listEvent;
String eventname[]={
"Name",
"of",
"the",
"events",
"are",
"present",
"here"
};
String eventlogoname[]={
"Logo",
"name",
"of",
"events",
"are",
"present",
"here"
};
Drawable[] arr=new Drawable[7];
String eventsubtitle []={
"Subtitles",
"of",
"the",
"events",
"are",
"present",
"here"
};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_events, null);
for(int i=0;i<7;i++) {
try {
InputStream stream = getContext().getAssets().open(eventlogoname[i] + ".jpg");
Drawable el = Drawable.createFromStream(stream, null);
arr[i] = el;
} catch (IOException e) {
e.printStackTrace();
}
}
EventList adapter = new
EventList(getActivity(), eventname, arr, eventsubtitle);
//ListView lv = (ListView)rootView.
listEvent=(ListView)view.findViewById(R.id.listEvent);
listEvent.setAdapter(adapter);
return view;
}
}
ListView adapter:
package com.basil.victor;
import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class EventList extends ArrayAdapter<String>{
private final Activity context;
private final String[] title;
private final Drawable[] banner;
private final String[] subtitle;
public EventList(Activity context,
String[] title, Drawable[] banner, String[] subtitle) {
super(context, R.layout.list_single, title);
this.context = context;
this.title = title;
this.banner = banner;
this.subtitle = subtitle;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView= inflater.inflate(R.layout.event_row, null, true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.event_title);
ImageView imageView = (ImageView) rowView.findViewById(R.id.event_banner);
TextView subTitle = (TextView) rowView.findViewById(R.id.event_subtitle);
txtTitle.setText(title[position]);
imageView.setImageDrawable(banner[position]);
subTitle.setText(subtitle[position]);
return rowView;
}
}
If you're getting a FileNotFound Exception,
Check if the image is inside a subfolder in assets and add the appropriate path
Check the case of the extension (I faced this problem for a long time before I realized my image had a .JPG (Uppercase) extension)
The final string that's being searched, check for random whitespaces
Why are using asset folder for images? if it is not necessary then you can use drawable for same put all images in drawable folder and
package com.basil.victor;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import java.io.IOException;
import java.io.InputStream;
public class Events extends Fragment {
private ListView listEvent;
String eventname[]={
"Name",
"of",
"the",
"events",
"are",
"present",
"here"
};
int[] arr=new int[7];
String eventsubtitle []={
"Subtitles",
"of",
"the",
"events",
"are",
"present",
"here"
};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_events, null);
arr[]={
R.drawable.Logo,
R.drawable.name,
R.drawable.of,
R.drawable.events,
R.drawable.are,
R.drawable.present,
R.drawable.here
};
EventList adapter = new
EventList(getActivity(), eventname, arr, eventsubtitle);
//ListView lv = (ListView)rootView.
listEvent=(ListView)view.findViewById(R.id.listEvent);
listEvent.setAdapter(adapter);
return view;
}
}
adapter:
package com.basil.victor;
import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class EventList extends ArrayAdapter<String>{
private final Activity context;
private final String[] title;
private final int[] banner;
private final String[] subtitle;
public EventList(Activity context,
String[] title, int[] banner, String[] subtitle) {
super(context, R.layout.list_single, title);
this.context = context;
this.title = title;
this.banner = banner;
this.subtitle = subtitle;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView= inflater.inflate(R.layout.event_row, null, true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.event_title);
ImageView imageView = (ImageView) rowView.findViewById(R.id.event_banner);
TextView subTitle = (TextView) rowView.findViewById(R.id.event_subtitle);
txtTitle.setText(title[position]);
imageView.setImageResource((banner[position]);
subTitle.setText(subtitle[position]);
return rowView;
}
}
Do it like this
class MainActivity extends AppCompatActivity {
private ListView listEvent;
String arras[]={
"Logo",
"name",
"of",
"events",
"are",
"present",
"here"
};
Drawable[] arr=new Drawable[5];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EventList adapter = new EventList(MainActivity.this, arras);
//ListView lv = (ListView)rootView.
listEvent=(ListView)findViewById(R.id.listEvent);
listEvent.setAdapter(adapter);
}
}
And Adapter class is like this
public class EventList extends BaseAdapter {
LayoutInflater inflater;
private final Activity context;
String arras[];
public EventList(Activity context,String[] arras) {
super();
this.context = context;
this.arras = arras;
inflater = (LayoutInflater) this.context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return arras.length;
}
#Override
public Object getItem(int position) {
return arras.length;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View myView, ViewGroup parent) {
if (myView == null) {
myView = inflater.inflate(R.layout.event_row, null, true);
}
ImageView imageView = (ImageView) myView.findViewById(R.id.event_banner);
try {
InputStream stream = context.getAssets().open(arras[position] + ".jpg");
Drawable el = Drawable.createFromStream(stream, null);
imageView.setImageDrawable(el);
} catch (IOException e) {
e.printStackTrace();
}
return myView;
}
}
Use a ViewHolder
ViewHolder makes the list view to load faster by caching the views. If it look up the view every time by calling the findViewById(), it will be very slow.
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
ViewHolder holder; // to reference the child views for later actions
if (v == null) {
LayoutInflater vi =
(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.mainrow, null);
// cache view fields into the holder
holder = new ViewHolder();
holder.ImageView = (ImageView) v.findViewById(R.id.event_banner);
// associate the holder with the view for later lookup
v.setTag(holder);
} else {
// view already exists, get the holder instance from the view
holder = (ViewHolder) v.getTag();
}
// no local variables with findViewById here
// use holder.ImageView where you were
// using the local variable nameText before
try {
InputStream stream = context.getAssets().open(arras[position] + ".jpg");
Drawable el = Drawable.createFromStream(stream, null);
holder.ImageView.setImageDrawable(el);
} catch (IOException e) {
e.printStackTrace();
}
return v;
}
// somewhere else in your class definition
static class ViewHolder {
ImageView imageView;
}

Void android.widget.imageview.setimageresource(int)' on a Null Reference(fatal error message in the log cat)

Please am having issue with this null error message java.lang.NullPointerException (no error message). I really need assistance on how and where to add the appropriate code so that the application would not crash. Here is the JAVA file that i am having issues with. I am trying to create a recycler view and jpg images from my drawable folder
HorizontalListAdapter.java
import android.app.Activity;
import android.graphics.Picture;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
public class HorizontalListAdapter extends RecyclerView.Adapter<HorizontalListAdapter.ViewHolder>
{
private Activity activity;
int[] images= {R.drawable.vb1,R.drawable.pota,R.drawable.vb1,
R.drawable.pota,R.drawable.vb1,R.drawable.download1,R.drawable.pota};
String[] food_items={"prawan","awadhi_lucknow_biryani","eggwraps","chips","mayonnaise","companin","mixvegwrap"};
public HorizontalListAdapter(Activity activity)
{
this.activity = activity;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
LayoutInflater inflater = activity.getLayoutInflater();
View view = inflater.inflate(R.layout.item_horizontal_list, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(HorizontalListAdapter.ViewHolder viewHolder, final int position) {
viewHolder.imageView.setImageResource(images[position]);
viewHolder.txtview.setText(food_items[position].toUpperCase());
viewHolder.linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(activity, "Position clicked: " + position, Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return images.length;
}
/**
* View holder to display each RecylerView item
*/
protected class ViewHolder extends RecyclerView.ViewHolder {
private LinearLayout linearLayout;
private ImageView imageView;
private TextView txtview;
public ViewHolder(View view) {
super(view);
imageView = (ImageView) view.findViewById(R.id.imageview);
txtview = (TextView) view.findViewById(R.id.txtview);
linearLayout = (LinearLayout) view.findViewById(R.id.layout);
}
}
}
The second java class VerticalListAdapter.java
import android.app.Activity;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
public class VerticalListAdapter extends RecyclerView.Adapter<VerticalListAdapter.ViewHolder> {
private Activity activity;
public VerticalListAdapter(Activity activity) {
this.activity = activity;
}
int[] images= {R.drawable.images,R.drawable.images,R.drawable.images,
R.drawable.images,R.drawable.images,R.drawable.images,R.drawable.images};
String[] food_items={"prawan","awadhi_lucknow_biryani","eggwraps","chips","mayonnaise","companin","mixvegwrap"};
String[] cost={"Rs 200","Rs 300","Rs 150","R 320","Rs 450","Rs 120","Rs 380"};
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = activity.getLayoutInflater();
View view = inflater.inflate(R.layout.item_recycler_view, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, final int position) {
// if ((position + 1) % 2 == 0) {
viewHolder.imageView.setImageResource(images[position]);
viewHolder.txtview.setText(food_items[position].toUpperCase());
viewHolder.txtCost.setText("Cost Per Person "+cost[position]);
// } else {
// viewHolder.imageView.setImageResource(R.drawable.awadhi_lucknow_biryani);
//}
viewHolder.container.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(activity, "Position: " + position, Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return images.length;
}
/**
* View holder to display each RecylerView item
*/
protected class ViewHolder extends RecyclerView.ViewHolder {
private ImageView imageView;
private TextView txtview;
private TextView txtCost;
private RelativeLayout container;
public ViewHolder(View view) {
super(view);
imageView = (ImageView) view.findViewById(R.id.image);
txtview = (TextView) view.findViewById(R.id.text);
txtCost= (TextView) view.findViewById(R.id.textView);
container = (RelativeLayout) view.findViewById(R.id.container);
}
}
}
Please i need assistance with this i guess it is the int[]images causing the error i may be wrong please correct me with the right code i would use to replace and make the code work.
changeimageview accessibility form private to any other modifier & try again

Display Image in Listview with AsyncTask

I am trying to display images in a listview with AsyncTask but I am getting an error. Saying...
Attempt to invoke virtual method 'java.lang.String
java.lang.Object.toString()' on a null object reference
This is error is happening on
public LoadImage(ImageView imv) {
this.imv = imv;
this.path = imv.getTag().toString();
}
And
LoadImage loadImage = new LoadImage(imageView);
Bitmap bitmap = loadImage.doInBackground();
Here is LoadImage.java
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Environment;
import android.view.View;
import android.widget.ImageView;
import java.io.File;
/**
* Created by Yudii on 27/05/2016.
*/
class LoadImage extends AsyncTask<Object, Void, Bitmap>{
private ImageView imv;
private String path;
public LoadImage(ImageView imv) {
this.imv = imv;
this.path = imv.getTag().toString();
}
#Override
protected Bitmap doInBackground(Object... params) {
Bitmap bitmap = null;
File file = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath() + path);
if (file.exists()) {
bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
}
return bitmap;
}
#Override
protected void onPostExecute(Bitmap result) {
if (!imv.getTag().toString().equals(path)) {
/* The path is not same. This means that this
image view is handled by some other async task.
We don't do anything and return. */
// return;
}
if(result != null && imv != null){
imv.setVisibility(View.VISIBLE);
imv.setImageBitmap(result);
}else{
imv.setVisibility(View.GONE);
}
}
}
And here is CustomList.java
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
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 java.util.ArrayList;
public class CustomList extends ArrayAdapter<String>{
private final Activity context;
private final Integer[] imageId;
public CustomList(Activity context,
String[] web, Integer[] imageId) {
super(context, R.layout.list_single, web);
this.context = context;
this.imageId = imageId;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView= inflater.inflate(R.layout.list_single, null, true);
ImageView imageView = (ImageView) rowView.findViewById(R.id.img);
LoadImage loadImage = new LoadImage(imageView);
Bitmap bitmap = loadImage.doInBackground();
imageView.setImageResource(imageId[position]);
return rowView;
}
}
And here is MainActivity.java
import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity {
ListView list;
String[] web = {
"Google Plus",
"Twitter",
"Tall",
};
Integer[] imageId = {
R.drawable.gggggggggg,
R.drawable.hhhhhhhhhh,
R.drawable.ttttttttttt
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CustomList adapter = new
CustomList(MainActivity.this, web, imageId);
list=(ListView)findViewById(R.id.list);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, "You Clicked at " +web[+ position], Toast.LENGTH_SHORT).show();
}
});
}
}
You need to change loadImage.execute(); instead of Bitmap bitmap = loadImage.doInBackground();
Why do you need AsyncTask? Try to use library Picasso and open images by one string:
File file = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath() + path);
Picasso.with(context).load(file).into(imageView);
Bitmap objects are very weight and you need to clean memory after each Bitmap image for prevent OutOfMemoryError. I recommend you to use libraries.
Add this in your dependencies :-
compile 'com.squareup.picasso:picasso:2.5.2'
and then load your image :-
Picasso.with(this)
.load(drawerImage) // ImagePath
.placeholder( R.mipmap.download)
.error( R.mipmap.add_photo)
.into(imageDrawerView); //ImageView
1,Reason:
As I see, in your getView function:
ImageView imageView = (ImageView) rowView.findViewById(R.id.img);
// You need to set tag to your image view
// Ex: imageView.setTag("your_image_file_path") below this line
your imageView has no tag so the below code will get NullPointerException.
public LoadImage(ImageView imv) {
this.imv = imv;
this.path = imv.getTag().toString(); // Crashed here.
}
Also, I see in your getView function has this code:
imageView.setImageResource(imageId[position]);
That means "your ImageView will set resource corresponding to defined imageId array". So you no need AsyncTask class, let remove it and change your getView like below:
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView= inflater.inflate(R.layout.list_single, parent, false);
ImageView imageView = (ImageView) rowView.findViewById(R.id.img);
// Remove below code
// LoadImage loadImage = new LoadImage(imageView);
// Bitmap bitmap = loadImage.doInBackground();
imageView.setImageResource(imageId[position]);
return rowView;
}
Your Asynctask class is needed whenever you use path of image file, not drawable resources.
2, Improvement:
You can learn more about ViewHolder pattern when using ListView, RecyclerView to improve performance, from Google Search. Below is an example with your current code:
#Override
public View getView(int position, View view, ViewGroup parent) {
View holder = null;
if (view == null) {
holder = new ViewHolder();
LayoutInflater inflater = context.getLayoutInflater();
view = inflater.inflate(R.layout.list_single, parent, false);
holder.imageView = (ImageView) view.findViewById(R.id.img);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.imageView.setImageResource(imageId[position]);
return view;
}
static class ViewHolder { // should be static class
ImageView imageView;
}

Android custom Listadapter

I want to let the adapter check if the submitted value is a file
but when I check
it only checks the first value so
for eg.
I submit
app (directory)
meta (directory)
this shoul look like this :
app with the directory icon
meta with the directory icon
but the out put is only app as directory
The adapter:
package org.alexander.fuchs.compress;
import java.io.File;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class adapter extends ArrayAdapter<String> {
private final Activity context;
private final String[] names;
static class ViewHolder {
public TextView text;
public ImageView image;
}
public adapter(Activity context, String[] names) {
super(context, R.layout.rowlayout, names);
this.context = context;
this.names = names;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
if (rowView == null) {
LayoutInflater inflater = context.getLayoutInflater();
rowView = inflater.inflate(R.layout.rowlayout, null);
ViewHolder viewHolder = new ViewHolder();
viewHolder.text = (TextView) rowView.findViewById(R.id.label);
viewHolder.image = (ImageView) rowView
.findViewById(R.id.icon);
rowView.setTag(viewHolder);
}
ViewHolder holder = (ViewHolder) rowView.getTag();
String s = names[position];
holder.text.setText(s);
File entry = new File(s);
if(entry.isDirectory() == true)
{
holder.image.setImageResource(R.drawable.ok);
}
else
{
holder.image.setImageResource(R.drawable.no);
}
return rowView;
}
}

Categories