I am using this code to show the cover of the songs in the listview:
package com.xrobotx.love.musicalbums;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
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.RelativeLayout;
import android.widget.TextView;
import com.bumptech.glide.Glide;
public class SongAdapter extends BaseAdapter {
private List<Song> songs;
private LayoutInflater songInf;
Context mContext;
public SongAdapter(Context c, List<Song> theSongs){
songs=theSongs;
songInf=LayoutInflater.from(c);
mContext = c;
}
#Override
public int getCount() {
return songs.size();
}
#Override
public Object getItem(int arg0) {
return songs.get(arg0);
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//map to song layout
RelativeLayout songLay = (RelativeLayout)songInf.inflate
(R.layout.song_layout, parent, false);
//get title and artist views
TextView songView = (TextView)songLay.findViewById(R.id.song_title);
TextView artistView = (TextView)songLay.findViewById(R.id.song_artist);
TextView durationView = (TextView)songLay.findViewById(R.id.song_duration);
ImageView coverView = (ImageView)songLay.findViewById(R.id.song_cover);
//get song using position
Song currSong = songs.get(position);
//get title and artist strings
songView.setText(currSong.getTitle());
artistView.setText(currSong.getArtist());
durationView.setText(String.format("%02d:%02d",
TimeUnit.MILLISECONDS.toMinutes((long) currSong.getDuration()),
TimeUnit.MILLISECONDS.toSeconds((long) currSong.getDuration()) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) currSong.getDuration()))));
if(currSong.getCover() != null){
Glide.with(mContext).load(currSong.getCover()).override(50, 50).into(coverView);
}
songLay.setTag(position);
return songLay;
}
}
Not all covers are displayed correctly. Some covers infact are black.
Why ?
EDIT:
This is the code to get the Cover:
private static String getCoverArtPath(long albumId, Context context) {
Cursor albumCursor = context.getContentResolver().query(
MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI,
new String[]{MediaStore.Audio.Albums.ALBUM_ART},
MediaStore.Audio.Albums._ID + " = ?",
new String[]{Long.toString(albumId)},
null
);
boolean queryResult = albumCursor.moveToFirst();
String result = null;
if (queryResult) {
result = albumCursor.getString(0);
}
albumCursor.close();
return result;
}
I ran into this. Glide network requests like any other request it fails sometimes
So the solution i found is to make another request on failure.
Glide.with(context)
.load((currSong.getCover())
.asBitmap()
.into(new SimpleTarget<Bitmap>(width, height) {
#Override
public void onResourceReady(Bitmap resource, GlideAnimation glideAnimation) {
//handle Bitmap
coverview.setBitmap(resource);
}
#Override
public void onLoadFailed(Exception e, Drawable errorDrawable) {
Glide.with(mContext).load(currSong.getCover()).override(50, 50).into(coverView);
}
});
Related
I saw a tutorial on youtube showing how you can add data to sqlLite db and then display these data to a ListView Video.
After doing that... I applied DragSortListView to my listview... but everytime I drag a row. This error keeps on coming and I couldn't solve it :
FATAL EXCEPTION: main
Process: com.example.justi.ricksonbar, PID: 29157
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.get(ArrayList.java:411)
at com.example.justi.ricksonbar.ProductAdapter.getItem(ProductAdapter.java:49)
at com.example.justi.ricksonbar.BackgroundTask$1.drop(BackgroundTask.java:91)
at com.mobeta.android.dslv.DragSortListView.dropFloatView(DragSortListView.java:1501)
at com.mobeta.android.dslv.DragSortListView.access$1200(DragSortListView.java:59)
at com.mobeta.android.dslv.DragSortListView$DropAnimator.onStop(DragSortListView.java:1293)
at com.mobeta.android.dslv.DragSortListView$SmoothAnimator.run(DragSortListView.java:1192)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Here's my ProductAdapter.java¨
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
import com.mobeta.android.dslv.DragSortController;
import com.mobeta.android.dslv.DragSortListView;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class ProductAdapter extends ArrayAdapter{
List list = new ArrayList();
public ProductAdapter(Context context,int resource) {
super(context, resource);
}
public void add(Product object) {
list.add(object);
super.add(object);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public View getView(int position, final View convertView, ViewGroup parent) {
View row = convertView;
final ProductHolder productHolder;
if(row == null){
LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.product_list, parent, false);
productHolder = new ProductHolder();
productHolder.tx_name = (TextView)row.findViewById(R.id.tvProd_name);
productHolder.tx_price = (TextView)row.findViewById(R.id.tvProd_price);
productHolder.tx_type = (TextView)row.findViewById(R.id.tvProd_type);
row.setTag(productHolder);
}else{
productHolder = (ProductHolder) row.getTag();
}
Product product = (Product) getItem(position);
productHolder.tx_name.setText(product.getName().toString());
productHolder.tx_price.setText(Double.toString(product.getPrice()));
productHolder.tx_type.setText(product.getType().toString());
return row;
}
static class ProductHolder{
TextView tx_name, tx_price, tx_type;
}
}
and my BackgroundTask.java (where I put DragSortListView methods)
import android.app.Activity;
import android.app.VoiceInteractor;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.mobeta.android.dslv.DragSortController;
import com.mobeta.android.dslv.DragSortListView;
public class BackgroundTask extends AsyncTask<String, Product, String> {
Context ctx;
ProductAdapter productAdapter;
Activity activity;
DragSortListView listView;
BackgroundTask(Context ctx){
this.ctx = ctx;
activity = (Activity)ctx;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
String method = params[0];
DatabaseHelper dHelper = new DatabaseHelper(ctx);
if (method.equals("add_info")){
String name = params[1];
double price = Double.parseDouble(params[2]);
String type = params[3];
SQLiteDatabase db = dHelper.getWritableDatabase();
//Call method of insertion
dHelper.addInformations(db, name, price, type);
return "One row is inserted....";
}else if (method.equals("get_info")){
listView = (DragSortListView)activity.findViewById(R.id.display_listview);
SQLiteDatabase db = dHelper.getReadableDatabase();
Cursor cursor = dHelper.getInformations(db);
productAdapter = new ProductAdapter(ctx,R.layout.product_list);
String name, type;
double price;
while (cursor.moveToNext()){
name = cursor.getString(cursor.getColumnIndex(ProductContract.ProductEntry.NAME));
price = cursor.getDouble(cursor.getColumnIndex(ProductContract.ProductEntry.PRICE));
type = cursor.getString(cursor.getColumnIndex(ProductContract.ProductEntry.TYPE));
Product product = new Product(name, price, type);
publishProgress(product);
}
return "get_info";
}
return null;
}
#Override
protected void onProgressUpdate(Product... values) {
productAdapter.add(values[0]);
}
private DragSortListView.DropListener onDrop = new DragSortListView.DropListener()
{
#Override
public void drop(int from, int to)
{
productAdapter = new ProductAdapter(ctx,R.layout.product_list);
if (from != to)
{
Object item = productAdapter.getItem(from);
productAdapter.remove(item);
productAdapter.insert(item, to);
}
}
};
private DragSortListView.RemoveListener onRemove = new DragSortListView.RemoveListener()
{
#Override
public void remove(int which)
{
productAdapter = new ProductAdapter(ctx,R.layout.product_list);
productAdapter.remove(productAdapter.getItem(which));
}
};
#Override
protected void onPostExecute(String result) {
if (result.equals("get_info")){
listView.setAdapter(productAdapter);
listView.setDropListener(onDrop);
listView.setRemoveListener(onRemove);
DragSortController controller = new DragSortController(listView);
controller.setRemoveEnabled(false);
controller.setSortEnabled(true);
controller.setDragInitMode(1);
listView.setFloatViewManager(controller);
listView.setOnTouchListener(controller);
listView.setDragEnabled(true);
}else{
Toast.makeText(ctx, result, Toast.LENGTH_LONG).show();
}
}
}
Please help me. Thank you so much
You are trying to fetch item before adding any element in a adapter.
#Override
public void drop(int from, int to)
{ // Adapter is Created here
productAdapter = new ProductAdapter(ctx,R.layout.product_list);
if (from != to)
{
// here you are trying to get item which must throw indexoutofbounds
// because you didn't added anything yet
Object item = productAdapter.getItem(from);
productAdapter.remove(item);
productAdapter.insert(item, to);
}
}
According to your add method of your adapter will add elements in Adapter.
public void add(Product object) {
list.add(object);
super.add(object);
}
Use Cursor Adapter, it is more efficient:
https://guides.codepath.com/android/Populating-a-ListView-with-a-CursorAdapter
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 got a source code about GridView.
But, I confused why some code were error.
These are the code. I got error on OnClick Method in MainActivity. Is here anyone help me? Thanks
public void onItemClick(AdapterView <? > AdapterView, View View, int Int, long Long) {
AdapterView = ((ImageItem) imageItems.get(Int)).getTitle();
toDetail(Int, AdapterView);
}
});
I want to each item that when it clicked shown the detailed image and text. I also get code like this but when I clicked "GingerBread" item, it goes to first item ("Astro")
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
ImageItem item = (ImageItem) parent.getItemAtPosition(position);
//Create intent
Intent intent = new Intent(getApplicationContext(), DetailActivity.class);
// intent.putExtra("android.intent.extra.TEXT", Integer.parseInt(getIntent().getStringExtra("android.intent.extra.TEXT")));
intent.putExtra("title", item.getTitle());
//Start details activity
startActivity(intent);
overridePendingTransition(R.anim.home_detail_entry, R.anim.home_detail_exit);
}
});
MainActivity.java
package com.acer.gridview;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends Activity {
public static String[] bitmapName = {
"Astro", "Bender", "Cupcake", "Donut", "Eclair",
"Froyo", "Gingerbread", "HoneyComb"
};
public static int[] bitmapId = {
R.drawable.Astro, R.drawable.Bender, R.drawable.Cupcake, R.drawable.Eclair,
R.drawable.Froyo, R.drawable.Gingerbread, R.drawable.HoneyComb
};
private GridViewAdapter gridAdapter;
private GridView gridView;
ArrayList < ImageItem > imageItems;
private ArrayList < ImageItem > getData() {
imageItems = new ArrayList();
BitmapFactory.Options localOptions = new BitmapFactory.Options();
localOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;
int i = 0;
for (;;) {
if (i > 7) {
return imageItems;
}
Bitmap localBitmap = BitmapFactory.decodeResource(getResources(), bitmapId[i], localOptions);
imageItems.add(new ImageItem(localBitmap, bitmapName[i]));
i += 1;
}
}
#
Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_grid);
gridView = (GridView) findViewById(R.id.gridView);
gridAdapter = new GridViewAdapter(this, R.layout.row_grid, getData());
gridView.setAdapter(gridAdapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView <? > AdapterView, View View, int Int, long Long) {
////////////This code shown error///////////////////
AdapterView = ((ImageItem) imageItems.get(Int)).getTitle();
toDetail(Int, AdapterView);
////////////This code shown error///////////////////
}
});
}
public void toDetail(int Int, String String) {
Intent localIntent = new Intent(this, DetailActivity.class);
localIntent.putExtra("android.intent.extra.TEXT", Integer.toString(Int));
localIntent.putExtra("title", String);
startActivity(localIntent);
}
/**
* A placeholder fragment containing a simple view.
*/
private boolean ActionBar(final Intent aIntent) {
try {
startActivity(aIntent);
return true;
} catch (ActivityNotFoundException e) {
return false;
}
}
public void showDialog() {
LayoutInflater inflater = getLayoutInflater();
View localView = inflater.inflate(R.layout.help_dialog, null);
((ImageView) localView.findViewById(R.id.imageView1)).setImageResource(R.drawable.makhrojulhuruf);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(localView);
builder.show();
}
#
Override
public boolean onCreateOptionsMenu(Menu menu) {}
#
Override
public boolean onOptionsItemSelected(MenuItem item) {
}
}
GridViewAdapter.java
package com.acer.gridview;
import android.app.Activity;
import android.content.Context;
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;
/**
* Created by Acer on 08/02/2016.
*/
public class GridViewAdapter extends ArrayAdapter<ImageItem> {
private Context context;
private int layoutResourceId;
private ArrayList<ImageItem> data = new ArrayList();
public GridViewAdapter(Context context, int layoutResourceId, ArrayList<ImageItem> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder holder = null;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ViewHolder();
holder.imageTitle = (TextView) row.findViewById(R.id.text);
holder.image = (ImageView) row.findViewById(R.id.image);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
ImageItem item = (ImageItem) data.get(position);
holder.imageTitle.setText(item.getTitle());
holder.image.setImageBitmap(item.getImage());
return row;
}
static class ViewHolder {
TextView imageTitle;
ImageView image;
}
}
ImageItem.java
package com.acer.gridview;
import android.graphics.Bitmap;
/**
* Created by Acer on 08/02/2016.
*/
public class ImageItem {
private Bitmap image;
private String title;
public ImageItem(Bitmap Bitmap, String String)
{
setImage(Bitmap);
setTitle(String);
}
public Bitmap getImage()
{
return this.image;
}
public String getTitle()
{
return this.title;
}
public void setImage(Bitmap Bitmap)
{
this.image = Bitmap;
}
public void setTitle(String String)
{
this.title = String;
}
}
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 activity, where in i display list of media files i.e Video, Audio, Images and Animations. On clicking the list item, (as of now Images), the activity must display all the images in the local assets folder in grid View. To do so, i use a single adapter and have a switch case in my getView() function. Depending on the options that is set in the constructor, the switch cases would execute. It works fine for the ListView display, but i am unable to display list of images in grid View. Any help would be apprecaited. Thanks in advance. Here is my code:
package com.bookshelf;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.ThumbnailUtils;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MediaGalaryListActivity extends Activity implements
OnItemClickListener {
private ArrayList<String> mGalary = new ArrayList<String>();
private Bitmap mBitArray[];
private Gallery mMediaGallery;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mediagalary);
mGalary.add("Videos");
mGalary.add("Audios");
mGalary.add("Images");
mGalary.add("Animation");
ListView lv = (ListView) findViewById(R.id.mediaGal);
mMediaGallery = (Gallery) findViewById(R.id.mediaGallery);
lv.setAdapter(new MediaGalaryAdapter(this, mGalary, 1));
lv.setOnItemClickListener(this);
}
class MediaGalaryAdapter extends BaseAdapter {
private ArrayList<String> mGal = new ArrayList<String>();
private Bitmap[] mImgArray;
private Context context;
private LayoutInflater mInflate;
private int mAdapterOpt;
public MediaGalaryAdapter(Context ctx, ArrayList<String> gal,
int adapOpt) {
context = ctx;
mGal = gal;
mAdapterOpt = adapOpt;
mInflate = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public MediaGalaryAdapter(Context ctx, Bitmap[] imgArray, int adapOpt) {
context = ctx;
mImgArray = imgArray;
mInflate = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mAdapterOpt = adapOpt;
}
public int getCount() {
int size = 0;
switch (mAdapterOpt) {
case 1:
size = mGal.size();
break;
case 2:
size = mImgArray.length;
break;
}
return size;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
switch (mAdapterOpt) {
case 1:
convertView = mInflate.inflate(R.layout.medialayout, null);
TextView tv = (TextView) convertView.findViewById(R.id.text);
tv.setText(mGal.get(position));
break;
case 2:
ImageView imgView;
convertView = mInflate.inflate(R.layout.image_gallery, null);
imgView = new ImageView(context);
imgView.setImageBitmap(mImgArray[position]);
imgView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imgView.setLayoutParams(new GridView.LayoutParams(100, 100));
imgView.setPadding(8, 8, 8, 8);
break;
}
return convertView;
}
}
// For filtering the filename with extensions
class FileNamFilter implements FilenameFilter {
private String mFileExtn;
public FileNamFilter(String extn) {
mFileExtn = "." + extn;
}
public boolean accept(File dir, String filename) {
return filename.endsWith(mFileExtn);
}
}
public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
String mediaType = mGalary.get(pos);
String list[] = null;
AssetManager assetManager = getAssets();
try {
list = assetManager.list("Immersive");
mBitArray = new Bitmap[list.length];
System.out.println("Length of list ="+list.length);
for (int i = 0, idx = 0; i < list.length; i++)
{
if (list[i].endsWith(".png") || list[i].endsWith(".gif")
|| list[i].endsWith(".jpeg")
|| list[i].endsWith(".jpg"))
{
mBitArray[idx++] = BitmapFactory.decodeStream(assetManager
.open("Immersive/" + list[i]));
System.out.println("Image at position "+i+" is "+list[i]);
}
;
}
mMediaGallery
.setAdapter(new MediaGalaryAdapter(this, mBitArray, 2));
} catch (IOException e) {
e.printStackTrace();
}
AlertDialog.Builder build = new AlertDialog.Builder(this);
build.setTitle("InProgress....");
// build.setIcon(android.R.drawable.)
build.setMessage(mediaType + " is Inprogress...");
build.setPositiveButton("Ok", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// finish();
}
});
AlertDialog alert = build.create();
alert.show();
// Toast.makeText(getApplicationContext(), mediaType, 30).show();
}
class MediaGalary {
private ImageView mImage;
private TextView mName;
public MediaGalary(ImageView img, TextView strName) {
mImage = img;
mName = strName;
}
public ImageView getmImage() {
return mImage;
}
public void setmImage(ImageView mImage) {
this.mImage = mImage;
}
public TextView getmName() {
return mName;
}
public void setmName(TextView mName) {
this.mName = mName;
}
}
}
each application in the device will be allocated some amount of memory by the DVM. you are getting out of memory error becoz your application is exceeding the memory the allocated by dvm to ur application. for example in froyo, memory allocated for an application is 16Mb. if your application exceeding more than 16Mb, you will get out of memory error. The solution for this is you have to compress the images you are using in your application, and you have to clear all the collection you are using. try clearing all collection you are using once there job is done. you can check how much memory has been consumed by your application in ddms using heap tool. hope this will be helpfull for you.