I am using a custom gridview adapter to show images with volley singleton. But when I run it it returns the onErrorResponse. It looks like the adapter is not even set properly, is it something with where i set the adapter? I have tried setting it in onCreate but same error.
The adapter class looked fine so I think the problem is in MainActivity.
MainActivity.java:
public class MainActivity extends AppCompatActivity {
private final int THUMBNAIL_SIZE = 250;
private final String KEY = "IMAGE";
ArrayList<Bitmap> bitmaps = new ArrayList<Bitmap>();
private static final String URLS[] = {
"http://10.0.2.2/Android%20A4_1/germany.png",
"http://10.0.2.2/Android%20A4_1/indonesia.png",
"http://10.0.2.2/Android%20A4_1/japan.png",
"http://10.0.2.2/Android%20A4_1/sarawak.png",
"http://10.0.2.2/Android%20A4_1/singapore.png",
"http://10.0.2.2/Android%20A4_1/switzerland.png",
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
for(int i = 0; i<URLS.length; i++) {
LoadingImages(URLS[i]);
}
}
private void LoadingImages(String url) {
ImageLoader imageLoader = MySingleton.getInstance(getApplicationContext()).getImageLoader();
imageLoader.get(url, new ImageLoader.ImageListener() {
#Override
public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) {
Bitmap image = response.getBitmap();
Bitmap thumbnail = ThumbnailUtils.extractThumbnail(image, THUMBNAIL_SIZE, THUMBNAIL_SIZE);
bitmaps.add(thumbnail);
GridView gridView = (GridView)findViewById(R.id.grid_layout);
final ImageAdapter imageAdapter = new ImageAdapter(MainActivity.this, bitmaps);
gridView.setAdapter(imageAdapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(getApplicationContext(), Main2Activity.class);
intent.putExtra(KEY, URLS[i]);
startActivity(intent);
}
});
}
#Override
public void onErrorResponse(VolleyError error) {
Log.e("error", error.getMessage());
}
});
}
}
The Adapter class:
public class ImageAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<Bitmap> bitmaps;
public ImageAdapter(Context context, ArrayList<Bitmap> bitmaps) {
this.mContext = context;
this.bitmaps = bitmaps;
}
#Override
public int getCount() {
return 0;
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
if (view == null) {
final LayoutInflater layoutInflater = LayoutInflater.from(mContext);
view = layoutInflater.inflate(R.layout.griditems, null);
MyViewHolder myViewHolder = new MyViewHolder(view);
view.setTag(myViewHolder);
}
MyViewHolder myViewHolder = (MyViewHolder)view.getTag();
myViewHolder.img.setImageBitmap(bitmaps.get(i));
return view;
}
public class MyViewHolder {
public ImageView img;
public MyViewHolder(View view) {
img = view.findViewById(R.id.image1);
}
}
}
My Singleton:
public class MySingleton {
private static MySingleton instance;
private RequestQueue requestQueue;
private ImageLoader imageLoader;
private static Context context;
private MySingleton(Context context){
this.context = context;
requestQueue = Volley.newRequestQueue(context);
imageLoader = new ImageLoader(requestQueue, new ImageLoader.ImageCache() {
private final LruCache<String, Bitmap> cache = new LruCache<>(6);
#Override
public Bitmap getBitmap(String url) {
Bitmap bmp = cache.get(url);
if (bmp == null) {
System.out.println("Not in cache");
} else {
System.out.println("In cache");
}
return bmp;
}
#Override
public void putBitmap(String url, Bitmap bitmap) {
System.out.println("Put in cache");
cache.put(url, bitmap);
}
});
}
public static synchronized MySingleton getInstance(Context context) {
if (instance == null) {
instance = new MySingleton(context);
}
return instance;
}
public ImageLoader getImageLoader() {
return imageLoader;
}
}
Main2Activity:
public class Main2Activity extends AppCompatActivity {
private ImageView imageView;
private final String KEY = "IMAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
imageView = (ImageView)findViewById(R.id.imageView);
Bundle bundle = getIntent().getExtras();
String url = bundle.getString(KEY);
LoadingImages(url);
}
private void LoadingImages(String url) {
final ImageLoader imageLoader = MySingleton.getInstance(getApplicationContext()).getImageLoader();
imageLoader.get(url, new ImageLoader.ImageListener() {
#Override
public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) {
Bitmap bitmap = response.getBitmap();
imageView.setImageBitmap(bitmap);
}
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Error", error.getMessage());
}
});
}
}
change This methods
#Override
public int getCount() {
return 0;
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
To
#Override
public int getCount() {
return bitmaps.size;
}
#Override
public Object getItem(int i) {
return bitmaps.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
Related
I've a image slider made with the help of ViewPager. I want to show different toast messages when clicked in different images loaded by ViewPager, how can i do that?
this my activity where image slider is shown:
public class MainActivity extends AppCompatActivity{
public static final String MAIN = "OTHER";
private static ViewPager mPager;
private static int currentPage = 0;
private static final Integer[] XMEN=
{R.drawable.benz2, R.drawable.benz2,
R.drawable.benz2};
private ArrayList<Integer> XMENArray = new ArrayList<Integer>();
#Override
protected void onCreate(...);
init();
}
private void init() {
for(int i=0;i<XMEN.length;i++)
XMENArray.add(XMEN[i]);
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(new com.example.nepali_test.MyAdapter(MainActivity.this,XMENArray));
CircleIndicator indicator = (CircleIndicator) findViewById(R.id.indicator);
indicator.setViewPager(mPager);
final Handler handler = new Handler();
final Runnable Update = new Runnable() {
public void run() {
if (currentPage == XMEN.length) {
currentPage = 0;
}
mPager.setCurrentItem(currentPage++, true);
}
};
Timer swipeTimer = new Timer();
swipeTimer.schedule(new TimerTask() {
#Override
public void run() {
handler.post(Update);
}
}, 3000, 3000);
}
and this is the adapter of the viewpager:
public class MyAdapter extends PagerAdapter {
private ArrayList<Integer> images;
private LayoutInflater inflater;
private Context context;
public MyAdapter(Context context, ArrayList<Integer> images) {
this.context = context;
this.images=images;
inflater = LayoutInflater.from(context);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public int getCount() {
return images.size();
}
#Override
public Object instantiateItem(ViewGroup view, int position) {
View myImageLayout = inflater.inflate(R.layout.slide, view, false);
ImageView myImage = (ImageView) myImageLayout
.findViewById(R.id.image);
myImage.setImageResource(images.get(position));
view.addView(myImageLayout, 0);
return myImageLayout;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
}
I tried to make by adding
if (currentPage==1){
Toast.makeText(this, "page 1", Toast.LENGTH_SHORT).show();
}
in init() but it didn't work.
From what i could understand you need to display the toast when clicking on the image in each page of a ViewPager in which case an easy way is to add an onClickListener to your ImageView inside your adapter's instantiateItem method. So you should change/replace your method with this:
#NonNull
#Override
public Object instantiateItem(#NonNull final ViewGroup view, final int position) {
View myImageLayout = inflater.inflate(R.layout.slide, view, false);
ImageView myImage = (ImageView) myImageLayout
.findViewById(R.id.image);
myImage.setImageResource(images.get(position));
myImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context.getApplicationContext(), "page "+position, Toast.LENGTH_SHORT).show();
}
});
view.addView(myImageLayout, 0);
return myImageLayout;
}
Try this:
#Override
public Object instantiateItem(View collection, final int pos) { //have to make final so we can see it inside of onClick()
LayoutInflater inflater = (LayoutInflater) collection.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View page = inflater.inflate(R.layout.YOUR_PAGE, null);
page.setOnClickListener(new OnClickListener(){
public void onClick(View v){
//this will log the page number that was click
Log.i("TAG", "This page was clicked: " + pos);
}
});
((ViewPager) collection).addView(page, 0);
return page;
}
Hope this will work!
Make Image click interface in adapter class
public class MyAdapter extends PagerAdapter {
private ArrayList<Integer> images;
private LayoutInflater inflater;
private Context context;
MyClassImage myClassImage;
public interface MyClassImage{
void imageClick(String id);
}
public ViewPagerAdapter(Context context, ArrayList<Integer> images,MyClassImage myClassImage) {
this.context = context;
this.images=images;
this.myClassImage=myClassImage;
inflater = LayoutInflater.from(context);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public int getCount() {
return images.size();
}
#Override
public Object instantiateItem(ViewGroup view, int position) {
View myImageLayout = inflater.inflate(R.layout.z_slide_pager_item, view, false);
ImageView myImage = (ImageView) myImageLayout.findViewById(R.id.image);
myImage.setImageResource(images.get(position));
view.addView(myImageLayout, 0);
final int id=images.get(position);
final String imgId=String.valueOf(id);
myImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myClassImage.imageClick(imgId);
}
});
return myImageLayout;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
}
and implement it on your MainActivity class
public class MainActivity extends AppCompatActivity implements MyAdapter.MyClassImage {
public static final String MAIN = "OTHER";
private static ViewPager mPager;
private static int currentPage = 0;
private static final Integer[] XMEN= {R.drawable.benz2, R.drawable.benz2, R.drawable.benz2};
private ArrayList<Integer> XMENArray = new ArrayList<Integer>();
#Override
protected void onCreate(...);
init();
}
private void init() {
for(int i=0;i<XMEN.length;i++)
XMENArray.add(XMEN[i]);
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(new com.example.nepali_test.MyAdapter(MainActivity.this,XMENArray,this));
CircleIndicator indicator = (CircleIndicator) findViewById(R.id.indicator);
indicator.setViewPager(mPager);
final Handler handler = new Handler();
final Runnable Update = new Runnable() {
public void run() {
if (currentPage == XMEN.length) {
currentPage = 0;
}
mPager.setCurrentItem(currentPage++, true);
}
};
Timer swipeTimer = new Timer();
swipeTimer.schedule(new TimerTask() {
#Override
public void run() {
handler.post(Update);
}
}, 3000, 3000);
}
#Override
public void imageClick(String id) {
Toast.makeText(this, "page "+id, Toast.LENGTH_SHORT).show();
}
Hope it will be helpful to you.
Thanks.
I was just playing around with some code, learning new things, when I ran into this problem... I'm trying to pass a variable from my RecylcerViewAdapter to a method in MainActivity, but I just can't seem to accomplish it.
I tried a lot of different thing with interfaces and casting, but nothing did the trick. Since I'm fairly new to all of this, maybe I'm making a trivial mistake somewhere?
My Interface:
public interface AdapterCallback {
void onMethodCallback(int id);
}
This is my adapter class:
public class PostAdapter extends RecyclerView.Adapter<PostAdapter.ViewHolder> {
private List<Post> postList;
private Context context;
private AdapterCallback listener;
public PostAdapter() {
}
public PostAdapter(List<Post> postList, Context context) {
this.postList = postList;
this.context = context;
}
public void setListener(AdapterCallback listener) {
this.listener = listener;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.recycler_layout, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder viewHolder, final int position) {
viewHolder.tvTitle.setText(postList.get(position).getTitle());
viewHolder.tvBody.setText(new StringBuilder(postList.get(position).getBody().substring(0, 20)).append("..."));
viewHolder.tvId.setText(String.valueOf(postList.get(position).getUserId()));
viewHolder.parentLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int id = postList.get(position).getId();
if (listener != null) {
listener.onMethodCallback(id);
}
}
});
}
#Override
public int getItemCount() {
return postList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView tvTitle;
TextView tvBody;
TextView tvId;
LinearLayout parentLayout;
public ViewHolder(View itemView) {
super(itemView);
tvTitle = itemView.findViewById(R.id.tvTitle);
tvBody = itemView.findViewById(R.id.tvBody);
tvId = itemView.findViewById(R.id.tvId);
parentLayout = itemView.findViewById(R.id.parentLayout);
}
}
}
And my MainActivity:
public class MainActivity extends AppCompatActivity {
public static final String TAG = "MainActivityLog";
private CompositeDisposable disposable = new CompositeDisposable();
#BindView(R.id.rvPosts)
RecyclerView rvPosts;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
rvPosts.setHasFixedSize(true);
rvPosts.setLayoutManager(new LinearLayoutManager(this));
populateList();
logItems();
}
private void populateList() {
MainViewModel viewModel = ViewModelProviders.of(MainActivity.this).get(MainViewModel.class);
viewModel.makeQuery().observe(MainActivity.this, new Observer<List<Post>>() {
#Override
public void onChanged(#Nullable List<Post> posts) {
PostAdapter adapter = new PostAdapter(posts, getApplicationContext());
rvPosts.setAdapter(adapter);
}
});
}
public void logItems() {
PostAdapter adapter = new PostAdapter();
adapter.setListener(new AdapterCallback() {
#Override
public void onMethodCallback(int id) {
MainViewModel viewModel = ViewModelProviders.of(MainActivity.this).get(MainViewModel.class);
viewModel.makeSingleQuery(id).observe(MainActivity.this, new Observer<Post>() {
#Override
public void onChanged(#Nullable final Post post) {
Log.d(TAG, "onChanged: data response");
Log.d(TAG, "onChanged: " + post);
}
});
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
disposable.clear();
}
}
The populateList() method works just fine, but the logItems() method is the problem.
So when i click on a view in RecyclerView I expect the log to output the title, description and ID of the post that was clicked. nut nothing happens...
So, any help would be appreciated.
Make adapter global variable i.e. a field. Use the same object to set every properties.
private PostAdapter adapter;
Replace your logItems method with this:
public void logItems() {
adapter.setListener(new AdapterCallback() {
#Override
public void onMethodCallback(int id) {
MainViewModel viewModel = ViewModelProviders.of(MainActivity.this).get(MainViewModel.class);
viewModel.makeSingleQuery(id).observe(MainActivity.this, new Observer<Post>() {
#Override
public void onChanged(#Nullable final Post post) {
Log.d(TAG, "onChanged: data response");
Log.d(TAG, "onChanged: " + post);
}
});
}
});
}
And populateList with this:
private void populateList() {
MainViewModel viewModel = ViewModelProviders.of(MainActivity.this).get(MainViewModel.class);
viewModel.makeQuery().observe(MainActivity.this, new Observer<List<Post>>() {
#Override
public void onChanged(#Nullable List<Post> posts) {
adapter = new PostAdapter(posts, getApplicationContext());
rvPosts.setAdapter(adapter);
logItems();
}
});
}
And don't call logItems() from onCreate
This is how I implement with my ListAdapters:
public class FeedbackListAdapter extends RecyclerView.Adapter<FeedbackListAdapter.ViewHolder> {
private final ArrayList<Feedback> feedbacks;
private View.OnClickListener onItemClickListener;
private View.OnLongClickListener onItemLongClickListener;
private final Context context;
public FeedbackListAdapter(ArrayList<Feedback> feedbacks, Context context) {
this.feedbacks = feedbacks;
this.context = context;
}
public void setItemClickListener(View.OnClickListener onItemClickListener) {
this.onItemClickListener = onItemClickListener;
}
public void setOnItemLongClickListener(View.OnLongClickListener onItemLongClickListener){
this.onItemLongClickListener = onItemLongClickListener;
}
public class ViewHolder extends RecyclerView.ViewHolder{
final TextView feedback, created, updated;
final LinearLayout mainLayout;
ViewHolder(View iv) {
super(iv);
/*
* Associate layout elements to Java declarations
* */
mainLayout = iv.findViewById(R.id.main_layout);
feedback = iv.findViewById(R.id.feedback);
created = iv.findViewById(R.id.created_string);
updated = iv.findViewById(R.id.updated_string);
}
}
#Override
public int getItemCount() {
return feedbacks.size();
}
#Override
#NonNull
public FeedbackListAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.fragment_feedback_table_row, parent, false);
return new FeedbackListAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(final #NonNull FeedbackListAdapter.ViewHolder holder, final int position) {
/*
* Bind data to layout
* */
try{
Feedback feedback = feedbacks.get(position);
holder.feedback.setText(feedback.getContent());
holder.created.setText(feedback.getCreated());
holder.updated.setText(feedback.getUpdated());
holder.mainLayout.setOnClickListener(this.onItemClickListener);
holder.mainLayout.setOnLongClickListener(this.onItemLongClickListener);
holder.mainLayout.setTag(feedback.getDbID());
TypedValue outValue = new TypedValue();
context.getTheme().resolveAttribute(android.R.attr.selectableItemBackground, outValue, true);
holder.mainLayout.setBackgroundResource(outValue.resourceId);
}catch(IndexOutOfBoundsException e){
e.printStackTrace();
}
}
}
In onPopulateList you create an adaptor:
PostAdapter adapter = new PostAdapter(posts, getApplicationContext());
rvPosts.setAdapter(adapter);
However in public void logItems() { you used a different adapter
PostAdapter adapter = new PostAdapter();
adapter.setListener(new AdapterCallback() {
#Override
public void onMethodCallback(int id) {
...
}
});
Therefore the list is being populated with 1 adapter, but you are setting the listener on an unused second adapter.
The fix is to use the same adapter for both. If you make the adapater a field, and don't create a new one inside of logItems, but just set your listener it should work.
i.e.
// as a field in your class
private PostAdapter adapter;
then
// in `populateList()`
adapter = new PostAdapter(posts, getApplicationContext());
rvPosts.setAdapter(adapter);
and
// in `logItems()`
adapter.setListener(new AdapterCallback() {
#Override
public void onMethodCallback(int id) {
...
}
});
In Adapter
public class CustomerListAdapter extends RecyclerView.Adapter<CustomerListAdapter.OrderItemViewHolder> {
private Context mCtx;
ProgressDialog progressDialog;
//we are storing all the products in a list
private List<CustomerModel> customeritemList;
public CustomerListAdapter(Context mCtx, List<CustomerModel> orderitemList) {
this.mCtx = mCtx;
this.customeritemList = orderitemList;
progressDialog = new ProgressDialog(mCtx);
}
#NonNull
#Override
public OrderItemViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(mCtx);
View view = inflater.inflate(R.layout.activity_customer_list, null);
return new OrderItemViewHolder(view, mCtx, customeritemList);
}
#Override
public void onBindViewHolder(#NonNull OrderItemViewHolder holder, int position) {
CustomerModel customer = customeritemList.get(position);
try {
//holder.textViewPINo.setText("PINo \n"+Integer.toString( order.getPINo()));
holder.c_name.setText(customer.getCustomerName());
holder.c_address.setText(customer.getAddress());
holder.c_contact.setText(customer.getMobile());
holder.i_name.setText(customer.getInteriorName());
holder.i_contact.setText(customer.getInteriorMobile());
holder.i_address.setText(customer.getAddress());
} catch (Exception E) {
E.printStackTrace();
}
}
#Override
public int getItemCount() {
return customeritemList.size();
}
class OrderItemViewHolder extends RecyclerView.ViewHolder implements View.OnLongClickListener, View.OnClickListener {
AlertDialog.Builder alert;
private Context mCtx;
TextView c_name, c_contact, c_address, i_name, i_contact, i_address;
TextView OrderItemID, MaterialType, Price2, Qty, AQty;
//we are storing all the products in a list
private List<CustomerModel> orderitemList;
public OrderItemViewHolder(View itemView, Context mCtx, List<CustomerModel> orderitemList) {
super(itemView);
this.mCtx = mCtx;
this.orderitemList = orderitemList;
itemView.setOnClickListener(this);
itemView.setOnLongClickListener(this);
// CatelogOrderDetailModel catelogOrderDetailModel = new CatelogOrderDetailModel();
c_name = itemView.findViewById(R.id.customerName);
c_contact = itemView.findViewById(R.id.contact);
c_address = itemView.findViewById(R.id.address);
i_name = itemView.findViewById(R.id.interiorName);
i_address = itemView.findViewById(R.id.interiorAddress);
i_contact = itemView.findViewById(R.id.interiorContact);
}
#Override
public void onClick(View v) {
int position = getAdapterPosition();
CustomerModel orderitem = this.orderitemList.get(position);
}
#Override
public boolean onLongClick(View v) {
int position = getAdapterPosition();
CustomerModel orderitem = this.orderitemList.get(position);
if (v.getId() == itemView.getId()) {
// showUpdateDeleteDialog(order);
try {
} catch (Exception E) {
E.printStackTrace();
}
Toast.makeText(mCtx, "lc: ", Toast.LENGTH_SHORT).show();
}
return true;
}
}
}
I am using a custom gridview adapter to show images with volley singleton. The gridview showing the images are fine, its just that when I click the FIRST image it crashes instantly.
I have tried using URLS[i-6] but it doesnt return the right thing. There are 6 images, somehow the index of the first image is 6 thus causing the out of bound exception. I tried changing bits here and there that might cause the index starting at 6 but no result at all..
The error:
java.lang.ArrayIndexOutOfBoundsException: length=6; index=6
at com.example.user.assignmentfourtwo.MainActivity$1$1.onItemClick(MainActivity.java:80)
Which is this line:
Toast.makeText(MainActivity.this, URLS[i].toString(), Toast.LENGTH_LONG).show();
MainActivity.java:
public class MainActivity extends AppCompatActivity {
private final int THUMBNAIL_SIZE = 250;
private final String KEY = "IMAGE";
ArrayList<Bitmap> bitmaps = new ArrayList<Bitmap>();
private static final String URLS[] = {
"http://10.0.2.2/Android%20A4_1/germany.png",
"http://10.0.2.2/Android%20A4_1/indonesia.png",
"http://10.0.2.2/Android%20A4_1/japan.png",
"http://10.0.2.2/Android%20A4_1/sarawak.png",
"http://10.0.2.2/Android%20A4_1/singapore.png",
"http://10.0.2.2/Android%20A4_1/switzerland.png",
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
for(int i = 0; i<URLS.length; i++) {
LoadingImages(URLS[i]);
}
}
private void LoadingImages(String url) {
ImageLoader imageLoader = MySingleton.getInstance(getApplicationContext()).getImageLoader();
imageLoader.get(url, new ImageLoader.ImageListener() {
#Override
public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) {
Bitmap image = response.getBitmap();
Bitmap thumbnail = ThumbnailUtils.extractThumbnail(image, THUMBNAIL_SIZE, THUMBNAIL_SIZE);
bitmaps.add(thumbnail);
GridView gridView = (GridView)findViewById(R.id.grid_layout);
final ImageAdapter imageAdapter = new ImageAdapter(MainActivity.this, bitmaps);
gridView.setAdapter(imageAdapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(MainActivity.this, URLS[i].toString(), Toast.LENGTH_LONG).show();
// Intent intent = new Intent(getApplicationContext(), Main2Activity.class);
// intent.putExtra(KEY, URLS[i]);
// startActivity(intent);
}
});
}
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Do you even error?", error.getMessage());
}
});
}
}
MySingleton.java:
public class MySingleton {
private static MySingleton instance;
private RequestQueue requestQueue;
private ImageLoader imageLoader;
private static Context context;
private MySingleton(Context context){
this.context = context;
requestQueue = Volley.newRequestQueue(context);
imageLoader = new ImageLoader(requestQueue, new ImageLoader.ImageCache() {
private final LruCache<String, Bitmap> cache = new LruCache<>(6);
#Override
public Bitmap getBitmap(String url) {
Bitmap bmp = cache.get(url);
if (bmp == null) {
System.out.println("Not in cache");
} else {
System.out.println("In cache");
}
return bmp;
}
#Override
public void putBitmap(String url, Bitmap bitmap) {
System.out.println("Put in cache");
cache.put(url, bitmap);
}
});
}
public static synchronized MySingleton getInstance(Context context) {
if (instance == null) {
instance = new MySingleton(context);
}
return instance;
}
public ImageLoader getImageLoader() {
return imageLoader;
}
}
ImageAdapter.java:
public class ImageAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<Bitmap> bitmaps;
private final String KEY = "IMAGE";
public ImageAdapter(Context context, ArrayList<Bitmap> bitmaps) {
this.mContext = context;
this.bitmaps = bitmaps;
}
#Override
public int getCount() {
return bitmaps.size();
}
#Override
public Object getItem(int i) {
return bitmaps.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
if (view == null) {
final LayoutInflater layoutInflater = LayoutInflater.from(mContext);
view = layoutInflater.inflate(R.layout.griditems, null);
MyViewHolder myViewHolder = new MyViewHolder(view);
view.setTag(myViewHolder);
}
MyViewHolder myViewHolder = (MyViewHolder)view.getTag();
myViewHolder.img.setImageBitmap(bitmaps.get(i));
return view;
}
public class MyViewHolder {
public ImageView img;
public MyViewHolder(View view) {
img = view.findViewById(R.id.image1);
}
}
}
I am follow this link tutorial [https://developer.qualcomm.com/software/snapdragon-neural-processing-engine-ai/getting-started and i am able to download all model image but my requirement is now i need how to display gallery image in grid view my code is for model overview fragment:
public class ModelOverviewFragment extends Fragment {
public static final String EXTRA_MODEL = "model";
enum MenuRuntimeGroup {
SelectCpuRuntime(NeuralNetwork.Runtime.CPU),
SelectGpuRuntime(NeuralNetwork.Runtime.GPU),
SelectDspRuntime(NeuralNetwork.Runtime.DSP);
public static int ID = 1;
public NeuralNetwork.Runtime runtime;
MenuRuntimeGroup(NeuralNetwork.Runtime runtime) {
this.runtime = runtime;
}
}
private GridView mImageGrid;
private ModelImagesAdapter mImageGridAdapter;
private ModelOverviewFragmentController mController;
private TextView mDimensionsText;
private TextView mModelNameText;
private Spinner mOutputLayersSpinners;
private TextView mClassificationText;
private TextView mModelVersionText;
public static ModelOverviewFragment create(final Model model) {
final ModelOverviewFragment fragment = new ModelOverviewFragment();
final Bundle arguments = new Bundle();
arguments.putParcelable(EXTRA_MODEL, model);
fragment.setArguments(arguments);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_model, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mImageGrid = (GridView) view.findViewById(R.id.model_image_grid);
mImageGridAdapter = new ModelImagesAdapter(getActivity());
mImageGrid.setAdapter(mImageGridAdapter);
mImageGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final Bitmap bitmap = mImageGridAdapter.getItem(position);
mController.classify(bitmap);
}
});
mModelNameText = (TextView) view.findViewById(R.id.model_overview_name_text);
mModelVersionText = (TextView) view.findViewById(R.id.model_overview_version_text);
mDimensionsText = (TextView) view.findViewById(R.id.model_overview_dimensions_text);
mOutputLayersSpinners = (Spinner) view.findViewById(R.id.model_overview_layers_spinner);
mClassificationText = (TextView) view.findViewById(R.id.model_overview_classification_text);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
final Model model = getArguments().getParcelable(EXTRA_MODEL);
mController = new ModelOverviewFragmentController(
(Application) getActivity().getApplicationContext(), model);
}
#Override
public void onCreateOptionsMenu(android.view.Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
final SNPE.NeuralNetworkBuilder builder = new SNPE.NeuralNetworkBuilder(
(Application) (getActivity().getApplicationContext()));
for (MenuRuntimeGroup item : MenuRuntimeGroup.values()) {
if (builder.isRuntimeSupported(item.runtime)) {
menu.add(MenuRuntimeGroup.ID, item.ordinal(), 0, item.runtime.name());
}
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getGroupId() == MenuRuntimeGroup.ID) {
final MenuRuntimeGroup option = MenuRuntimeGroup.values()[item.getItemId()];
mController.setTargetRuntime(option.runtime);
}
return super.onOptionsItemSelected(item);
}
#Override
public void onStart() {
super.onStart();
mController.attach(this);
}
#Override
public void onStop() {
mController.detach(this);
super.onStop();
}
public void addSampleBitmap(Bitmap bitmap) {
if (mImageGridAdapter.getPosition(bitmap) == -1) {
mImageGridAdapter.add(bitmap);
mImageGridAdapter.notifyDataSetChanged();
}
}
public void setNetworkDimensions(Map<String, int[]> inputDimensions) {
mDimensionsText.setText(Arrays.toString(inputDimensions.get("data")));
}
public void displayModelLoadFailed() {
mClassificationText.setVisibility(View.VISIBLE);
mClassificationText.setText(R.string.model_load_failed);
Toast.makeText(getActivity(), R.string.model_load_failed, Toast.LENGTH_SHORT).show();
}
public void setModelName(String modelName) {
mModelNameText.setText(modelName);
}
public void setModelVersion(String version) {
mModelVersionText.setText(version);
}
public void setOutputLayersNames(Set<String> outputLayersNames) {
mOutputLayersSpinners.setAdapter(new ArrayAdapter<>(
getActivity(), android.R.layout.simple_list_item_1,
new LinkedList<>(outputLayersNames)));
}
public void setClassificationResult(String[] classificationResult) {
if (classificationResult.length > 0) {
mClassificationText.setText(
String.format("%s: %s", classificationResult[0], classificationResult[1]));
}
mClassificationText.setVisibility(View.VISIBLE);
}
public void setLoadingVisible(boolean visible) {
mClassificationText.setVisibility(visible ? View.VISIBLE : View.GONE);
if (visible) {
mClassificationText.setText(R.string.loading_network);
}
}
public void displayModelNotLoaded() {
Toast.makeText(getActivity(), R.string.model_not_loaded, Toast.LENGTH_SHORT).show();
}
public void displayClassificationFailed() {
Toast.makeText(getActivity(), R.string.classification_failed, Toast.LENGTH_SHORT).show();
}
private static class ModelImagesAdapter extends ArrayAdapter<Bitmap> {
public ModelImagesAdapter(Context context) {
super(context, R.layout.model_image_layout);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
if (convertView == null) {
view = LayoutInflater.from(parent.getContext()).
inflate(R.layout.model_image_layout, parent, false);
} else {
view = convertView;
}
final ImageView imageView = ImageView.class.cast(view);
imageView.setImageBitmap(getItem(position));
return view;
}
}
}
for image loading code :
public class LoadImageTask extends AsyncTask<File, Void, Bitmap> {
private final ModelOverviewFragmentController mController;
private final File mImageFile;
public LoadImageTask(ModelOverviewFragmentController controller, final File imageFile) {
mController = controller;
mImageFile = imageFile;
}
#Override
protected Bitmap doInBackground(File... params) {
return BitmapFactory.decodeFile(mImageFile.getAbsolutePath());
}
#Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
mController.onBitmapLoaded(mImageFile, bitmap);
}
}
/*public class LoadImageTask extends AsyncTask{
private final ModelOverviewFragmentController mController;
private File path;
public LoadImageTask(ModelOverviewFragmentController controller, File jpeg)
{
mController=controller;
path=jpeg;
}
#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());
Log.d("ImagePath",bitmap.toString());
}
return bitmap;
}
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
mController.onBitmapLoaded(path,result);
}
}
for model :
public class Model implements Parcelable {
public static final Uri MODELS_URI = Uri.parse("content://snpe/models");
// public static final Uri MODELS_URI=Uri.parse("content://mtp://[usb:002,029]/Internal%20shared%20storage/DCIM");
public static final String INVALID_ID = "null";
public File file;
public String[] labels;
public File[] rawImages;
public File[] jpgImages;
public String name;
public File meanImage;
protected Model(Parcel in) {
name = in.readString();
file = new File(in.readString());
final String[] rawPaths = new String[in.readInt()];
in.readStringArray(rawPaths);
rawImages = fromPaths(rawPaths);
final String[] jpgPaths = new String[in.readInt()];
in.readStringArray(jpgPaths);
jpgImages = fromPaths(jpgPaths);
meanImage = new File(in.readString());
labels = new String[in.readInt()];
in.readStringArray(labels);
}
public Model() {}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeString(file.getAbsolutePath());
dest.writeInt(rawImages.length);
dest.writeStringArray(toPaths(rawImages));
dest.writeInt(jpgImages.length);
dest.writeStringArray(toPaths(jpgImages));
dest.writeString(meanImage.getAbsolutePath());
dest.writeInt(labels.length);
dest.writeStringArray(labels);
}
private File[] fromPaths(String[] paths) {
final File[] files = new File[paths.length];
for (int i = 0; i < paths.length; i++) {
files[i] = new File(paths[i]);
}
return files;
}
private String[] toPaths(File[] files) {
final String[] paths = new String[files.length];
for (int i = 0; i < files.length; i++) {
paths[i] = files[i].getAbsolutePath();
}
return paths;
}
#Override
public int describeContents() {
return 0;
}
public static final Creator<Model> CREATOR = new Creator<Model>() {
#Override
public Model createFromParcel(Parcel in) {
return new Model(in);
}
#Override
public Model[] newArray(int size) {
return new Model[size];
}
};
#Override
public String toString() {
return name.toUpperCase();
}
}
To load SD card images in grid view, please make few changes in loadImageSamples method of ModelOverviewFragmentController.java. Currently, the images are picked from snpe folder inside internal storage of the device and are populated on Grid View. To get all the images from the gallery, create AsyncTask class to load images from the Gallery to the Grid View with the help of Content Provider.
Please use this link https://stackoverflow.com/a/10877404 for code reference to load images on grid view.
Hope this helps!
Thank You
I'm creating a Movie Catalog app using themoviedb API. How can I implement search using EditText?
I have a list view that contains the movie info.
App screenshot:
Now I want to use the EditText to find another movie, and the list view updated. How do I do that?
My loader:
public class MyAsyncTaskLoader extends AsyncTaskLoader<ArrayList<MovieItem>> {
public ArrayList<MovieItem> mData;
public boolean hasResult = false;
public MyAsyncTaskLoader(final Context context) {
super(context);
onContentChanged();
Log.d("INIT ASYNCLOADER","1");
}
#Override
protected void onStartLoading() {
Log.d("Content Changed","1");
if (takeContentChanged())
forceLoad();
else if (hasResult)
deliverResult(mData);
}
#Override
public void deliverResult(final ArrayList<MovieItem> data) {
mData = data;
hasResult = true;
super.deliverResult(data);
}
#Override
protected void onReset() {
super.onReset();
onStopLoading();
if (hasResult) {
onReleaseResources(mData);
mData = null;
hasResult = false;
}
}
public static String Search = "Avengers";
public static String API_KEY = "f00e74c69ff0512cf9e5bf128569f6b5";
#Override
public ArrayList<MovieItem> loadInBackground() {
Log.d("LOAD BG","1");
SyncHttpClient client = new SyncHttpClient();
final ArrayList<MovieItem> movieItemses = new ArrayList<>();
final String url = "https://api.themoviedb.org/3/search/movie?api_key="+API_KEY+"&language=en-US&query="+Search;
client.get(url, new AsyncHttpResponseHandler() {
#Override
public void onStart() {
super.onStart();
setUseSynchronousMode(true);
}
#Override
public void onSuccess(int statusCode, Header[] headers,
byte[] responseBody) {
try {
String result = new String(responseBody);
JSONObject responseObject = new JSONObject(result);
JSONArray list = responseObject.getJSONArray("results");
for (int i = 0 ; i < list.length() ; i++){
JSONObject movie = list.getJSONObject(i);
MovieItem movieItems = new MovieItem(movie);
movieItemses.add(movieItems);
}
Log.d("REQUEST SUCCESS","1");
}catch (Exception e){
e.printStackTrace();
Log.d("REQUEST FAILED","1");
}
}
#Override
public void onFailure(int statusCode, Header[] headers,
byte[] responseBody, Throwable error) {
}
});
for (int i = 0 ; i< movieItemses.size() ; i++){
Log.d("Title",movieItemses.get(i).getTitle());
}
Log.d("BEFORE RETURN","1");
return movieItemses;
}
protected void onReleaseResources(ArrayList<MovieItem> data) {
//nothing to do.
}
public ArrayList<MovieItem> getResult() {
return mData;
}
}
My adapter:
public class MovieAdapter extends BaseAdapter {
private ArrayList<MovieItem> mData = new ArrayList<>();
private LayoutInflater mInflater;
private Context context;
Activity activity;
private String urlConfig ;
public MovieAdapter(Context context) {
this.context = context;
mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void setData(ArrayList<MovieItem> items){
mData = items;
notifyDataSetChanged();
}
public void clearData(){
mData.clear();
}
#Override
public int getItemViewType(int position) {
return 0;
}
#Override
public int getViewTypeCount() {
return 1;
}
#Override
public int getCount() {
return mData.size();
}
#Override
public MovieItem getItem(int position) {
return mData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.item_row_film, null);
holder.textViewuJudul= (TextView)convertView.findViewById(R.id.tv_judul);
holder.textViewDescription = (TextView)convertView.findViewById(R.id.tv_deskripsi);
holder.textViewRate = (TextView)convertView.findViewById(R.id.tv_rate);
holder.imgPoster = (ImageView) convertView.findViewById(R.id.img_poster);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.textViewuJudul.setText(mData.get(position).getTitle());
holder.textViewDescription.setText(mData.get(position).getDescription());
holder.textViewRate .setText(mData.get(position).getRate());
Picasso.with(context).load(mData.get(position).getImgurl()).into(holder.imgPoster);
return convertView;
}
private class ViewHolder {
public TextView textViewuJudul;
public TextView textViewDescription;
public TextView textViewRate;
public ImageView imgPoster;
}}
The item:
public class MovieItem {
public static String POSTER_BASE_URL = "http://image.tmdb.org/t/p/";
private int id;
private String title;
private String description;
private String rate;
private String imgurl;
public MovieItem(JSONObject object){
try {
String title = object.getString("title");
String description = object.getString("overview");
double movieRatet = object.getDouble("vote_average");
String movieRate = new DecimalFormat("#.#").format(movieRatet);
String releaseDate = object.getString("release_date");
String posterUrl = object.getString("poster_path");
posterUrl = POSTER_BASE_URL + "w185" + posterUrl;
description = description.length() > 64 ? description.substring(0,64)+"...":description;
Log.d("movie poster", posterUrl);
Log.d("movie title ", title);
Log.d("movie description ", description);
Log.d("movie release ", releaseDate);
this.title = title;
this.description = description;
this.rate = releaseDate;
this.imgurl = posterUrl;
}catch (Exception e){
e.printStackTrace();
}
}
My MainActivity:
public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<ArrayList<MovieItem>>
,View.OnClickListener{
ListView listView;
MovieAdapter adapter;
MyAsyncTaskLoader myAsyncTaskLoader;
private TextView edt_cari;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edt_cari = (TextView) findViewById(R.id.edt_cari);
adapter = new MovieAdapter(this);
adapter.notifyDataSetChanged();
listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(adapter);
getLoaderManager().initLoader(0, null, this);
}
#Override
public Loader<ArrayList<MovieItem>> onCreateLoader(int id, Bundle args) {
Log.d("Create Loader", "1");
return new MyAsyncTaskLoader(this);
}
#Override
public void onLoadFinished(Loader<ArrayList<MovieItem>> loader, ArrayList<MovieItem> data) {
Log.d("Load Finish","1");
adapter.setData(data);
}
#Override
public void onLoaderReset(Loader<ArrayList<MovieItem>> loader) {
Log.d("Load Reset","1");
adapter.setData(null);
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.btn_cari){
SearchMovieTask searchMovie = new SearchMovieTask();
searchMovie.execute(edt_cari.getText().toString().trim());
}
}
private class SearchMovieTask extends AsyncTask<String,Void,String>{
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}}
Replace your MovieAdapter to this ...!
public class MovieAdapter extends BaseAdapter implements Filterable {
private ArrayList<MovieItem> mData = new ArrayList<>();
private ArrayList<MovieItem> mSearchData = new ArrayList<>();
private ArrayList<MovieItem> categoryListOne = new ArrayList<>();
private LayoutInflater mInflater;
private Context context;
Activity activity;
ItemFilter mFilter = new ItemFilter();
private String urlConfig;
public MovieAdapter(Context context) {
this.context = context;
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void setData(ArrayList<MovieItem> items) {
mData = items;
mSearchData = items;
notifyDataSetChanged();
}
public void clearData() {
mData.clear();
}
#Override
public int getItemViewType(int position) {
return 0;
}
#Override
public int getViewTypeCount() {
return 1;
}
#Override
public int getCount() {
return mData.size();
}
#Override
public MovieItem getItem(int position) {
return mData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.item_row_film, null);
holder.textViewuJudul = (TextView) convertView.findViewById(R.id.tv_judul);
holder.textViewDescription = (TextView) convertView.findViewById(R.id.tv_deskripsi);
holder.textViewRate = (TextView) convertView.findViewById(R.id.tv_rate);
holder.imgPoster = (ImageView) convertView.findViewById(R.id.img_poster);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.textViewuJudul.setText(mData.get(position).getTitle());
holder.textViewDescription.setText(mData.get(position).getDescription());
holder.textViewRate.setText(mData.get(position).getRate());
Picasso.with(context).load(mData.get(position).getImgurl()).into(holder.imgPoster);
return convertView;
}
#Override
public Filter getFilter() {
return mFilter;
}
public class ItemFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
constraint = constraint.toString().toLowerCase().replace(" ", "");
Log.v("DataAdapter", "constratinst : " + constraint);
FilterResults result = new FilterResults();
if (constraint.toString().length() > 0) {
ArrayList<Sticker> filteredItems =
new ArrayList<>();
for (int i = 0, l = mData.size(); i < l; i++) {
// ArrayList<HashMap<String, String>> p =
// originalList.get(i);
String p = mData.get(i).getName().toLowerCase().replace(" ", "");
if (p.toLowerCase().startsWith(String.valueOf(constraint)))
filteredItems.add(mData.get(i));
// if (p.toLowerCase().contains(constraint))
// filteredItems.add(categoryListSearch.get(i));
}
Log.v("DataAdapter", "not blank");
result.count = filteredItems.size();
result.values = filteredItems;
} else {
synchronized (this) {
result.count = categoryListOne.size();
result.values = categoryListOne;
// result.values = dataList;
// result.count = dataList.size();
}
}
return result;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
// users = (List<GraphUser>) results.values;
//filteredData = (ArrayList<String>) results.values;
mData = (ArrayList<MovieItem>) results.values;
notifyDataSetChanged();
// for (int i = 0, l = mData.size(); i < l; i++)
// mSearchData.get(i);
//add(productList.get(i));
notifyDataSetInvalidated();
}
}
private class ViewHolder {
public TextView textViewuJudul;
public TextView textViewDescription;
public TextView textViewRate;
public ImageView imgPoster;
}
}
And your activity set EditText Listener to this..!
editText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void afterTextChanged(Editable editable) {
adapter.getFilter().filter(charSequence.toString());
}
});
i hope it's helpful to you ..!
Implement addTextChangedListener() on your search EditText and as the text changes filter your list data and update MovieAdapter with filtered data.
check this post on how to update custom list adapter