Android Listview not scrolling smoothly with multple images - android

I am working on an android application in which i have implemented CustomListView having some images and texts. i am feeding data in listview after a webservice call it takes some time to render list and when i scroll the list it's not scrolling smoothly.
here is the code of my List Adapter:
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.TextView;
import com.tv.makamaka.Constant;
import com.tv.makamaka.R;
import com.tv.makamaka.comment.SmileyCommentDialogActivity;
public class MakaMakaProfileListAdapter extends BaseAdapter implements Filterable {
private LayoutInflater mInflater;
private ArrayList<Object> itemList;
private Activity _activity;
String caption="";
String photoPath="";
String comments="";
String commentImage="";
String commentUserId="";
String likersImage="";
String likersType="";
String likersUserId="";
String mediaid="";
String mediaImageUrl="";
String mediaString="";
String mediaStringImage="";
String mediaStringUserId="";
String mediaType="";
String rating="";
String requestCount="";
String userid="";
String userProileImage="";
String withfriends="";
int index,index1,index2;
public MakaMakaProfileListAdapter(Activity activity, ArrayList<Object> itemList) {
this._activity = activity;
this.itemList = itemList;
mInflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return itemList.size();
}
public Object getItem(int position) {
return itemList.get(position);
}
public Filter getFilter() {
return null;
}
public long getItemId(int position) {
return 0;
}
static class ViewHolder {
TextView _commentTxt;
ImageView _userImage;
ImageView _smallUserImage;
ImageView _smallPostedUserImage;
ImageView _transparentImage;
}
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.makamaka_profile_listrow, null);
holder = new ViewHolder();
holder._userImage=(ImageView)convertView.findViewById(R.id.posted_userimage);
holder._smallUserImage=(ImageView)convertView.findViewById(R.id.small_userimage);
holder._smallPostedUserImage=(ImageView)convertView.findViewById(R.id.small_posted_userimage);
holder._transparentImage=(ImageView)convertView.findViewById(R.id.transparent_smiley_image);
holder._commentTxt = (TextView) convertView.findViewById(R.id.comment_txt);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder._commentTxt.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
}
});
holder._transparentImage.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent=new Intent(_activity,SmileyCommentDialogActivity.class);
_activity.startActivity(intent);
}
});
//////////////////SET VALUES ON LIST VIEW///////////////////////////
MakaMakaProfileBean makaMakaProfileBean=(MakaMakaProfileBean)itemList.get(position);
////////////////PARSE CAPTION///////////
caption=makaMakaProfileBean.getCaption();
ArrayList<String> captionList = new ArrayList<String>(Arrays.asList(caption.split(" , ")));
/*int index=caption.indexOf(",");
String caption1=caption.substring(0,index);
int index1=caption.indexOf(",", index+1);
String userName=caption.substring(index,index1+1);
String timeAgo=caption.substring(index1+1);*/
////////////////////////////////////////
////////////////PARSE COMMENTS////////////
comments=makaMakaProfileBean.getComments();
ArrayList<String> commentList = new ArrayList<String>(Arrays.asList(comments.split(" , ")));
//////////////////////////////////////////
////////////////PARSE COMMENT IMAGES//////
commentImage=makaMakaProfileBean.getCommentImage();
ArrayList<String> commentImageList = new ArrayList<String>(Arrays.asList(commentImage.split(" , ")));
//////////////////////////////////////////
////////////////PARSE COMMENT USER ID//////
commentUserId=makaMakaProfileBean.getCommentId();
ArrayList<String> commentUserIdList = new ArrayList<String>(Arrays.asList(commentUserId.split(" , ")));
//////////////////////////////////////////
////////////////PARSE LIKER IMAGES//////
likersImage=makaMakaProfileBean.getlikersImage();
ArrayList<String> likersImageList = new ArrayList<String>(Arrays.asList(likersImage.split(" , ")));
//////////////////////////////////////////
////////////////PARSE LIKER TYPE//////
likersType=makaMakaProfileBean.getComments();
ArrayList<String> likerTypeList = new ArrayList<String>(Arrays.asList(likersType.split(" , ")));
//////////////////////////////////////////
////////////////PARSE LIKER USER ID//////
likersUserId=makaMakaProfileBean.getComments();
ArrayList<String> likerUserIdList = new ArrayList<String>(Arrays.asList(likersUserId.split(" , ")));
//////////////////////////////////////////
////////////////PARSE OTHER PARAS//////
mediaid=makaMakaProfileBean.getmediaId();
mediaImageUrl=makaMakaProfileBean.getMediaImageUrl();
mediaString=makaMakaProfileBean.getMediaString();
mediaStringImage=makaMakaProfileBean.getMediaStringImage();
//mediaStringUserId=makaMakaProfileBean.
mediaType=makaMakaProfileBean.getMediaType();
rating=makaMakaProfileBean.getRating();
requestCount=makaMakaProfileBean.getRequestCount();
userid=makaMakaProfileBean.getUserId();
//userProileImage=makaMakaProfileBean.getUserProfileImage();
withfriends=makaMakaProfileBean.getWithFriends();
//////////////////////////////////////////
photoPath=makaMakaProfileBean.getUserProfileImage();
if(photoPath!=null){
URL url;
try {
url = new URL(photoPath);
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
holder._userImage.setImageBitmap(bmp);
} catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
int i=0;
while(i<captionList.size()){
if(i==0){
holder._commentTxt.setText((String)captionList.get(i));
}else if(i==1){
holder._commentTxt.setText(Html.fromHtml((String)captionList.get(i)));
}else if(i==2){
holder._commentTxt.setText(Html.fromHtml((String)captionList.get(i)));
}
i++;
}
return convertView;
/////////////////////////////////////////////////////////////////////
}
private Handler _handler = new Handler() {
public void dispatchMessage(Message msg) {
switch (msg.arg1) {
case 123:
break;
default:
break;
}
}
};
public void serverResponse(String response, int processid) {
Message msg = new Message();
msg.arg1 = processid;
msg.obj = response;
_handler.dispatchMessage(msg);
}
//SEND EMAIL TO INVITE FRIEND
public void sendEmail(String emailId){
Intent intent = new Intent(Intent.ACTION_SEND);
//intent.setType("text/plain");
intent.setType("message/rfc822");
intent.putExtra(Intent.EXTRA_EMAIL, emailId);
intent.putExtra(Intent.EXTRA_SUBJECT,Constant.EMAIL_SUBJECT);
intent.putExtra(Intent.EXTRA_TEXT, Constant.EMAIL_CONTENT);
_activity.startActivity(Intent.createChooser(intent, "Send Email"));
}
}
Output:
Is there any way to make list with smooth scroll.

You're decoding the image in getView. That's an expensive call, and you're going to be doing it a lot while scrolling. Use an LRUCache to cache images, so you can reuse the results of previous decodes if they exist. Only decode it in getView if its not in the cache.

Related

Why my listview not refresh when I press back button and come back to activity?

I'm tired already with my code. I'm writing chat application. My app consist of two activity. First activity has a listview of wich each row contain a last message which was send for the user while a second activity contain the whole conversation. In my app I used socket.io for android. My app works fine. Listview is refresh when a data is receive but when I press back button and then come back to the activity a listview not refresh itself already. In logs console I see that a data has received and "changed" method is called but listview is not refresh. What is wrong in belows code?
package com.example.seadog.fb_dialog;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.URISyntaxException;
import java.util.ArrayList;
import io.socket.client.IO;
import io.socket.client.Socket;
import io.socket.emitter.Emitter;
public class MainActivity extends Activity {
public static ArrayList arrayList = new ArrayList();
public ListView listView;
public MyBaseAdapter adapter;
public TextView textView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*
* Get Socket.io Object
*/
SocketIO socketIo = new SocketIO();
Socket mSocket = socketIo.getSocket(); // get socket
Integer id = socketIo.getId(); // get Website ID
if(mSocket == null) {
socketIo.Connection();
mSocket = socketIo.getSocket();
mSocket.on("message", new Emitter.Listener() {
/*
* Message Listener
*/
#Override
public void call(Object... args) {
Boolean isset = false;
try {
JSONObject object = (JSONObject) args[0];
String _id = object.getString("_id");
String message = object.getString("message");
JSONObject obj = new JSONObject();
obj.put("direction", "fb-lt");
obj.put("message", message);
obj.put("date", "2017-05-29T12:15:49.245Z");
for(int i = 0; i < arrayList.size(); i++){
ListData ld = (ListData) arrayList.get(i);
String id = ld.getId();
if(_id.equals(id)){
JSONArray Data = ld.getData();
Data.put(obj);
ld.setDescription(message);
arrayList.set(i, ld);
isset = true;
Log.d("LOG", message);
}
}
if(!isset) {
JSONArray jsonArray = new JSONArray();
jsonArray.put(obj);
ListData ld = new ListData();
ld.set_id(_id);
ld.setID(1);
ld.setTitle("Klient:");
ld.setDescription(message);
ld.setData(jsonArray);
arrayList.add(ld);
}
} catch (JSONException e) {
e.printStackTrace();
}
changed();
}
});
}
/*
* Populate a listview
*/
listView = (ListView) findViewById(R.id.listView);
adapter = new MyBaseAdapter(this, arrayList);
listView.setAdapter(adapter);
/*
* OnItemClickListener
*/
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this, Conversation.class);
intent.putExtra("item", position);
startActivity(intent);
TextView textView = (TextView) view.findViewById(R.id.descitem);
textView.setTypeface(null, Typeface.NORMAL);
}
});
textView = (TextView) findViewById(R.id.count);
}
private void changed() {
runOnUiThread(new Runnable() {
#Override
public void run() {
adapter.notifyDataSetChanged();
Log.d("LOG:", "adapter refresh");
}
});
}
}
MyBaseAdapter Class:
package com.example.seadog.fb_dialog;
import android.content.Context;
import android.graphics.Typeface;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.ArrayList;
public class MyBaseAdapter extends BaseAdapter {
Context context;
ArrayList<ListData> items = new ArrayList();
LayoutInflater inflater;
int id = 0;
public MyBaseAdapter(Context context, ArrayList items) {
this.context = context;
this.items = items;
inflater = LayoutInflater.from(this.context);
}
#Override
public int getCount() {
return items.size();
}
#Override
public ListData getItem(int position) {
return items.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
MyViewHolder mViewHolder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.list_item, parent, false);
mViewHolder = new MyViewHolder(convertView);
convertView.setTag(mViewHolder);
} else {
mViewHolder = (MyViewHolder) convertView.getTag();
}
ListData currentListData = getItem(position);
id = position > 0 ? getItem(position - 1).getID() : 0;
mViewHolder.Title.setText(currentListData.getTitle());
mViewHolder.Desc.setText(currentListData.getDescription());
if(1==1){
mViewHolder.Title.setVisibility(View.GONE);
}else {
if (id != currentListData.getID()) {
mViewHolder.Title.setVisibility(View.VISIBLE);
} else {
mViewHolder.Title.setVisibility(View.GONE);
}
}
return convertView;
}
private class MyViewHolder {
TextView Title, Desc;
public MyViewHolder(View item) {
Title = (TextView) item.findViewById(R.id.txtitem);
Desc = (TextView) item.findViewById(R.id.descitem);
Typeface title = Typeface.createFromAsset(context.getAssets(), "fonts/DroidSans.ttf");
Title.setTypeface(title);
Typeface desc = Typeface.createFromAsset(context.getAssets(), "fonts/DroidSans.ttf");
Desc.setTypeface(desc, Typeface.BOLD);
}
}
}
#Override
protected void onRestart() {
Intent intentBack = new Intent(getApplicationContext(),MainActivity.class);
startActivity(intentBack);
super.onRestart();
}
you did not have any callback after you back to this activity .
You can either override onResume() method or startActivityForResult and do something in the onAcitvityForResult method.

Listview refresh while fetching data from server

I have been working on an android project where I need to fetch data from server and display in a listview. The first retrieval is done successfully but from second retrieval onwards the fetched data's are placed below the previously fetched data. How can I refresh the listview to view the fetched data in the listview? The codes I used are given below.
package com.example.sohan.patient;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Sohan on 5/20/2016.
*/
public class Doctors_layout extends Fragment implements AdapterView.OnItemSelectedListener{
View myView;
Spinner spinner;
String selectedCity;
Context myContext;
String jsonResult;
JSONObject jsonObject;
JSONArray jsonArray;
ContactAdapter contactAdapter;
String JSON_String;
ListView listView;
Button button;
int check=0;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.doctors_directory, container, false);
myContext = inflater.getContext();
contactAdapter = new ContactAdapter(myContext, R.layout.row_layout);
spinner = (Spinner)myView.findViewById(R.id.spinner);
listView = (ListView)myView.findViewById(R.id.listView);
listView.setAdapter(contactAdapter);
spinner.setOnItemSelectedListener(this);
List<String> city = new ArrayList<String>();
city.add("Choose a City");
city.add("Chittagong");
city.add("Dhaka");
ArrayAdapter<String> aAdapter = new ArrayAdapter<String>(myContext, android.R.layout.simple_spinner_item ,city);
aAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(aAdapter);
return myView;
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//contactAdapter.notifyDataSetChanged();
if(check==0) {
((TextView) parent.getChildAt(0)).setTextSize(21);
if (position == 0) {
nothing();
} else {
check++;
selectedCity = parent.getItemAtPosition(position).toString();
Toast.makeText(myContext, "Check value: "+check, Toast.LENGTH_LONG).show();
retrieveInfo ri = new retrieveInfo();
ri.execute(selectedCity); // notifydata
}
}
else{
contactAdapter.notifyDataSetChanged();
selectedCity = parent.getItemAtPosition(position).toString();
retrieveInfo ri = new retrieveInfo();
ri.execute(selectedCity);
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
public void nothing(){
//Toast.makeText(myContext, "Default position 0", Toast.LENGTH_LONG).show();
}
class retrieveInfo extends AsyncTask<String, Void, String> { // send data to server
String myUrl;
protected void onPreExecute() {
myUrl ="http://bdpricelist.com/patient/retrieveMedicalName.php"; // change php script
}
protected String doInBackground(String... args) {
String city;
String result = null;
city = args[0];
JSONArray jsonArray = null;
try{
URL url = new URL(myUrl);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String data_to_send = URLEncoder.encode("city", "UTF-8")+"="+URLEncoder.encode(city,"UTF-8");
bufferedWriter.write(data_to_send);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream is = httpURLConnection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
while ((JSON_String = reader.readLine()) != null)
{
sb.append(JSON_String+"\n");
}
reader.close();
httpURLConnection.disconnect();
is.close();
return sb.toString().trim();
}catch(MalformedURLException e){
e.printStackTrace();
}catch(IOException f){
f.printStackTrace();
}
return null;
}
protected void onPostExecute(String result) {
jsonResult = result;
parseJSON(jsonResult);
//jsonResult="";
}
}
public void delete(String city) {
Fragment Dl = new Doctors_layout();
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.content_frame, Dl);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
public void parseJSON(String json){
Contacts contacts=null;
try {
jsonObject = new JSONObject(json);
jsonArray = jsonObject.getJSONArray("patient");
int count = 0;
String name;
while (count < jsonArray.length()) {
JSONObject jo = jsonArray.getJSONObject(count);
name = jo.getString("Medical"); // data's are send to store in and print in listview
contacts = new Contacts(name);
contactAdapter.add(contacts);
count++;
}
//contactAdapter.add(contacts.getMedicalName());
} catch (Exception e) {
e.printStackTrace();
}
}
}
And my adapter class is given below
package com.example.sohan.patient;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Sohan on 6/9/2016.
*/
public class ContactAdapter extends ArrayAdapter {
//ContactHolder contactHolder;
List list = new ArrayList();
ContactAdapter contactAdapter;
List receivedList = new ArrayList();
View row;
ContactHolder contactHolder;
int count =0;
public ContactAdapter(Context context, int resource) {
super(context, resource);
}
public void add(Contacts object) {
// list.clear();
super.add(object);
list.add(object);
//notifyDataSetChanged();
Toast.makeText(getContext().getApplicationContext(), "Entry without delete ", Toast.LENGTH_SHORT).show();
}
#Override
public int getCount() {
return list.size();
}
#Override
public void clear() {
super.clear();
}
#Override
public boolean isEmpty() {
return super.isEmpty();
}
#Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
public void deleteEntry(){
list.clear();
Toast.makeText(getContext().getApplicationContext(), "List cleared before entry ", Toast.LENGTH_SHORT).show();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//count++;
row = convertView;
if(row==null){
LayoutInflater layoutInflater = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.row_layout,parent,false);
contactHolder = new ContactHolder();
contactHolder.MedicalName =(TextView) row.findViewById(R.id.textView5);
row.setTag(contactHolder);
}
else{
contactHolder = (ContactHolder)row.getTag();
}
contactHolder = new ContactHolder();
contactHolder.MedicalName =(TextView) row.findViewById(R.id.textView5);
Contacts contacts = (Contacts)this.getItem(position);
contactHolder.MedicalName.setText(contacts.getMedicalName());
return row;
}
static class ContactHolder{
TextView MedicalName;
}
}
Instead of having add(Contacts object) in your adapter, have a method where you clear the current items in the list and update with the newly retrieved items.
private void updateContactList(List<Contacts> updatedList) {
list.clear();
list.addAll(updatedList);
notifyDataSetChanged();
}
and inside parseJSON(String json)
List<Contacts> newList = new ArrayList<>();
while (count < jsonArray.length()) {
JSONObject jo = jsonArray.getJSONObject(count);
name = jo.getString("Medical");
contacts = new Contacts(name);
newList.add(contacts);
count++;
}
contactAdapter.updateContactList(newList);
The new data is being shown after the old data because you are adding new data to the existing one in parseJSON().
If you want to replace the old data with new one then remove these lines from onCreateView and add inside parseJSON(), right after while loop.
contactAdapter = new ContactAdapter(myContext, R.layout.row_layout);
listView.setAdapter(contactAdapter);

GridView doesn't show anything after JSON parsing the values into its items

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 :)

How to load images using android baseadapter?

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;
}
}

CustomAdapter with multiple getView in android

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.

Categories

Resources