I have made a listview with image and text as elements. If the data is text it displays text and if it is image it displays image.
When i click button from MainActivity to the listview, the listview is displayed as needed, i.e images for image and text for text data.
The problem occurs when the listview activity is opened and any new data is inserted in db and the listview is refreshed. The data in the view is completely messed up. it shows image in the some of the text data.
But when i go back to the main activity and again come back to listview everything is perfect.
Can anyone please help me whats going wrong here.
I am using SimpleCursorAdaptor, CursorLoader.
MainActivity.java
public class MainActivity extends ActionBarActivity implements LoaderCallbacks<Cursor>{
private TextView from, data;
private SimpleCursorAdapter dataAdapter;
private String TO_USER;
ConnectionService connService;
boolean mBounded;
#Override
public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
String[] projection = {MessageHelper.COLUMN_ID,
MessageHelper.COLUMN_FROM,
MessageHelper.COLUMN_DATA};
String args[] ={ "cid","data"};
CursorLoader cursorLoader = new CursorLoader(this,
MyContentProvider.CONTENT_URI, projection,
MessageHelper.COLUMN_CONVERSATION_ID + " = ?" + " AND " +
MessageHelper.COLUMN_EXIN + " = ?" ,args,
MessageHelper.COLUMN_RECIEVED_TIMESTAMP);
return cursorLoader;
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter();
getLoaderManager().initLoader(0, null, this);
}
private void setListAdapter() {
String[] columns = new String[] {
MessageHelper.COLUMN_FROM,
MessageHelper.COLUMN_DATA
};
int[] to = new int[] {
R.id.data
};
Cursor cursor = loadMessage();
cursor.moveToFirst();
dataAdapter = new CustomCursorAdapter(
this,
R.layout.linear_listitem,
cursor,
columns,
to,
0);
listview.setAdapter(dataAdapter);
.
}
public void onLoaderReset(Loader<Cursor> loader) {
dataAdapter.swapCursor(null);
}
protected void onResume() {
super.onResume();
getLoaderManager().restartLoader(0, null, this);
}
protected void onRestart(){
super.onRestart();
}
CursorAdapter.java
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ClipDrawable;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
//import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import com.expert.sqllite.MessageChat;
import com.expert.sqllite.MessageHelper;
public class CustomCursorAdapter extends SimpleCursorAdapter {
private LayoutInflater mInflater;
private Map<Integer, ArrayList<MessageChat>> chatMapConId = new HashMap<Integer,
ArrayList<MessageChat>>();
public CustomCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to, int flags) {
super(context, layout, c, from, to,flags);
mInflater = (LayoutInflater)context.getSystemService
(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
MessageChat msgchat = new MessageChat();
msgchat.setData(cursor.getString(cursor.getColumnIndex(MessageHelper.COLUMN_DATA)));
msgchat.setFrom(cursor.getString(cursor.getColumnIndex(MessageHelper.COLUMN_FROM)));
ViewHolder holder;
if(!msgchat.getData().contains("-image-")){
holder = (ViewHolder) view.getTag();
}
else{
holder = (ViewHolder) view.getTag();
}
TextView dataMsg =(TextView)view.findViewById(R.id.data);
RelativeLayout.LayoutParams lp1 = new RelativeLayout.LayoutParams
(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
ImageView imgMsg =null;
if(msgchat.getFrom().equalsIgnoreCase("me"))
{
if(!msgchat.getData().contains("-image-")){
dataMsg.setBackgroundResource
(R.drawable.speech_bubble_green);
dataMsg.setText(msgchat.getData());
}
else
{
String[] imageSplit=msgchat.getData().split("-image-");
Uri imgUri=Uri.parse(imageSplit[1]);
try {
imgMsg (ImageView)view.findViewById
(R.id.chat_image);
imgMsg.setImageBitmap(getThumbnail
(imgUri,context));
dataMsg.setVisibility(View.INVISIBLE);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
lp1.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
}
else
{
if(!msgchat.getData().contains("-image-")){
dataMsg.setBackgroundResource
(R.drawable.speech_bubble_orange);
dataMsg.setText(msgchat.getData());
}
else{
String[] imageSplit=msgchat.getData().split("-image-");
Uri imgUri=Uri.parse(imageSplit[1]);
try {
imgMsg =(ImageView)view.findViewById
(R.id.chat_image);
imgMsg.setImageBitmap(getThumbnail
(imgUri,context));
imgMsg.setBackgroundResource
(R.drawable.speech_bubble_orange);
dataMsg.setVisibility(View.INVISIBLE);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
lp1.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
}
if(!msgchat.getData().contains("-image-")){
dataMsg.setLayoutParams(lp1);
dataMsg.setTextColor(R.color.textColor);
}
else{
imgMsg.setLayoutParams(lp1);
}
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// TODO Auto-generated method stub
File imageFile;
View rowView = mInflater.inflate(R.layout.linear_listitem, parent, false);
View rowViewImage = mInflater.inflate(R.layout.linear_listitem_image, parent, false);
ViewHolder holder = null;
ViewHolderImage holderImage = null;
String data = cursor.getString(cursor.getColumnIndex(MessageHelper.COLUMN_DATA));
String path = null;
if(data.contains("-image-")){
path = data.split("-image-")[1];
}
holder = new ViewHolder();
holder.data = (TextView)rowView.findViewById(R.id.data);
holder.imageHolder = (ImageView)rowViewImage.findViewById(R.id.chat_image);
rowView.setTag(holder);
return rowView;
}
class ViewHolder
{
TextView data,from;
ImageView imageHolder ;
}
class ViewHolderImage
{
ImageView imageHolder ;
}
public static Bitmap getThumbnail(Uri uri,Context context) throw FileNotFoundException,IOException{
InputStream input = context.getContentResolver().openInputStream(uri);
BitmapFactory.Options onlyBoundsOptions = new BitmapFactory.Options();
onlyBoundsOptions.inJustDecodeBounds = true;
onlyBoundsOptions.inDither=true;//optional
onlyBoundsOptions.inPreferredConfig=Bitmap.Config.ARGB_8888;//optional
BitmapFactory.decodeStream(input, null, onlyBoundsOptions);
input.close();
if ((onlyBoundsOptions.outWidth == -1) || (onlyBoundsOptions.outHeight == -1))
return null;
int originalSize = (onlyBoundsOptions.outHeight > onlyBoundsOptions.outWidth) ?
onlyBoundsOptions.outHeight : onlyBoundsOptions.outWidth;
// double ratio = (originalSize > THUMBNAIL_SIZE) ? (originalSize / THUMBNAIL_SIZE): 1.0;
double ratio = 1.0;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
//bitmapOptions.inSampleSize = getPowerOfTwoForSampleRatio(ratio);
bitmapOptions.inSampleSize = 2;
bitmapOptions.inMutable = true;
bitmapOptions.inDither=true;//optional
bitmapOptions.inPreferredConfig=Bitmap.Config.RGB_565;//optional
bitmapOptions.outHeight=150;
bitmapOptions.outWidth=150;
input = context.getContentResolver().openInputStream(uri);
Bitmap bitmap = BitmapFactory.decodeStream(input, null, bitmapOptions);
input.close();
//bitmap.setWidth(400);
//bitmap.setHeight(400);
return bitmap;
}
private static int getPowerOfTwoForSampleRatio(double ratio){
int k = Integer.highestOneBit((int)Math.floor(ratio));
if(k==0) return 1;
else return k;
}
}
Update
If i have data only text or only image. Then the list view is perfect. The problem i think is when both the view i.e text and image comes into picture.
#Override
public int getItemViewType(int position) {
Cursor cursor = (Cursor) getItem(position);
return getItemViewType(cursor);
}
#Override
public int getViewTypeCount() {
return 2;
}
These method has solved the problem of improper display
Related
I have a sample app where the contacts in my android phone are listed and I can search for them. However, very often the contacts are listed twice. I only want them to be listed once. What should I change in my code to fix this? I've posted the relevant parts of my code below.
I did try here how to remove duplicate contacts from arraylist but I couldn't modify the code sufficiently to suit my needs.
MainActivity.java
package com.example.chris.contactlistcustomlistview;
import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.Toast;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends Activity {
// ArrayList
ArrayList<SelectUser> selectUsers;
List<SelectUser> temp;
// Contact List
ListView listView;
// Cursor to load contacts list
Cursor phones, email;
// Pop up
ContentResolver resolver;
SearchView search;
SelectUserAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
selectUsers = new ArrayList<SelectUser>();
resolver = this.getContentResolver();
listView = (ListView) findViewById(R.id.contacts_list);
phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
// retrieves contact information
LoadContact loadContact = new LoadContact();
loadContact.execute();
// let's set up our search box,
search = (SearchView) findViewById(R.id.searchView);
//*** setOnQueryTextListener ***
search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
// when the text in searchView changes, call the filter function
adapter.filter(newText);
return false;
}
});
}
// Load data on background
class LoadContact extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... voids) {
// Get Contact list from Phone
if (phones != null) {
Log.e("count", "" + phones.getCount());
if (phones.getCount() == 0) {
Toast.makeText(MainActivity.this, "No contacts in your contact list.", Toast.LENGTH_LONG).show();
}
while (phones.moveToNext()) {
Bitmap bit_thumb = null;
String id = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String EmailAddr = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA2));
String image_thumb = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_THUMBNAIL_URI));
try {
if (image_thumb != null) {
bit_thumb = MediaStore.Images.Media.getBitmap(resolver, Uri.parse(image_thumb));
} else {
Log.e("No Image Thumb", "--------------");
}
} catch (IOException e) {
e.printStackTrace();
}
//what's happening here? For every user in the phonebook, show an image, the name, number, an id and maybe a checkbox?
SelectUser selectUser = new SelectUser();
selectUser.setThumb(bit_thumb);
selectUser.setName(name);
selectUser.setPhone(phoneNumber);
selectUser.setEmail(id);
selectUser.setCheckedBox(false);
selectUsers.add(selectUser);
}
} else {
Log.e("Cursor close 1", "----------------");
}
//phones.close();
return null;
}
#Override
// when DoInBackground is finished, when we have our phone number, name etc... display the results in our listview.
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
adapter = new SelectUserAdapter(selectUsers, MainActivity.this);
listView.setAdapter(adapter);
// Select item on listclick
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Log.e("search", "here---------------- listener");
SelectUser data = selectUsers.get(i);
}
});
listView.setFastScrollEnabled(true);
}
}
#Override
protected void onStop() {
super.onStop();
phones.close();
}
}
SelectUserAdapter.java
package com.example.chris.contactlistcustomlistview;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
/**
* Created by Chris on 25/03/2016.
*/
public class SelectUserAdapter extends BaseAdapter {
public List<SelectUser> _data;
private ArrayList<SelectUser> arraylist;
Context _c;
ViewHolder v;
// RoundImage roundedImage;
public SelectUserAdapter(List<SelectUser> selectUsers, Context context) {
_data = selectUsers;
_c = context;
this.arraylist = new ArrayList<SelectUser>();
this.arraylist.addAll(_data);
}
#Override
public int getCount() {
return _data.size();
}
#Override
public Object getItem(int i) {
return _data.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
#Override
public View getView(int i, View convertView, ViewGroup viewGroup) {
View view = convertView;
if (view == null) {
LayoutInflater li = (LayoutInflater) _c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = li.inflate(R.layout.inflate_listview, null);
Log.e("Inside", "here--------------------------- In view1");
} else {
view = convertView;
Log.e("Inside", "here--------------------------- In view2");
}
// we are making a cell format in the ListView, which will contain info like
// number, name... the layout for this, with name, no, pic etc...
// is contained in inflate_listview.xml, which describes how each cell data
// loads into the listview
v = new ViewHolder();
// So, for example, title is cast to the name id, in activity main,
// phone is cast to the id called no etc
v.title = (TextView) view.findViewById(R.id.name);
v.check = (CheckBox) view.findViewById(R.id.check);
v.phone = (TextView) view.findViewById(R.id.no);
// v.imageView = (ImageView) view.findViewById(R.id.pic);
// for each new cell with title, name, number etc...
//
final SelectUser data = (SelectUser) _data.get(i);
v.title.setText(data.getName());
v.check.setChecked(data.getCheckedBox());
v.phone.setText(data.getPhone());
Log.e("Image Thumb", "--------------" + data.getThumb());
view.setTag(data);
return view;
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
// _data is our list of Users, or contacts
_data.clear();
// If there is nothing in the searchbox,
// then show all the contacts
if (charText.length() == 0) {
_data.addAll(arraylist);
// or else....
} else {
for (SelectUser wp : arraylist) {
// If a contact's phone number matches the input thus far that the user
// is filtering for, then include it in the listview.
if (wp.getPhone().toLowerCase(Locale.getDefault())
.contains(charText)) {
_data.add(wp);
}
}
}
notifyDataSetChanged();
}
static class ViewHolder {
// In each cell in the listview show a name and phone number
// ImageView imageView;
TextView title, phone;
CheckBox check;
}
}
public class MainActivity extends Activity {
Cursor cursor;
ListView mainListView;
ArrayList hashMapsArrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (cursor != null) {
cursor.moveToFirst();}
try {
cursor = getApplicationContext().getContentResolver()
.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
int Idx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID);
int nameIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
int phoneNumberIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
int photoIdIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_THUMBNAIL_URI);
cursor.moveToFirst();
Set<String> ids = new HashSet<>();
do {
System.out.println("=====>in while");
String contactid=cursor.getString(Idx);
if (!ids.contains(contactid)) {
ids.add(contactid);
HashMap<String, String> hashMap = new HashMap<String, String>();
String name = cursor.getString(nameIdx);
String phoneNumber = cursor.getString(phoneNumberIdx);
String image = cursor.getString(photoIdIdx);
System.out.println("Id--->"+contactid+"Name--->"+name);
System.out.println("Id--->"+contactid+"Number--->"+phoneNumber);
if (!phoneNumber.contains("*")) {
hashMap.put("contactid", "" + contactid);
hashMap.put("name", "" + name);
hashMap.put("phoneNumber", "" + phoneNumber);
hashMap.put("image", "" + image);
// hashMap.put("email", ""+email);
if (hashMapsArrayList != null) {
hashMapsArrayList.add(hashMap);}
// hashMapsArrayList.add(hashMap);
}
}
} while (cursor.moveToNext());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (cursor != null) {
cursor.close();
}
}
}
}
Try this, I am not sure it will solve this problem.
if (selectUsers.indexOf(selectUser) == -1) {
selectUsers.add(selectUser);
}
I have a problem here, this is my customAdapter for ListView.
I was trying to get an XML file and show it using this adapter.
I have few source of XML files and one of them has an image link.
Using this code, I have shown all the images, but somehow it was not placed in the correct imageView.
Can anyone see why this is not working correctly?
package dotmanga.classes;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
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 example.dotmanga.R;
public class TestAdapter extends BaseAdapter {
private Context con;
private List<Entry> entries;
private LayoutInflater inflater;
private Handler hand = new Handler();
static class ViewHolder {
TextView title;
TextView link;
ImageView imv;
}
public TestAdapter(Context c, List<Entry> e) {
this.con = c;
this.entries = e;
this.inflater = LayoutInflater.from(this.con);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return entries.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return entries.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final ViewHolder holder;
View vi = convertView;
if (convertView == null) {
vi = this.inflater.inflate(R.layout.activity_list_row, null);
holder = new ViewHolder();
holder.title = (TextView) vi.findViewById(R.id.title);
holder.link = (TextView) vi.findViewById(R.id.link);
holder.imv = (ImageView) vi.findViewById(R.id.imageView1);
vi.setTag(holder);
} else {
holder = (ViewHolder) vi.getTag();
}
Entry entry = entries.get(position);
holder.title.setText(entry.title);
holder.link.setText(entry.link);
if (entry.img != null) {
final String myurl = entry.img;
new Thread(new Runnable() {
public void run() {
try {
URL url = new URL(myurl);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
final Bitmap myBitmap = BitmapFactory.decodeStream(input);
hand.post(new Runnable() {
public void run() {
holder.imv.setImageBitmap(myBitmap);
}
});
connection.disconnect();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}
return vi;
}
}
Your issue is probably due to an empty imageView, if some image are empty, getView will display wrong image. You need to catch some "ErrorRessource".
like :
if (entry.img != null) {
//do some stuff
}
else {
holder.imv.setImageResource(R.drawable.theErrorImage);
}
But more deeply, i don't think you use the best practice to display images from Url, i strongly advice you to use some libs like https://github.com/lexs/webimageloader , who allow you to cache these images and do your job in an easy ans useful way.
im easily able to use for textviews but textview with imageview like contacts name,number and image display sort of listing i m suffering with i have searched many blogs but without success please help....
public class Listmain extends ListActivity
{
#Override public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
try
{
Data_baseActivity db=new Data_baseActivity(this);
db.open();
InputStream is;
Cursor cursor =db.getAllContacts1();
int len=cursor.getCount();
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.rowlayout, cursor, new String[] { "image", "name"}, new int[] { R.id.icon, R.id.label});
adapter.setViewBinder(new ProductViewBinder());
setListAdapter(adapter);
db.close();
}
catch(Exception e)
{
Toast.makeText(this, e.toString()+" error", Toast.LENGTH_LONG).show();
}
}
}
public class ProductViewBinder implements ViewBinder
{
public boolean setViewValue(View view, Cursor cursor, int columnIndex)
{
try
{
if (view instanceof ImageView)
{
byte[] result = cursor.getBlob(3);//my image is stored as blob in db at 3
Bitmap bmp = BitmapFactory.decodeByteArray(result, 0, result.length);
ImageView im=(ImageView)findViewById(R.id.icon);
im.setImageBitmap(bmp);
return true;
}
}
catch(Exception e)
{
Toast.makeText(Listmain.this, e.toString()+" err", Toast.LENGTH_LONG).show();
}
return false;
}
}
Try like this:
cr.getBlob(cr.getColumnIndex("Image")) //where "Image" is column name.
I used this and it worked.
If it doesn't worked. Please post the toast message that u r getting in the exception
package com.service;
import java.io.InputStream;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class Listmain extends ListActivity{
Bitmap bmaps;
private FriendAdapter friendAdapter;
String forDeletion[][]=null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.viewer);
EditText etxData=(EditText)findViewById(R.id.search);
etxData.setText(null);
listContacts();
}
#Override
protected void onResume() {
super.onResume();
EditText etxData=(EditText)findViewById(R.id.search);
etxData.setText(null);
listContacts();
}
public void listContacts()
{
Data_baseActivity db=new Data_baseActivity(this);
try
{
Resources res=getResources();
Drawable d = res.getDrawable(R.drawable.no_photo);
bmaps = ((BitmapDrawable)d).getBitmap();
final ListView lv = getListView();
final EditText etx=(EditText)findViewById(R.id.search);
final ImageButton imgbtn=(ImageButton)findViewById(R.id.refresh);
db.open();
Cursor cursor =getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null);
if(cursor.getCount()<1)
{
etx.setVisibility(View.GONE);
}
startManagingCursor(cursor);
int len=cursor.getCount();
forDeletion=new String[len][4];
String[] from = new String[] {};
int[] to = new int[] {};
this.friendAdapter = new FriendAdapter(this, R.layout.rowlayout, cursor, from, to);
lv.setAdapter(friendAdapter);
etx.addTextChangedListener(new TextWatcher(){
public void afterTextChanged(Editable arg0) {
}
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
}
public void onTextChanged(CharSequence c, int s,
int e, int h) {
try
{
Data_baseActivity db1=new Data_baseActivity(Listmain.this);
db1.open();
Cursor searchCursor =getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,null,
ContactsContract.Contacts.DISPLAY_NAME + " LIKE ?" , new String[]{c+"%"}, null);
startManagingCursor(searchCursor);
String[] from = new String[] {};
int[] to = new int[] {};
friendAdapter = new FriendAdapter(Listmain.this, R.layout.rowlayout, searchCursor, from, to);
lv.setAdapter(friendAdapter);
db1.close();
}
catch(Exception es)
{
Toast.makeText(Listmain.this, es.toString()+" g", Toast.LENGTH_LONG).show();
}
}
});
}
catch(Exception e)
{
Toast.makeText(this, e.toString()+" error", Toast.LENGTH_LONG).show();
}
db.close();
}
#Override
protected void onListItemClick(ListView l, View v, final int position, long id) {
super.onListItemClick(l, v, position, id);
Intent intent=new Intent(Listmain.this,Editing.class);
String send[]=new String[4];
send[0]=forDeletion[position][0];
send[1]=forDeletion[position][1];
send[2]=forDeletion[position][2];
send[3]=forDeletion[position][3];
intent.putExtra("com.service.id", send);
startActivity(intent);
}
public class FriendAdapter extends SimpleCursorAdapter
{
private final Context mContext;
private final int mLayout;
private final Cursor mCursor;
private final int mNameIndex;
private final int mIdIndex;
private final LayoutInflater mLayoutInflater;
private int lookUp;
private final class ViewHolder {
public TextView name;
public ImageView image;
public TextView number;
public ImageView endis;
}
public FriendAdapter(Context context, int layout, Cursor c, String[] from, int[] to) {
super(context, layout, c, from, to);
this.mContext = context;
this.mLayout = layout;
this.mCursor = c;
this.mNameIndex = mCursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
this.mIdIndex = mCursor.getColumnIndex(ContactsContract.Contacts._ID);
this.lookUp=mCursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY);
this.mLayoutInflater = LayoutInflater.from(mContext);
}
public View getView(int position, View convertView, ViewGroup parent) {
try
{
if (mCursor.moveToPosition(position)) {
ViewHolder viewHolder = null;
String name = mCursor.getString(mNameIndex);
if (convertView == null)
{
convertView = mLayoutInflater.inflate(mLayout, null);
viewHolder = new ViewHolder();
viewHolder.name = (TextView) convertView.findViewById(R.id.label);
viewHolder.number = (TextView) convertView.findViewById(R.id.number);
viewHolder.image = (ImageView) convertView.findViewById(R.id.icon);
viewHolder.endis = (ImageView) convertView.findViewById(R.id.endis);
convertView.setTag(viewHolder);
}
else
{
viewHolder = (ViewHolder) convertView.getTag();
}
String number = null;
String image = mCursor.getString(mIdIndex);
String lookup=mCursor.getString(lookUp);
long lid=Long.parseLong(image);
Bitmap bmp = loadContactPhoto(mContext.getContentResolver(),lid,mContext);
if(bmp==null)
{
bmp=bmaps;
}
viewHolder.image.setImageBitmap(bmp);
viewHolder.name.setText(name);
Cursor cur = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ? " , new String[] {image}, null);
String num=null;
while(cur.moveToNext())
{
num = cur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
num=num+"\n";
}
number=num;
viewHolder.endis.setVisibility(View.GONE);
viewHolder.number.setText(number);
forDeletion[position][0]=name;
forDeletion[position][1]=number;
forDeletion[position][2]=image;
forDeletion[position][3]=lookup;
}
}
catch(Exception e)
{
Toast.makeText(Listmain.this, e.toString()+" 2", Toast.LENGTH_LONG).show();
}
return convertView;
}
}
public Bitmap loadContactPhoto(ContentResolver cr, long id,Context ctx) {
InputStream input=null;
try
{
Uri uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, id);
input= ContactsContract.Contacts.openContactPhotoInputStream(cr, uri);
}
catch(Exception e)
{
Toast.makeText(ctx, "Image formation error", Toast.LENGTH_LONG).show();
}
Bitmap bmp=BitmapFactory.decodeStream(input);
return bmp;
}
}
## Heading ##
Write a class and extend simpleCusorAdapter in it.
Create a constructor in the class and take parameters: context, layout, cursor, from, to
In the constructor, intialize the views of your customized layout like this.imageContainer=container.
good day, i am having a bit of a problem here. i am using and async task to display images from external or internal storage.Now it works but the problem is, it is very slow and slightly jerky in scrolling. I have no idea why? please any solution or an idea how to do this.
import java.io.IOException;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Debug;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class Wallpaper extends Activity implements OnItemClickListener{
/*Instance variables*/
private GridView grid;
private ImageAdapter imageAdapter;
private Display display;
Cursor cursor;
boolean inInternalStorage = false;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.wallpaper_images);
display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
setupViews();
setProgressBarIndeterminateVisibility(true);
loadImages();
}
#Override
protected void onStop(){
super.onStop();
}
/*methods called from AsyncTask as appropriate when its querying and processing the images from the MediaStore*/
private void loadImages() {
final Object data = getLastNonConfigurationInstance();
if(data == null){
new LoadImagesFromSDCard().execute();
}else {
final LoadedImage[] photos = (LoadedImage[])data;
if(photos.length == 0){
new LoadImagesFromSDCard().execute();
}
for(LoadedImage photo:photos){
addImage(photo);
}
}
}
private void addImage(LoadedImage... value) {
for(LoadedImage photo: value){
imageAdapter.addPhotos(photo);
imageAdapter.notifyDataSetChanged();
}
}
private void setupViews() {
grid = (GridView)findViewById(R.id.gridview);
grid.setNumColumns(display.getWidth()/95);
grid.setClipToPadding(false);
imageAdapter = new ImageAdapter(getApplicationContext());
grid.setAdapter(imageAdapter);
grid.setOnItemClickListener(this);
}
protected void onDestroy() {
super.onDestroy();
final GridView gridview = grid;
final int count = grid.getChildCount();
ImageView v = null;
for (int i = 0; i < count; i++) {
v = (ImageView) grid.getChildAt(i);
((BitmapDrawable) v.getDrawable()).setCallback(null);
}
unbindDrawables(findViewById(R.id.gridview));
System.gc();
}
/*public Object onRetainNonConfigurationInstance(){
final GridView gridview = grid;
final int count = grid.getChildCount();
final LoadedImage[] list = new LoadedImage[count];
for(int i = 0; i < count; i++){
final ImageView v = (ImageView)grid.getChildAt(i);
list[i] = new LoadedImage(((BitmapDrawable) v.getDrawable()).getBitmap());
}
return list;
}*/
/*utility method called that prevents screen from crashing when screen orientation changes*/
private void unbindDrawables(View view){
if(view.getBackground() != null){
view.getBackground().setCallback(null);
}
if(view instanceof ViewGroup){
for(int i = 0; i < ((ViewGroup) view).getChildCount(); i++){
unbindDrawables(((ViewGroup)view).getChildAt(i));
}
try{
((ViewGroup)view).removeAllViews();
}catch(Exception e){
e.printStackTrace();
}
}
}
/*AsyncTask thats queries the MediaStore for images and creates thumbnail images from bitmaps*/
class LoadImagesFromSDCard extends AsyncTask<Object, LoadedImage, Object> {
#Override
protected Object doInBackground(Object... params) {
Cursor cursor;
Bitmap bitmap = null;
Bitmap newbitmap = null;
Uri uri = null;
String [] img = {MediaStore.Images.Media._ID};
String state = Environment.getExternalStorageState();
if(Environment.MEDIA_MOUNTED.equals(state)){
cursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, img,
MediaStore.Images.Media.DATA + " like ? " , new String[]{ "%dcim%"}, null);
} else {
cursor = getContentResolver().query(MediaStore.Images.Media.INTERNAL_CONTENT_URI, img, null, null, null);
inInternalStorage = true;
}
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID);
int size = cursor.getCount();
if(size == 0){
Toast.makeText(getApplicationContext(), "There are no Images on the sdcard", Toast.LENGTH_SHORT).show();
}else {
}
for(int i = 0; i < size; i++){
cursor.moveToPosition(i);
int ImageId = cursor.getInt(column_index);
if(inInternalStorage == true){
uri = Uri.withAppendedPath(MediaStore.Images.Media.INTERNAL_CONTENT_URI, "" + ImageId);
}else {
uri = Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "" + ImageId);
}
try {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize=4;
bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri), null, options);
if(bitmap != null){
newbitmap = Bitmap.createScaledBitmap(bitmap, 100, 100, true);
bitmap.recycle();
}
if(newbitmap != null){
publishProgress(new LoadedImage(newbitmap));
}
}catch(IOException e){
}
}
cursor.close();
return null;
}
#Override
public void onProgressUpdate(LoadedImage... value){
addImage(value);
}
#Override
protected void onPostExecute(Object result) {
setProgressBarIndeterminateVisibility(false);
}
}
private static class LoadedImage {
Bitmap mBitmap;
LoadedImage(Bitmap bitmap) {
mBitmap = bitmap;
}
public Bitmap getBitmap() {
return mBitmap;
}
}
/*Image Adapter to populate grid view of images*/
public class ImageAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<LoadedImage> photos = new ArrayList<LoadedImage>();
public ImageAdapter(Context context){
this.mContext = context;
}
public void addPhotos(LoadedImage photo){
photos.add(photo);
}
#Override
public int getCount() {
return photos.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
System.gc();
ImageView image;
ViewHolder holder;
if(convertView == null){
LayoutInflater inflater = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.image_list,null);
holder = new ViewHolder();
holder.image = (ImageView)convertView.findViewById(R.id.image_list_id);
convertView.setTag(holder);
} else{
holder = (ViewHolder)convertView.getTag();
}
holder.image.setLayoutParams(new GridView.LayoutParams(100, 100));
holder.image.setImageBitmap(photos.get(position).getBitmap());
return convertView;
}
}
static class ViewHolder {
ImageView image;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Cursor cursor = null;
int image_column_index = 0;
String[] proj = {MediaStore.Images.Media.DATA};
String state = Environment.getExternalStorageState();
if(Environment.MEDIA_MOUNTED.equals(state)){
cursor = managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,proj, MediaStore.Images.Media.DATA + " like ? ", new String[]{"%dcim%"},null);
}else{
cursor = managedQuery(MediaStore.Images.Media.INTERNAL_CONTENT_URI,proj,null, null,null);
}
cursor.moveToPosition(position);
image_column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
String info = cursor.getString(image_column_index);
Intent imageviewer = new Intent(getApplicationContext(), ViewImage.class);
imageviewer.putExtra("pic_name", info);
startActivity(imageviewer);
}
}
i think what i am after is a way to allow doBackground() to run for a while before i call publishProgress(). just like how the gallery app in android does.
Any ideas on why this could be slow or how to solve this problem will be greatly appreciated as i have been stuck on how to improve the perfomance for a while now.
The biggest bottleneck will be accessing the images from the device (internal or external). Therefore, you'll want to have as many images in memory as possible (within reason of course). You can do this in a number of ways:
Load perhaps 18 images first (as you said, prebuffer before displaying). Check to make sure the number of images doesn't exceed whatever number you choose though.
Create a 'thumbs.db' type file which will store 100x100 px thumbnails of the bitmaps. This will allow much faster reading since you'd only need to read in one file then extract each bitmap. If the user clicks an image, then request it from the storage. This method requires more work, but will be able to load the thumbnails really fast. You'd probably have to design your own simple file headers, such as:
<file header (size of file, number of images)>
<image header (img id, size in bytes)>
<image bitmap data>
<image header (img id, size in bytes)>
<image bitmap data>
<image header (img id, size in bytes)>
<image bitmap data>
...
How can i get image from image url in image view.
My imageUrl is coming from databaseadapter.
In Fields class LocationImage dataype is string but in setBackgroundResource method it is asking for int value as parameter. LocationImage url is getting from database, so that i've taken that as string variable.
code lines are here.
import java.util.ArrayList;
import android.app.ListActivity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class FindPlaces extends ListActivity{
private SQLiteDatabase DbLoc;
ListView lv;
int val;
private ArrayList<Fields> results = new ArrayList<Fields>();
#Override
public void onCreate(Bundle savedInstance) {
super.onCreate(savedInstance);
setContentView(R.layout.places);
getallLocs();
setListAdapter(new StudentListAdapter(this, val, results));
}
class StudentListAdapter extends ArrayAdapter<Fields>{
private ArrayList<Fields> locationDetails;
private Context mContext;
public StudentListAdapter(Context context,int textViewResourceId, ArrayList<Fields> results) {
super(context, textViewResourceId, results);
// TODO Auto-generated constructor stub
System.out.println("Constructor StudentList Adapter...");
this.locationDetails = results;
mContext = context;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return results.size();
}
#Override
public Fields getItem(int position) {
// TODO Auto-generated method stub
return locationDetails.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return super.getItemId(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v = convertView;
if(v == null){
LayoutInflater vl = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vl.inflate(R.layout.placeslist, null);
}
Fields o = results.get(position);
if (o != null) {
TextView iv = (TextView)v.findViewById(R.id.toptext);
TextView tv_sNo = (TextView)v.findViewById(R.id.toptext1);
ImageView tv_Image = (ImageView)v.findViewById(R.id.Locimage);
iv.setText(o.getLocationName());
//tv_sNo.setText("Status: "+ o.getOrderStatus());
tv_sNo.setText(o.getLocationImage());
tv_Image.setBackgroundResource(o.getLocationImage());
}
DbLoc.close();
return v;
}
}
static class ViewHolder
{
TextView Locationname;
ImageView Locationimage;
}
private void getallLocs() {
// TODO Auto-generated method stub
try {
DatabaseHelper dbHelper = new DatabaseHelper(
this.getApplicationContext());
DbLoc = dbHelper.getWritableDatabase();
Cursor c = DbLoc.rawQuery("SELECT " + DatabaseHelper.LocationName+ " , " + DatabaseHelper.LocationImage + " FROM "
+ DatabaseHelper.LOCATIONTABLE , null);
System.out.println("SELECT " + DatabaseHelper.LocationLang+" , "+DatabaseHelper.LocationLat+" , "+ DatabaseHelper.LocationName
+ " ," + DatabaseHelper.LocationImage + " FROM "
+ DatabaseHelper.LOCATIONTABLE );
if (c != null) {
if (c.moveToFirst()) {
do {
String LocationName= c.getString(c.getColumnIndex("LocationName"));
String Mobile = c.getString(c
.getColumnIndex("LocationImage"));
Fields p = new Fields(LocationName, Mobile);
results.add(p);
} while (c.moveToNext());
}
}
} catch (SQLiteException se) {
Log.e(getClass().getSimpleName(),
"Could not create or Open the database");
}
}
}
if u got image url use the below code to set the image from url to imageview
Bitmap mbmp = BitmapFactory.decodeStream(new java.net.URL("urlname").openStream());
Imageview_ref.setImageBitmap(mbmp);