Load image From basic gallery To imageview in Custom Listview/ - android

First, I'm sorry for my bad English. please excuse me. :)..
I tried to make a custom listView which has ImageView, TextViews, and Button.
So, I want to change image after I click ImageView in listview and select image from gallery. But.. It's really hard to me.
In my code(customAdapter)Adapter class is not Activity, So it cannot call startActivityForResult directly. So I make new Activity(It is GalleryImage.java). and call startActivity using that class. But it is not working. What should I do...
(Error occur in ImageView.setOnClickListner, getView of PhoneBookAdapter)
CustomAdapter Source Code
//..skip import
public class PhoneBookAdapter extends BaseAdapter implements Filterable {
ArrayList<Contact> m_people = new ArrayList<Contact>();
ArrayList<Contact> m_filteredPeople = new ArrayList<Contact>();
private ItemFilter mFilter = new ItemFilter();
private class CustomHolder {
ImageView m_photo;
TextView m_name, m_phone;
Button m_call, m_reserve;
}
public PhoneBookAdapter(ArrayList<Contact> people) {
m_people = people;
m_filteredPeople = people;
}
#Override
public int getCount() {
return m_filteredPeople.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// final int pos = position;
final Context context = parent.getContext();
final TextView phone;
final ImageView photo;
TextView name;
Button call, reserve;
final int pos = position;
CustomHolder holder = null;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.phonebook_list_item, parent,
false);
photo = (ImageView) convertView.findViewById(R.id.iv_photo);
name = (TextView) convertView.findViewById(R.id.tv_name);
phone = (TextView) convertView.findViewById(R.id.tv_phonenumber);
call = (Button) convertView.findViewById(R.id.btn_call);
reserve = (Button) convertView.findViewById(R.id.btn_reserve);
holder = new CustomHolder();
holder.m_photo = photo;
holder.m_name = name;
holder.m_phone = phone;
holder.m_call = call;
holder.m_reserve = reserve;
convertView.setTag(holder);
} else {
holder = (CustomHolder) convertView.getTag();
photo = holder.m_photo;
name = holder.m_name;
phone = holder.m_phone;
call = holder.m_call;
reserve = holder.m_reserve;
}
//photo.setImageResource(m_filteredPeople.get(position).getImage());
name.setText(m_filteredPeople.get(position).getName());
phone.setText(m_filteredPeople.get(position).getNumber());
photo.setOnClickListener(new OnClickListener() {
Activity activity;
int SELECT_IMAGE=90;
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType(android.provider.MediaStore.Images.Media.CONTENT_TYPE);
intent.setData(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
GalleryImage gallery = new GalleryImage(SELECT_IMAGE, photo);
gallery.startActivityForResult(intent, SELECT_IMAGE);
}
});
call.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO make real phone call
Toast.makeText(context, "call " + phone.getText(),
Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Intent.ACTION_CALL, Uri
.parse("tel:" + m_filteredPeople.get(pos).getNumber()));
context.startActivity(intent);
}
});
reserve.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "reserve " + phone.getText(),
Toast.LENGTH_SHORT).show();
}
});
return convertView;
}
#Override
public Filter getFilter() {
return mFilter;
}
private class ItemFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
String filterString = constraint.toString();
FilterResults results = new FilterResults();
final ArrayList<Contact> m_IFpeople = m_people;
int count = m_IFpeople.size();
final ArrayList<Contact> n_people = new ArrayList<Contact>();
String filterableString;
if (filterString != null
&& filterString.trim().equalsIgnoreCase("") != true) {
// Whitespace와 null 제거
// for (int i = 0; i < count; i++) {
// filterableString = m_IFpeople.get(i).getName();
// if (filterableString.indexOf(filterString) >= 0) {
// n_people.add(m_IFpeople.get(i));
// }
// }
for (int i = 0; i < count; i++) {
filterableString = HangulUtils.getHangulInitialSound(
m_IFpeople.get(i).getName(), filterString);
if (filterableString.indexOf(filterString) >= 0) {
n_people.add(m_IFpeople.get(i));
}
}
results.values = n_people;
results.count = n_people.size();
} else {
results.values = m_IFpeople;
results.count = m_IFpeople.size();
}
return results;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
m_filteredPeople = (ArrayList<Contact>) results.values;
notifyDataSetChanged();
}
}
}
GalleryImage.java(new Activity)
//..skip import
public class GalleryImage extends Activity {
final int REQ_CODE_SELECT_IMAGE;
ImageView photo;
public GalleryImage(int codeImage, ImageView m_photo) {
REQ_CODE_SELECT_IMAGE = codeImage;
photo = m_photo;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Intent intent = new Intent(Intent.ACTION_PICK);
// intent.setType(android.provider.MediaStore.Images.Media.CONTENT_TYPE);
// intent.setData(
// android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// startActivityForResult(intent, REQ_CODE_SELECT_IMAGE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQ_CODE_SELECT_IMAGE && resultCode == Activity.RESULT_OK
&& data != null) {
final Uri selectImageUri = data.getData();
final String[] filePathColumn = { MediaStore.Images.Media.DATA };
final Cursor imageCursor = this.getContentResolver()
.query(selectImageUri, filePathColumn, null, null, null);
final int columnIndex = imageCursor.getColumnIndex(filePathColumn[0]);
final String imagePath = imageCursor.getString(columnIndex);
imageCursor.close();
final Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
}
}
}
Thanks for your help. :D.

Solution here is not creating a new instance of Activity but being able to access already existing instance created by Android Framework. Instance of an Activity should never be created by an application programmer.
Best approach would be to add a parameter of type Activity to the constructor of PhoneBookAdapter. Such as:
private Activity activity;
public PhoneBookAdapter(Activity activity, ArrayList<Contact> people) {
this.activity = activity;
m_people = people;
m_filteredPeople = people;
}
You can than then call activity.startActivityForResult on this instance of Activity.
You then pass in the instance of Activity when you create the adapter. In Activity you would simply pass this and in Fragment you can obtain the instance by calling getActivity() method of Fragment class.
As to processing the result of the started Activity you would need to implement this in the Activity or Fragment in which you display the list.

Related

Listview is setting text only for first position

Listview is setting the filename only in first position. Even though on clicking any positions of the listview it sets the filename for the first position only. Please let me know what changes i need to make so that filename will be set properly on clicked item only instead of first item always. Thanks in advance.
I have done same with in Recycle view I am sharing my project code with you
package com.deepak.myapplication;
public class DocumentActivity extends AppCompatActivity implements
View.OnClickListener {
ImageView toolbar_back;
TextView next, tvDocName;
RecyclerView listView;
ArrayList<Survey_vehiclepojo> mylist = new ArrayList();
My_document_adapter adapter;
private int position;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//toolbar_back = ( ImageView ) findViewById(R.id.toolbar_back);
//toolbar_back.setOnClickListener(this);
//next = ( TextView ) findViewById(R.id.next);
//next.setOnClickListener(this);
listView = findViewById(R.id.recycleView);
mylist.add(new Survey_vehiclepojo("Pay Slip", "file1"));
mylist.add(new Survey_vehiclepojo("Insurance", "file2"));
mylist.add(new Survey_vehiclepojo("NA Certificate", "file3"));
mylist.add(new Survey_vehiclepojo("NA 1", "file3"));
mylist.add(new Survey_vehiclepojo("NA 2", "file3"));
mylist.add(new Survey_vehiclepojo("NA 3", "file3"));
listView.setLayoutManager(new LinearLayoutManager(this));
adapter = new My_document_adapter(mylist, DocumentActivity.this);
listView.setAdapter(adapter);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
/*case R.id.toolbar_back:
finish();
break;
case R.id.next:
Intent n=new Intent(DocumentActivity.this, Loan_checklistActivity.class);
startActivity(n);
break;
}*/
}
}
public void Document(int pos) {
position = pos;
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
startActivityForResult(intent, position);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
selectedFile(data, requestCode);
}
private void selectedFile(Intent data, int position) {
String displayName = null;
if (data != null) {
Uri uri = data.getData();
String uriString = null;
if (uri != null) {
uriString = uri.toString();
}
File myFile = new File(uriString);
String path = myFile.getAbsolutePath();
if (uriString != null) {
if (uriString.startsWith("content://")) {
try (Cursor cursor = DocumentActivity.this.getContentResolver().query(uri, null, null, null, null)) {
if (cursor != null && cursor.moveToFirst()) {
displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
tvDocName = findViewById(R.id.tvDocName);
Survey_vehiclepojo selected = mylist.get(position);
selected.setFile1(displayName);
//My_document_adapter.display(displayName,position);
adapter.notifyDataSetChanged();
}
}
}
} else if (uriString.startsWith("file://")) {
displayName = myFile.getName();
tvDocName = findViewById(R.id.tvDocName);
Survey_vehiclepojo selected = mylist.get(position);
selected.setFile1(displayName);
//My_document_adapter.display(displayName,position);
adapter.notifyDataSetChanged();
}
}
}
}
This is Adapter
class My_document_adapter extends
RecyclerView.Adapter<My_document_adapter.ViewHolder>{
ArrayList<Survey_vehiclepojo> mylist;
DocumentActivity documentActivity;
public My_document_adapter(ArrayList<Survey_vehiclepojo> mylist,
DocumentActivity documentActivity) {
this.mylist = mylist;
this.documentActivity = documentActivity;
}
#NonNull
#Override
public My_document_adapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup
parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item, parent, false);
return new My_document_adapter.ViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull My_document_adapter.ViewHolder holder,
final int position) {
holder.name.setText("name"+position);
holder.ivDocument.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View view) {
Log.d("**Postion", "Postion: "+position);
documentActivity.Document(position);
} });
}
#Override
public int getItemCount() {
return mylist.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
final TextView tvDocName,name;
ImageView ivDocument;
public ViewHolder(#NonNull View view) {
super(view);
name = view.findViewById(R.id.tvName);
tvDocName = view.findViewById(R.id.tvDocName);
ivDocument = view.findViewById(R.id.ivDocument);
}
}
}
and my file is selecting see this screenshot

Display ListView of selected data to next Activity in textView

In ListView here i have all my contacts with check box. When i select 2 contacts from list and hit a button then selected list's value should be display in next activity. How can i do this?
Its my Activity class :
public class ContactListActivity extends Activity implements OnItemClickListener {
private ListView listView;
private List<ContactBean> list = new ArrayList<ContactBean>();
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
listView = (ListView) findViewById(R.id.list);
listView.setOnItemClickListener(this);
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
while (phones.moveToNext()) {
String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
ContactBean objContact = new ContactBean();
objContact.setName(name);
objContact.setPhoneNo(phoneNumber);
list.add(objContact);
}
phones.close();
ContanctAdapter objAdapter = new ContanctAdapter(ContactListActivity.this, R.layout.alluser_row, list);
listView.setAdapter(objAdapter);
if (null != list && list.size() != 0) {
Collections.sort(list, new Comparator<ContactBean>() {
#Override
public int compare(ContactBean lhs, ContactBean rhs) {
return lhs.getName().compareTo(rhs.getName());
}
});
AlertDialog alert = new AlertDialog.Builder(ContactListActivity.this).create();
alert.setTitle("");
alert.setMessage(list.size() + " Contact Found!!!");
alert.setButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alert.show();
} else {
showToast("No Contact Found!!!");
}
}
private void showToast(String msg) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
#Override
public void onItemClick(AdapterView<?> listview, View v, int position, long id) {
ContactBean bean = (ContactBean) listview.getItemAtPosition(position);
showCallDialog(bean.getName(), bean.getPhoneNo());
}
private void showCallDialog(String name, final String phoneNo) {
AlertDialog alert = new AlertDialog.Builder(ContactListActivity.this).create();
alert.setTitle("Call?");
alert.setMessage("Are you sure want to call " + name + " ?");
alert.setButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alert.setButton2("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String phoneNumber = "tel:" + phoneNo;
Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse(phoneNumber));
startActivity(intent);
}
});
alert.show();
}
And My Adapter Class to Hold Data is
public class ContanctAdapter extends ArrayAdapter<ContactBean> {
private Activity activity;
private List<ContactBean> items;
private int row;
private LayoutInflater inflater = null;
public ContanctAdapter(Activity act, int row, List<ContactBean> items) {
super(act, row, items);
this.activity = act;
this.row = row;
this.items = items;
this.inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(row, null);
holder.tvname = (TextView) convertView.findViewById(R.id.tvname);
holder.tvPhoneNo = (TextView) convertView.findViewById(R.id.tvphone);
holder.checkbox = (ImageView) convertView.findViewById(R.id.img_checkbox);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
if ((items == null) || ((position + 1) > items.size()))
return convertView;
ContactBean objBean = items.get(position);
holder.checkbox.setSelected((objBean.getIsSelected() == 1) ? true : false);
if (holder.tvname != null && null != objBean.getName() && objBean.getName().trim().length() > 0) {
holder.tvname.setText(Html.fromHtml(objBean.getName()));
}
if (holder.tvPhoneNo != null && null != objBean.getPhoneNo() && objBean.getPhoneNo().trim().length() > 0) {
holder.tvPhoneNo.setText(Html.fromHtml(objBean.getPhoneNo()));
}
holder.checkbox.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
items.get(position).isSelected = (v.isSelected()) ? 0 : 1;
notifyDataSetChanged();
}
});
return convertView;
}
public class ViewHolder {
public TextView tvname, tvPhoneNo;
private ImageView checkbox;
}
}
There is multiple ways to achieve that :
Method 1:
Use static class setter and getter method:
create static class and set values from first activity and get value from second activity
Method 2:
Post your values through the intent
Method 3:
Use database to store data from one activity and get data from other activity
Method 4:
Use Shared preference
Example:
Post values using Intent like this
Post values in Shared preference
Another tutorial for Shared preference
Try this, It may Help you
Add this code in your onitemClicklistener Listview Page
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position,
long id) {
String TVNameitem = ((TextView) view.findViewById(R.id.tvname)).getText().toString();
String TVPhoneitem = ((TextView) view.findViewById(R.id.tvphone)).getText().toString();
Intent intent1 = new Intent(this,NextActivity.class);
intent1.putExtra("STRING_I_NEED_From_TVNAME", TVNameitem );
intent1.putExtra("STRING_I_NEED_From_TVPHONE",TVPhoneitem );
startActivity(intent1);
}
Add this code in your Nextactivty Oncreate for Getting Values, Then Show in Textview
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.find);
Bundle extras = getIntent().getExtras();
String VALUE_1= extras.getString("STRING_I_NEED_From_TVNAME");
String Value_2 =extras.getString("STRING_I_NEED_From_TVPHONE");
TextView Textview1=(TextView)findViewById(R.id.CompanyText);
Textview1.setText(VALUE_1+":"+Value_2);
}
Create getter and setter to share contact details.
public class GetContacts {
private String contactNumber;
private String contactName;
GetContacts(){}// constructor without parameter.
public String getContactNumber() {
return contactNumber;
}
public void setContactNumber(String contactNumber) {
this.contactNumber = contactNumber;
}
public String getContactName() {
return contactName;
}
public void setContactName(String contactName) {
this.contactName = contactName;
}
}
Now set contact values to the setters in GetContact class
create an instance of GetContact class in your first Activity.
GetContact getContact= new GetContact();
And Set Parameters.
getContact.setContactNumber(phoneNumber);
getContact.setContactName(name);
Now its time to get those values in second activity.
create an instance of GetContact class in your second Activity like you did before.
And Get Parameters, and display into TextView.
textView1.setText(getContact.getContactNumber(phoneNumber));
textView2.setText(getContact.getContactName(name));

redirecting itemchecked to a new activity

I have read and tried to follow some other threads from stackoverflow and I am not understanding how to get this to work.
Brief description. I have an activity that loads the contact list into a custom list view. I can select the contacts using a check box. I also have a done button and a cancel button. When the done button is selected it will take all the check box items and display the contacts in a new activity with its own custom list view.
My issue is how to set up my button click to display just the selected contacts.
here is my done button code very rough:
private Button mDoneButton, mCancelButton;
ListView guestListView;
ProgressDialog guestProgressDialog;
ArrayList<String> guestAA = new ArrayList<String>();
ArrayList<String> guestNum = new ArrayList<String>();
//ArrayList<String> guestEmail = new ArrayList<String>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.contacts);
guestListView = (ListView) findViewById(R.id.ListView);
new AsyncTask<Void, Void, Void>() {
#Override
protected void onPreExecute() {
guestProgressDialog = ProgressDialog.show(contactDisplayActivity.this, "Loading...", "Please Wait", true, false);
} //end of on PreExecute method
#Override
protected Void doInBackground(Void... params) {
getGuestContacts();
return null;
} //end of doInBackground method
#Override
protected void onPostExecute(Void result) {
//getGuestContacts();
guestProgressDialog.dismiss();
CustomAdapter guestCustomAdapter = new CustomAdapter(contactDisplayActivity.this);
guestListView.setAdapter(guestCustomAdapter);
} //end of onPostExecute Method
} .execute((Void[]) null);
//Done Button
mDoneButton = (Button)findViewById(R.id.doneButton);
mDoneButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
long [] guestIds = guestListView.getCheckedItemIds();
for (long guestId : guestIds ) {
getGuestContacts();
}
Intent myIntent = new Intent(contactDisplayActivity.this, GuestList.class);
startActivity(myIntent);
}
});
//Cancel Button
mCancelButton = (Button)findViewById(R.id.cancelButton);
mCancelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//mListener.onFragmentInteraction();
//((PlanMeMainActivity) getActivity()).newActivityToLaunch(1);
Intent myIntent = new Intent(contactDisplayActivity.this, EventDetails.class);
startActivity(myIntent);
}
});
}
private void getGuestContacts() {
ContentResolver guestContactResolver = getContentResolver();
Cursor guestCursor = guestContactResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
if (guestCursor.getCount() > 0) {
while (guestCursor.moveToNext()) {
String guestId = guestCursor.getString(guestCursor.getColumnIndex(ContactsContract.Contacts._ID));
String guestName = guestCursor.getString(guestCursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
//String guestEmail = guestCursor.getString(guestCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.ADDRESS));
guestAA.add(guestName);
if (Integer.parseInt(guestCursor.getString(guestCursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor phoneCursor = guestContactResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{guestId}, null);
while (phoneCursor.moveToNext()) {
String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
guestNum.add(phoneNumber);
}
//while (phoneCursor.moveToNext()) {
// String email = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.ADDRESS));
//guestEmail.add(email);
//}
phoneCursor.close();
}
}
}
}
public class CustomAdapter extends BaseAdapter {
private Context mContext;
public CustomAdapter(Context context) {
mContext = context;
}
public int getCount() {
return guestNum.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
final int pos = position;
if (convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(mContext).inflate(R.layout.contacts_display, null);
holder.textviewName = (TextView) convertView.findViewById(R.id.contactsTextView1);
holder.textviewNumber = (TextView) convertView.findViewById(R.id.contactsTextView2);
//holder.textViewEmail = (TextView) convertView.findViewById(R.id.contactsTextView3);
holder.checkbox = (CheckBox) convertView.findViewById(R.id.contactsCheckBox);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.checkbox.setId(position);
holder.textviewName.setId(position);
holder.textviewNumber.setId(position);
//holder.textViewEmail.setId(position);
holder.textviewName.setText(guestAA.get(position));
holder.textviewNumber.setText("No. " + guestNum.get(position));
//holder.textViewEmail.setText(guestEmail.get(position));
holder.id = position;
return convertView;
}
}
static class ViewHolder {
TextView textviewName;
TextView textviewNumber;
//TextView textViewEmail;
CheckBox checkbox;
int id;
}
}
the getGuestContacts method displays the contact list.
Any help or direction would be great. Thanks.

How to add image in custom list view while selecting an image in Intent

I want to put image in my custom listview everytime I select image in intent chooser.
Here I got so far...
public class ItemListBaseAdapter extends BaseAdapter {
private static ArrayList<ItemDetails> itemDetailsrrayList;
private static ArrayList<Uri> imagesUri;
private LayoutInflater l_Inflater;
public ItemListBaseAdapter(Context context, ArrayList<ItemDetails> results, ArrayList<Uri> uri) {
itemDetailsrrayList = results;
imagesUri = uri;
l_Inflater = LayoutInflater.from(context);
}
public int getCount() {
return itemDetailsrrayList.size();
}
public Object getItem(int position) {
return itemDetailsrrayList.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = l_Inflater.inflate(R.layout.item_details_view, null);
holder = new ViewHolder();
holder.txt_itemName = (TextView) convertView.findViewById(R.id.name);
holder.txt_itemDescription = (TextView) convertView.findViewById(R.id.itemDescription);
holder.txt_itemPrice = (TextView) convertView.findViewById(R.id.price);
holder.itemImage = (ImageView) convertView.findViewById(R.id.photo);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
ArrayList<Uri> lastimageUri = itemDetailsrrayList.get(position).getUriImage();
itemDetailsrrayList.get(position).setUriImage(lastimageUri.get(lastimageUri.size() - 1));
holder.itemImage.setImageURI(itemDetailsrrayList.get(position).getImage());
return convertView;
}
This is my Activity can u help me I think the Uri I'd added in the arraylist is been duplicated
public class ListViewImagesActivity extends Activity {
Button btn_GetPhotos;
private String selectedImagePath;
public Uri imageUri;
ArrayList<Uri> imageUris = new ArrayList<Uri>();
ArrayList<ItemDetails> results = new ArrayList<ItemDetails>();
ItemDetails item_details = new ItemDetails();
private final static int SELECT_PICTURE = 1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn_GetPhotos = (Button)findViewById(R.id.btn_GetPhotos);
btn_GetPhotos.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, "Select Photos"), SELECT_PICTURE);
}
});
}
private ArrayList<ItemDetails> GetSearchResults(){
item_details.setUriImage(ImageListUri());
results.add(item_details);
return results;
}
public ArrayList<Uri> ImageListUri(){
imageUris.add(imageUri);
return imageUris;
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE ) {
imageUri = data.getData();
ArrayList<ItemDetails> image_details = GetSearchResults();
//ArrayList<Uri> resultImageUri = ImageListUri();
ItemListBaseAdapter uriItem = new ItemListBaseAdapter(ListViewImagesActivity.this, image_details);
final ListView lv1 = (ListView) findViewById(R.id.listV_main);
lv1.setAdapter(uriItem);
}
}
}
}
but everytime i select an image it displays the current and replace the previous image i selected. So when I select picture 4x the latest selected image appear in my list view 4x. I want to display every image I selected not only the latest image.
I think the problem is caused by
item_details.setUriImage(ImageListUri());
results.add(item_details);
in the function GetSearchResults().
Each time GetSearchResults() is called, item_details is changed to the last selected picture. Be careful that results.add(item_details); will add a reference of item_details rather than the copy of item_details.

onItemClick of items in ListView after Scrolling throws NullPointerException

I have developed an activity that displays all the Contacts of Android phone and I am using a ListView to display the retrieved contacts. The problem is till the time I don't scroll my ListView, whenever I click on any list item - it is displaying that particular contact record details. But, when I scroll and click on any item in the list the application is crashing and throwing a NullPointerException. Can anyone guide me where am I going wrong and how to achieve my result. This may be a duplicate question, but I tried searching all over the net with no success. Below is the code snippet of my activity that displays contacts:
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.contact_manager);
filterText = (EditText) findViewById(R.id.search_box);
filterText.addTextChangedListener(filterTextWatcher);
mContactList = (ListView) findViewById(R.id.contactList);
populateContactList();
}
private void populateContactList()
{
// Another class used to retrieve contacts
ContactAPI contactAPI = ContactAPI.getAPI();
ContentResolver cr = getContentResolver();
contactAPI.setCr(cr);
ArrayList<Contact> a = new ArrayList<Contact>();
a = contactAPI.newContactList(this).getContacts();
contactsAL = new ArrayList<Contact>(a);
adapter = new CustomAdapter(this, R.layout.contact_entry, a);
mContactList.setAdapter(adapter);
mContactList.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
***// The below is the line where I am getting NullPointerException***
LinearLayout l = (LinearLayout) parent.getChildAt(position);
TextView tv = (TextView) l.getChildAt(1);
Intent myIntent = new Intent(view.getContext(), ContactDetailsActivity.class);
Bundle b = new Bundle();
b.putString("ContactID", tv.getText().toString());
myIntent.putExtras(b);
startActivityForResult(myIntent, 0);
}
});
private TextWatcher filterTextWatcher = new TextWatcher()
{
public void afterTextChanged(Editable s)
{
}
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
}
public void onTextChanged(CharSequence s, int start, int before, int count)
{
adapter.getFilter().filter(s);
}
};
protected void onDestroy()
{
super.onDestroy();
filterText.removeTextChangedListener(filterTextWatcher);
}
And below is my custom Adapter class code snippet:
private ArrayList<Contact> original;
private ArrayList<Contact> fitems;
private Filter filter;
private LayoutInflater mInflater;
public CustomAdapter(Context context, int layoutResourceId, ArrayList<Contact> data)
{
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.original = new ArrayList<Contact>(data);
this.fitems = new ArrayList<Contact>(data);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder holder;
if (convertView == null)
{
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.contact_entry, null);
holder = new ViewHolder();
holder.txtName = (TextView) convertView.findViewById(R.id.contactEntryText);
holder.txtID = (TextView) convertView.findViewById(R.id.contactID);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
if(fitems != null)
{
Contact ct = fitems.get(position);
if(ct != null)
{
holder.txtName.setText((String)ct.getDisplayName());
holder.txtID.setText((String)ct.getId());
}
}
//this.notifyDataSetChanged();
return convertView;
}
#Override
public Filter getFilter() {
// TODO Auto-generated method stub
// return super.getFilter();
if (filter == null)
filter = new ContactFilter();
return filter;
}
private class ContactFilter extends Filter
{
#Override
protected FilterResults performFiltering(CharSequence constraint)
{
FilterResults results = new FilterResults();
String prefix = constraint.toString().toLowerCase();
if (prefix == null || prefix.length() == 0)
{
ArrayList<Contact> list = new ArrayList<Contact>(original);
results.values = list;
results.count = list.size();
}
else
{
final ArrayList<Contact> list = new ArrayList<Contact>(original);
final ArrayList<Contact> nlist = new ArrayList<Contact>();
int count = list.size();
for (int i=0; i<count; i++)
{
final Contact cont = list.get(i);
final String value = cont.getDisplayName().toLowerCase();
if (value.contains(prefix))
{
nlist.add(cont);
}
}
results.values = nlist;
results.count = nlist.size();
}
return results;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results)
{
fitems = (ArrayList<Contact>)results.values;
clear();
int count = fitems.size();
for (int i=0; i<count; i++)
{
Contact cont = (Contact)fitems.get(i);
add(cont);
}
}
}
static class ViewHolder {
TextView txtName;
TextView txtID;
}
Can anyone please suggest me where am I doing wrong?
int the onItemClick call CustomAdapter.getItem(int) to retrive the Contact object at position, a use contact to retrive the information you need to start the new activity.
remove setting onitemclicklistener in your main activity.
In CustomAdapter, inside getView method you just add clicklistener to textview
holder.txtName.setOnclickListener(new OnClickListener() {
#Override
public void onClick() {
Intent myIntent = new Intent(view.getContext(), ContactDetailsActivity.class);
Bundle b = new Bundle();
b.putString("ContactID", holder.txtName.getText().toString());
myIntent.putExtras(b);
startActivityForResult(myIntent, 0);
}
})

Categories

Resources