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.
Related
I have been writing a gallery app for Android as I am just beginning with it. I have managed to get it working previously with photos in the drawable folder but now I have implemented getting the images from the storage, I can't seem to figure out how to get the ID to pass to the ShowPic Method.
Here is the code I have for my Main Activity:
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
public class MainActivity extends AppCompatActivity
{
private static final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 1;
private Cursor cursor;
private int columnIndex;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
}
String[] projection = {MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID};
cursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, null, null, MediaStore.Images.Thumbnails._ID + "");
columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID);
GridView imgGridView = findViewById(R.id.imgGridView);
PicAdapter picAdapter = new PicAdapter(MainActivity.this, cursor, columnIndex);
imgGridView.setAdapter(picAdapter);
imgGridView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
}
});
}
public void ShowPic(final int imgID)
{
Intent intent = new Intent(MainActivity.this, OpenPicFull.class);
intent.putExtra("picId", imgID);
startActivity(intent);
}
}
Here is my Adapter:
public class PicAdapter extends BaseAdapter
{
Context mCont;
Cursor mCur;
ImageView mImageView;
int mColumnIndex;
public PicAdapter(Context cont, Cursor cur, int index)
{
mCont = cont;
mCur = cur;
mColumnIndex = index;
}
#Override
public int getCount()
{
return mCur.getCount();
}
#Override
public Object getItem(int position)
{
return position;
}
#Override
public long getItemId(int position)
{
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
mImageView = new ImageView(mCont);
mCur.moveToPosition(position);
int imageID = mCur.getInt(mColumnIndex);
mImageView.setImageURI(Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "" + imageID));
mImageView.setLayoutParams(new GridView.LayoutParams(330, 330));
mImageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
mImageView.setPadding(4, 4, 4, 4);
return mImageView;
}
}
Here is my OpenFullPic class:
public class OpenPicFull extends AppCompatActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_open_pic_full);
ImageView fullImgView = findViewById(R.id.pic_full);
int picID = getIntent().getExtras().getInt("picId");
fullImgView.setImageResource(picID);
}
}
Any help would be greatly appreciated
Thanks
So do the same thing as you did in adapter:
imgGridView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
cursor.moveToPosition(position);
ShowPic(cursor.getInt(columnIndex));
}
});
}
And change your Openfullpic with this:
fullImgView.setImageURI(Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "" + picID));
Also a suggestion try to optimize your image because your code will show memory error if there are lots of image
I had created a custom list view. Please tell me how to delete a entry from listview. I don't know where to write a code for delete button in my code. Please help me. Thanks..
Here is ListAdapater.java class:
package com.example.login;
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class ListAdapater extends ArrayAdapter<String> {
customButtonListener customListner;
public interface customButtonListener {
public void onButtonClickListner(int position, String value);
}
public void setCustomButtonListner(customButtonListener listener) {
this.customListner = listener;
}
private Context context;
private ArrayList<String> data = new ArrayList<String>();
public ListAdapater(Context context, ArrayList<String> dataItem) {
super(context, R.layout.my_custom_list_layout, dataItem);
this.data = dataItem;
this.context = context;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(context);
convertView = inflater.inflate(R.layout.my_custom_list_layout, null);
viewHolder = new ViewHolder();
viewHolder.text = (TextView) convertView.findViewById(R.id.TextView);
viewHolder.button = (Button) convertView.findViewById(R.id.delete);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
final String temp = getItem(position);
viewHolder.text.setText(temp);
viewHolder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (customListner != null) {
customListner.onButtonClickListner(position, temp);
}
}
});
return convertView;
}
public class ViewHolder {
TextView text;
Button button;
}
}
Hompage.java class:
package com.example.login;
import com.example.login.ListAdapater.customButtonListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import android.app.Activity;
import android.database.Cursor;
import android.database.DataSetObserver;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class Hompage extends Activity implements customButtonListener {
ListView listView;
ListAdapater adapter;
ArrayList<String> dataItems = new ArrayList<String>();
SQLiteDatabase db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
db = openOrCreateDatabase("login", MODE_PRIVATE, null);
// My code
String query1 = "SELECT * FROM USERS;";
int c = 0;
try {
Cursor c1 = db.rawQuery(query1, null);
if (c1.moveToFirst()) {
String[] temp2 = new String[c1.getCount()];
do {
String tempo = "Name" + ": " + c1.getString(1) + " " + c1.getString(2) + " \n" + "Gender" + ": "
+ c1.getString(4) + "\n " + "Hobbies" + ": " + c1.getString(8) + " \n" + "User Type" + ": "
+ c1.getString(9);
temp2[c] = tempo;
c++;
// String[] dataArray = temp2;
// List<String> datatemp = Arrays.asList(dataArray);
// dataItems.addAll(datatemp);
} while (c1.moveToNext());
String[] dataArray = temp2;
List<String> datatemp = Arrays.asList(dataArray);
dataItems.addAll(datatemp);
listView = (ListView) findViewById(R.id.listView);
adapter = new ListAdapater(Hompage.this, dataItems);
adapter.setCustomButtonListner(Hompage.this);
listView.setAdapter(adapter);
}
} catch (Exception e) {
}
}
#Override
public void onButtonClickListner(int position, String value) {
//EDITED CODE...
// TODO Auto-generated method stub
String query = "SELECT USER_TYPE FROM USERS WHERE userName = '" + temp + "'";
Cursor c2 = db.rawQuery(query, null);
if (c2.moveToFirst()) {
if (c2.getString(0).equals("Admin")) {
dataItems.remove(position);
adapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "Deleted", Toast.LENGTH_LONG).show();
return;
}
else{
Toast.makeText(getApplicationContext(), "Only Admin can delete", Toast.LENGTH_LONG).show();
}
}
}
}
Try like this
#Override
public void onButtonClickListner(int position, String value) {
// TODO Auto-generated method stub
dataItems.remove(position);
adapter.notifyDataSetChanged();
// call this method
deleteRowFromTable(your_table_name, your_column_name, value)
}
public void deleteRowFromTable(String tableName, String columnName, String keyValue) {
String whereClause = columnName + "=?";
String[] whereArgs = new String[]{String.valueOf(keyValue)};
yourDatabase.delete(tableName, whereClause, whereArgs);
}
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
I have developed a Contacts application. It does everything that a normal contacts application should does. There is always a chance of improvement. I had noticed in Android Emulator that loading for contact images starts when user has settled, he has scrolled the contact list to the area where there are chances are good that he would get contact he is searching for. So, I tried to implement the same thing on my app copy. I have implemented it. Its running very very slow. As I presume, I believe that application is running the thread multiple time even if it has retrieved the image which leads to big lagging. I am aware of the ASync task but just out of curiosity and to check whether it can be done, I don't wish to implement it here. Here is the source code for MainActivity.
package com.example.contact;
import java.io.InputStream;
import java.util.ArrayList;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Contacts;
import android.app.ListActivity;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
public class MainActivity extends ListActivity {
ListView listview;
private boolean mPaused;
private MyAdapter mAdapter;
private View view;
private boolean running = false;
final private ArrayList<String> con_ids = new ArrayList<String>();
private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
listview = getListView();
context = this;
Cursor c = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,
null,
null,
null,
ContactsContract.Contacts.DISPLAY_NAME+" ASC");
if(c!=null)
{
for(c.moveToFirst();!c.isAfterLast();c.moveToNext()){
con_ids.add(c.getString(c.getColumnIndex(ContactsContract.Contacts._ID)));
}
}
mAdapter = new MyAdapter(this, android.R.layout.simple_list_item_1, con_ids);
listview.setAdapter(mAdapter);
listview.setOnScrollListener(makeScrollListener());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void setEnabled(boolean enabled) {
mPaused = !enabled;
}
private AbsListView.OnScrollListener makeScrollListener() {
return new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView absListView, int scrollState) {
setEnabled(scrollState != AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL);
running = false;
}
#Override
public void onScroll(AbsListView absListView, int i, int i1, int i2) {
String log = "";
Log.d(log, "Scroll First Item" + i);
Log.d(log, ""+ listview.getChildCount());
final int want = i;
running = true;
runOnUiThread(new Thread(new Runnable() {
int totalChild = listview.getChildCount();
int first = listview.getFirstVisiblePosition() - listview.getHeaderViewsCount();
int toRetrieve = want-first;
int id;
long con_id;
Bitmap thumbnail;
final ListView list = listview;
#Override
public void run() {
// TODO Auto-generated method stub
while(running)
{
if(!(toRetrieve<0||toRetrieve>=totalChild))
{
id = want+toRetrieve;
con_id = Long.valueOf(con_ids.get(id));
Uri ContactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, con_id);
InputStream stream = ContactsContract.Contacts.openContactPhotoInputStream(context.getContentResolver(), ContactUri);
thumbnail = BitmapFactory.decodeStream(stream);
if(thumbnail == null)
{
toRetrieve++;
continue;
}
else
{
View view = list.getChildAt(toRetrieve);
if(view == null)
{
toRetrieve++;
continue;
}
else
{
ImageView iamge = (ImageView) view.findViewById(R.id.contact_iamge);
iamge.setImageBitmap(thumbnail);
}
toRetrieve++;
}
}
else
{
running = false;
}
}
}
}));
}
};
}
}
Code for MyAdapter,
package com.example.contact;
import java.util.ArrayList;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Contacts;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView.FindListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class MyAdapter extends ArrayAdapter<String> {
private Context context;
private ListView listview;
private ArrayList<String> ids;
private LayoutInflater infl;
private String displayname;
private String maindetail;
private SimplifiedContact contact;
private Drawable drawable;
public MyAdapter(Context context, int ResourceId, ArrayList<String> list)
{
super(context, ResourceId, list);
this.context = context;
ids = list;
infl = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
drawable = context.getResources().getDrawable(R.drawable.person);
}
static class ViewHolder
{
public ImageView image;
public TextView display_name;
public TextView main_detail;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
contact = new SimplifiedContact(context, Long.valueOf(ids.get(position)));
if(row == null)
{
row = infl.inflate(R.layout.single_cell, parent, false);
ViewHolder viewHolder = new ViewHolder();
viewHolder.display_name =(TextView) row.findViewById(R.id.disp_name);
viewHolder.main_detail = (TextView) row.findViewById(R.id.main_detail);
viewHolder.image = (ImageView)row.findViewById(R.id.contact_iamge);
row.setTag(viewHolder);
}
ViewHolder holder = (ViewHolder) row.getTag();
holder.display_name.setText(contact.getDisplayName());
holder.main_detail.setText(contact.getMainDetail());
holder.image.setBackgroundDrawable(drawable);
return row;
}
}
I wish to know, how this lag can be reduced. Thanks in advance.
Why don't you try to take that Thread instance that you are making in runOnUiThread and put It in a field, initializing It in the onCreate. I think that you are creating several thread instaces with no use.
public class MainActivity extends ListActivity {
ListView listview;
private boolean mPaused;
private MyAdapter mAdapter;
private View view;
private boolean running = false;
final private ArrayList<String> con_ids = new ArrayList<String>();
private Context context;
Thread uiThread;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
listview = getListView();
context = this;
Cursor c = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,
null,
null,
null,
ContactsContract.Contacts.DISPLAY_NAME+" ASC");
if(c!=null)
{
for(c.moveToFirst();!c.isAfterLast();c.moveToNext()){
con_ids.add(c.getString(c.getColumnIndex(ContactsContract.Contacts._ID)));
}
}
uiThread = new Thread(new Runnable() {
int totalChild = listview.getChildCount();
int first = listview.getFirstVisiblePosition() - listview.getHeaderViewsCount();
int toRetrieve = want-first;
int id;
long con_id;
Bitmap thumbnail;
final ListView list = listview;
#Override
public void run() {
// TODO Auto-generated method stub
while(running)
{
if(!(toRetrieve<0||toRetrieve>=totalChild))
{
id = want+toRetrieve;
con_id = Long.valueOf(con_ids.get(id));
Uri ContactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, con_id);
InputStream stream = ContactsContract.Contacts.openContactPhotoInputStream(context.getContentResolver(), ContactUri);
thumbnail = BitmapFactory.decodeStream(stream);
if(thumbnail == null)
{
toRetrieve++;
continue;
}
else
{
View view = list.getChildAt(toRetrieve);
if(view == null)
{
toRetrieve++;
continue;
}
else
{
ImageView iamge = (ImageView) view.findViewById(R.id.contact_iamge);
iamge.setImageBitmap(thumbnail);
}
toRetrieve++;
}
}
else
{
running = false;
}
}
}
});
mAdapter = new MyAdapter(this, android.R.layout.simple_list_item_1, con_ids);
listview.setAdapter(mAdapter);
listview.setOnScrollListener(makeScrollListener());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void setEnabled(boolean enabled) {
mPaused = !enabled;
}
private AbsListView.OnScrollListener makeScrollListener() {
return new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView absListView, int scrollState) {
setEnabled(scrollState != AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL);
running = false;
}
#Override
public void onScroll(AbsListView absListView, int i, int i1, int i2) {
String log = "";
Log.d(log, "Scroll First Item" + i);
Log.d(log, ""+ listview.getChildCount());
final int want = i;
running = true;
runOnUiThread(uiThread);
}
};
}
}
I've a custom list view with 4 textViews and 2 buttons,which i am filling up via database,
TV NAME | TV EMAIL | TV NO | TV ID(database primary key,set invisible) | ButtonEDIT | ButtonDelete.
I successfully got the id from the database,which is set as primary key.
Now what i want to do is,when i PRESS ButtonEDIT,it should toast a message something like
"Edit selected for ID :" + TVID.getText().toString(),so basically i want to display the value which is stored in the TVID(i.e. my database id).
But when i am trying to do it,it only displays the firstID (0) for buttons of different rows,please do help asap.
Am linking code below
Custom ListView Adapter :
package com.iwill.Database_add_display;
import java.io.ObjectOutputStream.PutField;
import java.util.ArrayList;
import android.content.Context;
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.TextView;
import android.widget.Toast;
public class MyAdapter extends BaseAdapter
{
private ArrayList<userdetails> data;
private static LayoutInflater minflater=null;
private int[] userArray;
public MyAdapter(Context context,ArrayList<userdetails> results)
{
data = results;
minflater = LayoutInflater.from(context);
}
#Override
public int getCount()
{
return data.size();
}
#Override
public Object getItem(int position)
{
return data.get(position);
}
#Override
public long getItemId(int position)
{
return position;
}
public int getUserArray(int position){
return userArray[position];
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
ViewHolder holder;
if (convertView == null)
{
convertView = minflater.inflate(R.layout.row, null);
holder = new ViewHolder();
holder.tvname = (TextView) convertView.findViewById(R.id.textname);
holder.tvemail = (TextView) convertView.findViewById(R.id.textemail);
holder.tvno = (TextView) convertView.findViewById(R.id.textno);
holder.tvID = (TextView)convertView.findViewById(R.id.textID);
holder.b1 = (Button) convertView.findViewById(R.id.btnEdit);
holder.b2 = (Button) convertView.findViewById(R.id.btnDelete);
//convertView.setTag(holder);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
holder.tvname.setText(data.get(position).getName());
holder.tvemail.setText(data.get(position).getMail());
holder.tvno.setText(data.get(position).getNo());
holder.tvID.setText(String.valueOf(data.get(position).getID()));
return convertView;
}
static class ViewHolder
{
TextView tvname;
TextView tvemail;
TextView tvno;
Button b1;
Button b2;
TextView tvID;
}
}
ListActivity :
package com.iwill.Database_add_display;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class viewnameactivity extends Activity
{
ArrayList<userdetails> mylist = new ArrayList<userdetails>();
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
ListView listView;
MyAdapter adapter;
int pos;
#Override
protected void onCreate(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.viewname);
mDbHelper = new DatabaseHelper(this);
final List<userdetails> List = mDbHelper.selectAll();
for (int i = 0; i < List.size(); i++)
{
//Log.i("List of Data....", List.get(i));
}
for (int j = 0; j < List.size(); j++)
{
mylist.add(List.get(j));
Log.i("List View :", mylist.get(j).toString());
}
listView = (ListView)findViewById(R.id.listView);
adapter = new MyAdapter(this,mylist);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent,View v,int position,long id) {
Toast.makeText(viewnameactivity.this,"Edit button of ID : "+ adapter.getUserArray(position)+" selected.",
Toast.LENGTH_SHORT).show();
pos = adapter.getUserArray(position);
}
});
mDbHelper.close();
Button btnBack = (Button)findViewById(R.id.btnBack);
btnBack.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(viewnameactivity.this,MainActivity.class);
startActivity(i);
}
});
/* Button btnEdit = (Button)findViewById(R.id.btnEdit);
btnEdit.setOnClickListener(new OnClickListener() {
//TextView strID = (TextView)findViewById(R.id.textID);
//long lngID = Long.parseLong(strID.getText().toString());
#Override
public void onClick(View v) {
Toast.makeText(viewnameactivity.this,"Edit button of ID : selected.",
Toast.LENGTH_SHORT).show();
}
});
Button btnDelete = (Button)findViewById(R.id.btndelete);
btnDelete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(viewnameactivity.this,"Delete button of ID : selected.",
Toast.LENGTH_SHORT).show();
}
});*/
}
public void OnClickEdit(View v){
//TextView strID = (TextView)this.findViewById(R.id.textID);
//long lngID = Long.parseLong(strID.getText().toString());
Toast.makeText(viewnameactivity.this,"Edit button of ID : "+ pos +" selected.",
Toast.LENGTH_SHORT).show();
}
public void OnClickDelete(View v){
TextView strID = (TextView)findViewById(R.id.textID);
long lngID = Long.parseLong(strID.getText().toString());
Toast.makeText(viewnameactivity.this,"Delete button of ID :"+ lngID + "selected.",
Toast.LENGTH_SHORT).show();
}
}
DatabaseOpenHelper Class :
package com.iwill.Database_add_display;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DatabaseHelper
{
public static final String KEY_NAME = "NAME";
public static final String KEY_MAIL = "EMAIL";
public static final String KEY_NO ="NO";
public static final String KEY_ID = "ID";
private static final String DATABASE_NAME = "info.db";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "user";
private static String DB_PATH = "/data/data/com.iwill.Database_add_display";
private static String DB_NAME = "info.db";
private static Context context;
private static SQLiteDatabase db;
private static final String TAG = "MEDIA";
public DatabaseHelper(Context context)
{
this.context = context;
OpenHelper openHelper = new OpenHelper(this.context);
this.db = openHelper.getWritableDatabase();
//this.insertStmt = this.db.compileStatement(INSERT);
}
public long insert(String uname,String mail,String no)
{
ContentValues CV = new ContentValues();
CV.put(KEY_NAME, uname);
CV.put(KEY_MAIL , mail);
CV.put(KEY_NO, no);
long rawId = db.insert(TABLE_NAME, null, CV);
return rawId;
}
public void update(long _ID,String updateuname,String updatemail,String updateno)
{
Log.i("tag","_ID"+_ID);
ContentValues cvupdate=new ContentValues();
cvupdate.put(KEY_NAME,updateuname);
cvupdate.put(KEY_MAIL, updatemail);
cvupdate.put(KEY_NO, updateno);
db.update(TABLE_NAME, cvupdate, "_id"+" = ?",new String[]{String.valueOf(_ID)});
Log.i("tag", "Item Updated Database Helper");
}
public void delete(long _ID)
{
this.db.delete(TABLE_NAME, "_id"+" = ?", new String[]{String.valueOf(_ID)});
Log.i("tag", "Item deleted");
}
public List<userdetails> selectAll(){
List<userdetails> list = new ArrayList<userdetails>();
Cursor cursor = this.db.query(TABLE_NAME, new String[] {"_id", "NAME", "EMAIL", "NO"},
null, null, null, null, "_id asc");
if(cursor.moveToFirst()){
do {
userdetails usd= new userdetails();
usd.setName(cursor.getString(1));
usd.setMail(cursor.getString(2));
usd.setNo(cursor.getString(3));
usd.setID(cursor.getLong(0));
list.add(usd);
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return list;
}
public void close(){
db.close();
}
public List<String> selectAllid(){
List<String> list = new ArrayList<String>();
Cursor cursor = this.db.query(TABLE_NAME, new String[] {"_id", "NAME"},
null, null, null, null, "_id asc");
if(cursor.moveToFirst()){
do {
//list.add(cursor.getInt(0) + " "+cursor.getString(1));
list.add(cursor.getString(0));
Log.i("List 0 (id)....", cursor.getString(0));
Log.i("List 1 (URL)....", cursor.getString(1));
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return list;
}
// TESTING
private static class OpenHelper extends SQLiteOpenHelper
{
public OpenHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db)
{
// TODO Auto-generated method stub
String str = "CREATE TABLE IF NOT EXISTS user(_id INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT,EMAIL TEXT,NO TEXT)";
db.execSQL(str);
}
private boolean checkDatabase(){
SQLiteDatabase checkDB = null;
try{
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
}catch(SQLiteException e){
//database does't exist yet.
}
if(checkDB != null){
checkDB.close();
}
return checkDB != null ? true : false;
}
public void createNewDatabase() {
InputStream assetsDB = null;
try {
assetsDB = context.getAssets().open(DB_NAME);
OutputStream dbOut = new FileOutputStream(DB_PATH + DB_NAME);
byte[] buffer = new byte[1024];
int length;
while ((length = assetsDB.read(buffer)) > 0) {
dbOut.write(buffer, 0, length);
}
dbOut.flush();
dbOut.close();
assetsDB.close();
Log.i("New Database created.......", "New database created...");
} catch (IOException e) {
Log.e("Could not create new database...", "Could not create new database...");
e.printStackTrace();
}
}
#Override
public synchronized void close() {
if(db != null){
db.close();
super.close();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
//Log.w("Example", "Upgrading database, this will drop tables and recreate.");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
}
Am kinda beginner and any help would be really appreciated. (:
Try adding this to your adapter:
public class MyAdapter extends BaseAdapter
{
public static HashMap<Integer,String> myList=new HashMap<Integer,String>();
...
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
...
myList.put(position,String.valueOf(data.get(position).getID()));
return convertView;
}
...
}
Now in your activity,
public class viewnameactivity extends Activity
{
...
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent,View v,int position,long id) {
pos = adapter.getUserArray(position);
String TVID=MyAdapter.myList.get(position); // this will give you tvid for each listitem
}
});
...
}