What i am doing::
I am opening a camera onclick of item from actionbar menu
I am capturing the image and setting it in a listview
What is happening::
Say i have captured 10 images and set it in listview
next time i run my code, i am able to find the images i took last
time, and it dosen't start from groundup
What i am trying to do:
say i captured 10 images and set in listview
next time i start the app and start capturing the image it should add
freshly captured images to listview and not display the old images
i am not telling i have to delete these images but i the app i want
to show newly captured images everytime
MainActivity.java
public class MainActivity extends ListActivity {
private static final int CAMERA_CAPTURE = 20;
ArrayList<String> listOfImages;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DisplayCapturedImagesFromCamera();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_camera) {
startCameraCapture();
return true;
}
return super.onOptionsItemSelected(item);
}
private void startCameraCapture() {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
if (cameraIntent.resolveActivity(getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = CreateImageFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(photoFile != null)
{
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
startActivityForResult(cameraIntent, CAMERA_CAPTURE);
}
}
}
private File CreateImageFile() throws IOException
{
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "Image_" + timeStamp + "_";
File storageDirectory = getExternalFilesDir("");
File image = File.createTempFile(imageFileName, ".jpg",storageDirectory);
return image;
}
#Override
public void onActivityResult(final int requestCode, int resultCode, Intent data) {
switch(requestCode)
{
case CAMERA_CAPTURE:
if(resultCode == RESULT_OK)
{
DisplayCapturedImagesFromCamera();
}
break;
}
}
private void DisplayCapturedImagesFromCamera() {
// TODO Auto-generated method stub
File myPath = getExternalFilesDir(null);
listOfImages = new ArrayList<String>();
try
{
for(File f: myPath.listFiles()) {
listOfImages.add(f.getAbsolutePath());
}
AdptAddjobsGallery adapter = new AdptAddjobsGallery(MainActivity.this,listOfImages);
setListAdapter(adapter);
}
catch(Exception ex)
{
Log.w("Error", ex.getMessage());
}
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
// custom dialog
final Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.cust_dialog);
dialog.setTitle("Image ");
Bitmap bitmap = BitmapFactory.decodeFile(listOfImages.get(position));
// set the custom dialog components - text, image and button
ImageView image = (ImageView) dialog.findViewById(R.id.image);
image.setImageBitmap(bitmap);
Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK);
// if button is clicked, close the custom dialog
dialogButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
dialog.dismiss();
}
});
dialog.show();
}
}
AdptAddjobsGallery.java
public class AdptAddjobsGallery extends ArrayAdapter<String> {
private final Activity context;
private final ArrayList<String> listOfImages;
public AdptAddjobsGallery(Activity context, ArrayList<String> listOfImages) {
super(context, R.layout.adpt_addjobs_gallery, listOfImages);
// TODO Auto-generated constructor stub
this.context=context;
this.listOfImages = listOfImages;
}
public View getView(int position,View view,ViewGroup parent) {
ViewHolder holder;
if(view == null)
{
LayoutInflater inflater=context.getLayoutInflater();
view =inflater.inflate(R.layout.adpt_addjobs_gallery, null,true);
holder = new ViewHolder();
holder.imageView = (ImageView) view.findViewById(R.id.selfie);
holder.txtTitle = (TextView) view.findViewById(R.id.fileName);
view.setTag(holder);
}
else
{
holder = (ViewHolder) view.getTag();
}
Bitmap bitmap = BitmapFactory.decodeFile(listOfImages.get(position));
File f = new File(listOfImages.get(position));
holder.txtTitle.setText(f.getName());
holder.imageView.setImageBitmap(bitmap);
return view;
};
}
class ViewHolder {
TextView txtTitle;
ImageView imageView;
}
try this, using file.lastmodified() method.
private ArrayList<String> getRecentImages(long from, long to,
ArrayList<String> list) {
ArrayList<String> sortedList = new ArrayList<String>();
for (int i = 0; i < list.size(); i++) {
File file = new File(list.get(i));
long modified = file.lastModified();
if (modified > from && modified <= to) {
sortedList.add(list.get(i));
}
}
return sortedList;
}
Related
I have an activity with a capture button this catpture button when clicked ,it prompts the user with an alert dialog asking to choose between gallery and camera after making the decision and capturing the image or choosing it the app currently save the image in an image view,now how can i save the images in a gridview in another activity rather than the imageview,and as much as possible avoiding using sqlite?!
mainactivity.java:
public static final int CAMERA_PERM_CODE = 101;
public static final int CAMERA_REQUEST_CODE = 102;
public static final int GALLERY_REQUEST_CODE = 105;
DatabaseHelper mDatabaseHelper;
Cursor data;
Cursor price;
ArrayList<myDataClass> listData;
ArrayAdapter adapter;
ArrayList arrayList;
public SwipeMenuListView mListview;
CustomAdapter custom;
private TextView total;
ImageView camera;
ImageView display1;
String currentPhotoPath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_listitemsbought);
getSupportActionBar().hide();
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
mListview = (SwipeMenuListView) findViewById(R.id.list_items_bought);
mDatabaseHelper = new DatabaseHelper(this);
data = mDatabaseHelper.getDataOfTable();
total = (TextView) findViewById(R.id.totalpriceofitems);
listData = new ArrayList<myDataClass>();
camera = (ImageView) findViewById(R.id.imagetopic);
display1 = (ImageView) findViewById(R.id.displayimage);
display1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Listitemsbought.this,savedPics.class);
overridePendingTransition(R.anim.slide_in,R.anim.slide_out);
startActivity(intent);
}
});
camera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
askCameraPermission();
}
});
// adapter = new ArrayAdapter<String>(this, R.layout.list_boughts,R.id.Name,listData);
populateListView();
final SwipeMenuCreator creator = new SwipeMenuCreator() {
#Override
public void create(SwipeMenu menu) {
// create "delete" item
SwipeMenuItem deleteItem = new SwipeMenuItem(
getApplicationContext());
// set item background
deleteItem.setBackground(new ColorDrawable(Color.rgb(0,
0, 0)));
// set item width
deleteItem.setWidth((250));
// set a icon
deleteItem.setIcon(R.drawable.sym_keyboard_delete_holo_dark);
// add to menu
menu.addMenuItem(deleteItem);
}
};
// set creator
mListview.setMenuCreator(creator);
// Left
mListview.setSwipeDirection(SwipeMenuListView.DIRECTION_LEFT);
}
private void askCameraPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this,new String[] {Manifest.permission.CAMERA}, CAMERA_PERM_CODE);
}else {
alert();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == CAMERA_PERM_CODE){
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
alert();
}
}else {
Toast.makeText(this,"Camera Permission is required to use camera.",Toast.LENGTH_SHORT).show();
}
}
private void alert() {
new AlertDialog.Builder(Listitemsbought.this)
.setTitle(null)
.setMessage("Do you want to open gallery or take a new photo")
// Specifying a listener allows you to take an action before dismissing the dialog.
// The dialog is automatically dismissed when a dialog button is clicked.
.setPositiveButton("Open Camera", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dispatchTakePictureIntent();
}
})
// A null listener allows the button to dismiss the dialog and take no further action.
.setNegativeButton("Gallery", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent gallery = new Intent(Intent.ACTION_PICK,MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(gallery, GALLERY_REQUEST_CODE);
}
})
.setIcon(android.R.drawable.ic_menu_camera)
.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if(requestCode == CAMERA_REQUEST_CODE){
if(resultCode == Activity.RESULT_OK){
File f = new File(currentPhotoPath);
display1.setImageURI(Uri.fromFile(f));
Log.d("tag", "ABsolute Url of Image is " + Uri.fromFile(f));
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
}
if(requestCode == GALLERY_REQUEST_CODE){
if(resultCode == Activity.RESULT_OK){
Uri contentUri = data.getData();
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp +"."+getFileExt(contentUri);
Log.d("tag", "onActivityResult: Gallery Image Uri: " + imageFileName);
display1.setImageURI(contentUri);
}
}
}
private String getFileExt(Uri contentUri) {
ContentResolver c = getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
return mime.getExtensionFromMimeType(c.getType(contentUri));
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
// File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
currentPhotoPath = image.getAbsolutePath();
return image;
}
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.example.medicnes.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, CAMERA_REQUEST_CODE);
}
}
}
private void populateListView(){
while (data.moveToNext()){
listData.add(new myDataClass(data.getString(data.getColumnIndex("Name")),data.getString(data.getColumnIndex("Amount")),data.getString(data.getColumnIndex("Price"))));
}
total.setText(mDatabaseHelper.getPriceSum());
custom = new CustomAdapter(listData, this);
mListview.setAdapter(custom);
//custom.notifyDataSetChanged();
}
public class CustomAdapter extends BaseAdapter
{
private Context context;
private List<String> strings;
public class ViewHolder {
TextView textName;
TextView textAmount;
TextView textPrice;
}
public List<myDataClass> parkingList;
private CustomAdapter(List<myDataClass> apps, Context context) {
this.parkingList = apps;
this.context = context;
arrayList = new ArrayList<myDataClass>();
arrayList.addAll(parkingList);
}
#Override
public int getCount() {
return parkingList.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, final ViewGroup parent)
{
View rowView = convertView;
ViewHolder viewHolder = null;
if (rowView == null) {
LayoutInflater inflater = getLayoutInflater();
rowView = inflater.inflate(R.layout.list_boughts, parent, false);
viewHolder = new ViewHolder();
viewHolder.textName = rowView.findViewById(R.id.Name);
viewHolder.textAmount = rowView.findViewById(R.id.sdadprice);
viewHolder.textPrice = rowView.findViewById(R.id.dfsdfad);
rowView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
// here setting up names and images
viewHolder.textName.setText(parkingList.get(position).getProdaname() + "");
viewHolder.textAmount.setText(parkingList.get(position).getAmount());
viewHolder.textPrice.setText(parkingList.get(position).getPrice());
System.out.println(parkingList.get(position).getPrice());
mListview.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {
// delete
mDatabaseHelper.delete(parkingList.get(position).getProdaname());
System.out.println(parkingList.get(position).getProdaname());
listData.remove(index);
custom.notifyDataSetChanged();
populateListView();
// false : close the menu; true : not close the menu
return false;
}
});
return rowView;
}
}
Create a Offline database in scoped storage but this database will be deleted when user uninstall the app.
File mainfolder = getDir("datafolder", Context.MODE_PRIVATE);
Bitmap bitmap = BitmapFactory.decode(currentphotopath);
String name = new SimpleDateFormate("dd_mm_yyyy_hhss") + ".jpg"; // this or generate new file name each time user uploads.
File file = new File(mainfolder, name);
FileOutputStreme fout = new FIleOutputStreme(file);
bitmap.compress(jpg, 100, fout);
fout.close();
//listing all the files in mainfolder and set to gridview
File[] files = mainfolder.listFiles();
customView cview = new customView(this, files);
gridview.setAdapter(cview);
//adapter customview class
public class customview extends ArrayAdapter{
private Files[] files;
.
.`
.
public customview (Activity activity, Files[] fls){
files = fls;
}
#Override
public View getView(int position, View convertView, final ViewGroup parent){
Bitmap bitmap = BitmapFactory.decode(files[position].getAbsolutePath());
imageview.setImageBitmap(bitmap);
}
}
I have a list view with image.I want to change list item image on onActivityResult
of image capturing .I get the image file bitmap but when I change the list items image the list view image does not change.
final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),
options);
imageView1.setImageBitmap(bitmap);//there a bitmap exist---
dataAdapter.taskList.get(0).setImgBitmap(bitmap);
//this is not changing list image.why???????
dataAdapter.notifyDataSetChanged();
here the imageview1 has a bitmap and I set it to first item of list using CustomAdapter class's ArrayList<Task> taskList parameter.
here full sample code
NotifyAcitivity.java
package com.aci.notification;
public class NotifyActivity extends Activity {
// Activity request codes
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
public static final int MEDIA_TYPE_IMAGE = 1;
// directory name to store captured images and videos
private static final String IMAGE_DIRECTORY_NAME = "Hello Camera";
private Uri fileUri; // file url to store image/video
private ImageView imageView1;
Bitmap bm, bm2;
private Button btnCapturePicture;
ArrayList<Task> taskList = new ArrayList<Task>();
TextView tv;
CustomAdapter dataAdapter = null;
Button btnSave;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notify);
btnCapturePicture = (Button) findViewById(R.id.btnCapturePicture);
imageView1 = (ImageView) findViewById(R.id.imageView1);
tv = (TextView) findViewById(R.id.textViewtest);
btnSave = (Button) findViewById(R.id.button1);
listView = (ListView) findViewById(R.id.listView1);
new BitmapFactory();
bm = BitmapFactory.decodeResource(getApplicationContext()
.getResources(), R.drawable.ic_launcher);
bm2 = BitmapFactory.decodeResource(getApplicationContext()
.getResources(), R.drawable.bydefault);
Task task;
task = new Task(0, "This is task1", "/pictures/hello camera/", bm,false);
taskList.add(task);
task = new Task(1, "This is task2", "/pictures/hello camera/", bm,false);
taskList.add(task);
task = new Task(0, "This is task3", "/pictures/hello camera/", bm,false);
taskList.add(task);
task = new Task(0, "This is task4", "/pictures/hello camera/", bm2,false);
taskList.add(task);
task = new Task(0, "This is task5", "/pictures/hello camera/", bm,false);
taskList.add(task);
dataAdapter = new CustomAdapter(this, R.layout.list_style, taskList);
listView.setAdapter(dataAdapter);
}
/**
* Receiving activity result method will be called after closing the camera
* */
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// if the result is capturing Image
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// successfully captured the image
// display it in image view
previewCapturedImage();
}
}
}
/**
* Display image from a path to ImageView
*/
private void previewCapturedImage() {
try {
imageView1.setVisibility(View.VISIBLE);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),
options);
imageView1.setImageBitmap(bitmap);
dataAdapter.taskList.get(0).setImgBitmap(bitmap);
dataAdapter.notifyDataSetChanged();
} catch (NullPointerException e) {
e.printStackTrace();
}
}
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
}
CustomAdapter.java
public class CustomAdapter extends ArrayAdapter<Task> {
public ArrayList<Task> taskList;
Context context;
public CustomAdapter(Context context, int resource, ArrayList<Task> taskList) {
super(context, resource, taskList);
this.context=context;
// TODO Auto-generated constructor stub
this.taskList = new ArrayList<Task>();
this.taskList.addAll(taskList);
}
private class ViewHolder {
CheckBox task;
ImageView imageView;
int task_id;
Button imageCaptureBtnButton;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder viewHolder = null;
Log.v("ConvertView", String.valueOf(position));
if (convertView == null) {
LayoutInflater vi =(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.list_style, null);
viewHolder = new ViewHolder();
viewHolder.task_id=taskList.get(position).getTask_id();//set task id of that task
viewHolder.task = (CheckBox) convertView.findViewById(R.id.checkBox1);
viewHolder.imageView=(ImageView) convertView.findViewById(R.id.imgPreview);
viewHolder.imageCaptureBtnButton=(Button) convertView.findViewById(R.id.btnCapturePicture);
viewHolder.imageView.setImageBitmap(taskList.get(position).getImgBitmap());
convertView.setTag(viewHolder);
viewHolder.task.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
Task aTask =(Task) cb.getTag();
Toast.makeText(context,
"Clicked on Checkbox: " + cb.getText() + " is "
+ cb.isChecked(), Toast.LENGTH_LONG).show();
aTask.setSelected(cb.isChecked());
}
});
viewHolder.imageCaptureBtnButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(context, "dddd", Toast.LENGTH_LONG).show();
}
});
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
Task aTask = taskList.get(position);
viewHolder.task.setText(taskList.get(position).getTask());
viewHolder.task.setChecked(taskList.get(position).isSelected());
viewHolder.task.setTag(aTask);
return convertView;
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public int getCount() {
return taskList.size();
}
#Override
public Task getItem(int arg0) {
return null;
}
}
Task.java
public class Task {
int task_id = 0;
String task = null;
String imageURL=null;
Bitmap imgBitmap;
boolean selected=false;
public Task(int task_id, String task, String imageURL,Bitmap imgBitmap, boolean selected) {
super();
this.task_id = task_id;
this.task= task;
this.imageURL=imageURL;
this.imgBitmap=imgBitmap;
this.selected = selected;
}
//all getters and setters here
}
I have lost my days .please help me.
After a long time I found my own question answer.
The code is not fully matched to this question because answer is from my another project.I am just giving the way I succeeded.
Step 1:
When an image is captured I call imagedata(Bitmap bitmap).It convert each bitmap to base_64 string and this method adds new image to a list as array element of type ByteDrawable.
I create new adapter object again and set that adapter to the
listview.
private void imagedata(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
// Must compress the Image to reduce image size to make upload easy
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] byte_arr = stream.toByteArray();
// Encode Image to String
image_data = Base64.encodeToString(byte_arr, 0);
byteDrawableList.add(new ByteDrawable(image_data));
listAdapter = new CustomAdapter(this);
listView.setAdapter(listAdapter );
}
public class ByteDrawable {
String imageAsBytes;
public ByteDrawable(String imageAsBytes) {
this.imageAsBytes = imageAsBytes;
}
}
Step 2:
Then I populate my list from that arraylist and in Adapter class's constructor I convert the base_64 string to bitmap and add element to a local arraylist items<Item>, then in getview() method I used items to create listview.
private class CustomAdapter extends ArrayAdapter<ByteDrawable>{
public CustomAdapter(Context context, int resource, ArrayList<ByteDrawable > byteDrawableList) {
super(context, resource, byteDrawableList);
this.context=context;
this.byteDrawableList= new ArrayList<ByteDrawable >();
this.byteDrawableList.addAll(byteDrawableList);
inflater = LayoutInflater.from(context);
long k = 0;
for (ByteDrawable bd : byteDrawableList) {
String base = bd.getImageByteString();
byte[] imageAsBytes = Base64.decode(base.getBytes(),
Base64.DEFAULT);
items.add(new Item(k, BitmapFactory.decodeByteArray(
imageAsBytes, 0, imageAsBytes.length)));
k++;
}
}
private class Item {
final long itmeid;
final Bitmap drawabledata;
Item(long id, Bitmap bitmap) {
this.itmeid = id;
this.drawabledata = bitmap;
}
}
public View getView(final int position, View view, ViewGroup viewGroup) {
/* follow normal way to set data to list item*/
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int i) {
return items.get(i);
}
#Override
public long getItemId(int i) {
return items.get(i).itmeid;
}
}
Hope this will help someone if they face same problem.
I need to get the selected contacts from the SelectContactsActivity and display those selected contacts in ContactListActivity. But i am not getting the contacts which i selected.
my SelectContactsActivity.java
public class SelectContactsActivity extends Activity{
private ListView select_listView;
private EditText search_edt;
private List<ContactBean> list = new ArrayList<ContactBean>();
private ContanctAdapter objAdapter;
//private boolean UpdateAB;
private String groupName;
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.activity_selectcontacts);
select_listView = (ListView) findViewById(R.id.select_contacts_listView);
search_edt = (EditText) findViewById(R.id.inputSearch);
Intent intent = getIntent();
groupName = intent.getStringExtra("group_name");
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();
objAdapter = new ContanctAdapter(SelectContactsActivity.this, R.layout.select_contacts_list_item, list, updateAB);
select_listView.setAdapter(objAdapter);
objAdapter.setEditMode(true);
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());
}
});
} else {
showToast("No Contact Found!!!");
}
select_listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> listview, View v,
int position, long id) {
// TODO Auto-generated method stub
objAdapter.setChecked(position, v);
objAdapter.notifyDataSetChanged();
invalidateOptionsMenu();
}
});
/**
* Enabling Search Filter
* */
// Capture Text in EditText
search_edt.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
String text = search_edt.getText().toString().toLowerCase(Locale.getDefault());
objAdapter.filter(text);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
});
}
private void showToast(String msg) {
// TODO Auto-generated method stub
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
#Override
protected void onResume() {
super.onResume();
objAdapter.setEditMode(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.actions_select_contacts_list, menu);
MenuItem item = null;
if (select_listView.getCount() > 0) {
if(objAdapter.isCheckItem()){
menu.findItem(R.id.action_done).setEnabled(true).setVisible(true);
item = menu.add(Menu.NONE, R.id.action_done, Menu.NONE,R.string.done);
}else{
menu.findItem(R.id.action_done).setEnabled(false).setVisible(false);
}
}else{
menu.findItem(R.id.action_done).setEnabled(false).setVisible(false);
}
Log.v(this.getClass().getName(), "Check update..."+objAdapter.isCheckItem());
return true;
}
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch (item.getItemId()) {
case R.id.action_done:
StringBuilder _itemBuilder = new StringBuilder();
objAdapter.saveSelected(groupName);
invalidateOptionsMenu();
finish();
break;
}
return true;
}
Handler updateAB = new Handler(){
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
invalidateOptionsMenu();
Log.v(SelectContactsActivity.this.getClass().getName(), "Check invalidate cal;l");
}
};
}
My ContanctAdapter.java
public class ContanctAdapter extends ArrayAdapter<ContactBean> {
public Context mcontext;
private List<ContactBean> items;
private ContactBean objBean;
private boolean isEdit;
private ArrayList<ContactBean> arraylist;
public boolean[] contactCheckArray;
private LayoutInflater inflater;
public ContanctAdapter(Activity act, int row, List<ContactBean> items, Handler handler) {
super(act, row, items);
this.mcontext = act;
inflater = LayoutInflater.from(act);
this.items = items;
this.arraylist = new ArrayList<ContactBean>();
this.arraylist.addAll(items);
contactCheckArray = new boolean[items.size()];
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final View view = null==convertView?inflater.inflate(R.layout.select_contacts_list_item, null):convertView;
ViewHolder holder = null;
if (null == view.getTag()) {
holder = new ViewHolder();
holder.tvname = (TextView) view.findViewById(R.id.tvname);
holder.tvPhoneNo = (TextView) view.findViewById(R.id.tvphone);
holder.iv = (ImageView)view.findViewById(R.id.contacts_imageview);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
objBean = items.get(position);
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()));
}
if (isEdit) {
holder.iv.setVisibility(View.VISIBLE);
} else {
holder.iv.setVisibility(View.GONE);
}
return view;
}
public void setEditMode(boolean isEdit) {
this.isEdit = isEdit;
}
public boolean isCheckItem () {
for (boolean value : contactCheckArray) {
if (value)
return true;
}
return false;
}
public void setChecked(final int pos, final View row) {
if (!contactCheckArray[pos]) {
((ViewHolder) row.getTag()).iv.setImageResource(R.drawable.setting_check);
contactCheckArray[pos] = true;
notifyDataSetChanged();
} else {
contactCheckArray[pos] = false;
((ViewHolder) row.getTag()).iv.setImageResource(R.drawable.setting_check_box_bg);
notifyDataSetChanged();
}
}
public class ViewHolder {
public ImageView iv;
public TextView tvname, tvPhoneNo;
}
public void saveSelected(String groupName){
StringBuilder _itemBuilder = new StringBuilder();
ProfilesDatabaseHelper DbHelper = new ProfilesDatabaseHelper(mcontext);
for (int i = 0; i < arraylist.size(); i++) {
if (contactCheckArray[i]) {
_itemBuilder.append("'"+ arraylist.get(i).getPhoneNo() + "'" + ",");
//Toast.makeText(mcontext, "Selected Contacts : "+_itemBuilder.toString(), Toast.LENGTH_LONG).show();
DbHelper.executeSQL("INSERT INTO GroupsTable (GroupName, ContactName, PhoneNumber) VALUES ('"+groupName+"', '"+arraylist.get(i).getName()+"','"+ arraylist.get(i).getPhoneNo()+ "')");
}
}
if (_itemBuilder.length() > 0) {
_itemBuilder.deleteCharAt(_itemBuilder.length() - 1);
Log.v(getClass().getName(), "Check..selected contactss :"+ _itemBuilder.toString());
//Toast.makeText(getApplicationContext(), "Selected Contacts : "+_itemBuilder.toString(), Toast.LENGTH_LONG).show();
// This will clear the buffer
_itemBuilder.delete(0, _itemBuilder.length());
}
}
public void filter(String charText ) {
// TODO Auto-generated method stub
charText = charText.toLowerCase(Locale.getDefault());
items.clear();
if (charText.length() == 0) {
items.addAll(arraylist);
}else {
for (ContactBean ob : arraylist) {
if (ob.getName().toLowerCase(Locale.getDefault()).contains(charText)) {
items.add(ob);
}
}
}
notifyDataSetChanged();
}
}
And if i click on the first item in SelectContactsList activity automatically my 9th and 17th and 25th, 33.... contacts also selected and its returning one contact which i didn't select to the Contactslist activity. And i am not getting any errors. Any one help me to solve this issue.
Your issue is with this line in the first snippet, in your listener.
objAdapter.setChecked(position, v);
POSITION is different from ID. A ListView only renders the number of items that it needs to show. The position is the position in the rendered list.
Change it to id.
See this post as well for a better explanation of this with in-depth examples: Create a ListView with selectable rows/change background color of ListView rows when clicked
In LoginActivity showing single button
And want to launch UploadActivity, if UploadActivity's List contain any data else show alert "No Images found in UploadActivity"
In short,
i just want to show alert dialog if upload activity has no data in a List else Launch UploadActivity...
btnCheckUpload.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
AlertDialog.Builder alertdialog = new AlertDialog.Builder(LoginActivity.this);
alertdialog.setTitle(getResources().getString(R.string.app_name));
alertdialog.setMessage("No Images found in UploadActivity");
alertdialog.setPositiveButton("OK", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
alertdialog.show();
}
}
});
UploadActivity.java:-
public class UploadActivity extends Activity {
final private static int DIALOG_LOGIN = 1;
EditText editPersonName, editPersonaEmail, editPersonTelephone, parental_email ;
TextView editImageName ;
String fileName;
static ListView lstView;
private Handler handler = new Handler();;
static List <String> ImageList;
String strPath;
CheckBox chkOption3;
TextView tv1, tv2;
CheckBox chkOption1, chkOption2 ;
int position ;
static File f1;
static String folder = null ;
Intent i;
Intent intent ;
TextView textHeading1;
static File[] files;
static File file ;
static List <String> it ;
static String textHeading = null;
// new Class DB
final myDBClasss myDb = new myDBClasss(this);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload);
textHeading1 = (TextView) findViewById(R.id.txtEventNameDate1);
textHeading1.setText(CameraLauncherActivity.folder);
/*** Get Images from SDCard ***/
ImageList = getSD();
// ListView and imageAdapter
lstView = (ListView) findViewById(R.id.listView1);
lstView.setAdapter(new ImageAdapter(this));
}
public static List <String> getSD()
{
it = new ArrayList <String>();
String string = "/mnt/sdcard/Pictures/Awesome/";
f1 = new File (string+ CameraLauncherActivity.folder+ "/");
files = f1.listFiles ();
for (int i = 0; i < files.length; i++)
{
file = files[i];
Log.d("Count",file.getPath());
it.add (file.getPath());
}
return it;
}
public class ImageAdapter extends BaseAdapter
{
private Context context;
public ImageAdapter(Context c)
{
// TODO Auto-generated method stub
context = c;
}
public int getCount() {
// TODO Auto-generated method stub
return ImageList.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.list_upload, null);
}
// ColImgName
TextView txtName = (TextView) convertView.findViewById(R.id.ColImgName);
strPath = ImageList.get(position).toString();
// Get File Name
fileName = strPath.substring( strPath.lastIndexOf('/')+1, strPath.length() );
file = new File(strPath);
#SuppressWarnings("unused")
long length = file.length();
txtName.setText(fileName);
// Image Resource
ImageView imageView = (ImageView) convertView.findViewById(R.id.ColImgPath);
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
Bitmap bm = BitmapFactory.decodeFile(strPath,options);
imageView.setImageBitmap(bm);
// ColStatus
final ImageView txtStatus = (ImageView) convertView.findViewById(R.id.ColStatus);
txtStatus.setImageResource(R.drawable.bullet_button);
// progressBar
final ProgressBar progress = (ProgressBar) convertView.findViewById(R.id.progressBar);
progress.setVisibility(View.GONE);
//btnUpload
final ImageButton btnUpload = (ImageButton) convertView.findViewById(R.id.btnUpload);
btnUpload.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Upload
btnUpload.setEnabled(false);
startUpload(position);
}
});
return convertView;
}
}
lstView.getChildCount() will Returns the number of children in the group.that is you view.so store the refrence of your ImageAdapter
and then use adapter.getcount();
you can also check for your ImageList size as well.
instead of
if (UploadActivity.lstView.getChildCount() > 0)
use
if (imageList.size) > 0)
or
if (adapter.getcount() > 0)
ListView is a View, calling listView.getChildCount() means :
<ListView>
<TextView></TextView>
</ListView>
It doesn't make sense because a ListView have no child. What you need to Do is call your Adapter.getCount();
If you created your Adapter well it should work just fine.
Make your getSD() as public static and trying to access it in your LogincActivity as below:
btnCheckUpload.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
List<String> dt=new ArrayList<String>();
dt=UploadActivity.getSD();
if (dt.size()> 0) {
Intent intentUpload = new Intent(LoginActivity.this, UploadActivity.class);
startActivity(intentUpload);
} else {
AlertDialog.Builder alertdialog = new AlertDialog.Builder(LoginActivity.this);
alertdialog.setTitle(getResources().getString(R.string.app_name));
alertdialog.setMessage("No Images found in UploadActivity");
alertdialog.setPositiveButton("OK", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
alertdialog.show();
}
}
});
EDITED:
Another way is check the condition in your UploadActivity only and if no data found then simply show alert and onclick of alert finish the activity as below:
ImageAdapter adapter=new ImageAdapter(this);
if(adapter.getCount()>0)
{
// ListView and imageAdapter
lstView = (ListView) findViewById(R.id.listView1);
lstView.setAdapter(new ImageAdapter(this));
else
{
AlertDialog.Builder alertdialog = new AlertDialog.Builder(LoginActivity.this);
alertdialog.setTitle(getResources().getString(R.string.app_name));
alertdialog.setMessage("No Images found in UploadActivity");
alertdialog.setPositiveButton("OK", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which) {
finish(); //Finish your UploadActivity here.
}
});
alertdialog.show();
}
I have a custom listview with custom adapter extending BaseAdapter if i add items to this list view in OnCreate method they show up in list, but if i add them from other methods like a packet listener method then items do not show up , on the screen below this listview there is a textbox if i select textbox to entertext using virtual keyboard immediately the listview gets populated with previousely inserted items which didnt show up. This activity is a chat window basically
I have tried calling notifyDataSetChanged, invalidate on Layout or on listview but nothing helped.
What i think is i need to have a way to refresh activity , as same thing must be happening when the virtual keyboard pops up .
Help will be highly appreciated
Thanks
Code:
package com.arounds;
public class ChatActivity extends Activity implements OnClickListener,PacketListener{
private ListView chatView;
private ChatListViewCustomAdapter adapter;
private String user;
private XMPPConnection connection;
private Conversation conv;
private ChatActivity selfRef = this;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chat_win);
AroundApplication app = (AroundApplication) this.getApplicationContext();
connection = app.getConnection();
chatView = (ListView) findViewById(R.id.conversationList);
adapter = new ChatListViewCustomAdapter(this);
chatView.setAdapter(adapter);
// set send btn listener
ImageButton send = (ImageButton)findViewById(R.id.imgBtnSend);
send.setOnClickListener(this);
ImageButton smiley = (ImageButton)findViewById(R.id.imgBtnSmiley);
smiley.setOnClickListener(this);
// get the parameter passed by previouse activity
Bundle b = this.getIntent().getExtras();
String temp = b.getString("user");
user = temp;
TextView v = (TextView)this.findViewById(R.id.txtViewTitle_chat);
v.setText(temp);
v = (TextView)this.findViewById(R.id.txtViewDescription_chat);
temp = b.getString("status");
v.setText(temp);
//chatView.setOnItemClickListener(this);
HashMap convs = app.getConversations();
if(convs.containsKey(user) == true)
conv = (Conversation) convs.get(user);
else {
conv = new Conversation();
convs.put(user,conv);
}
PacketFilter filter = new MessageTypeFilter(Message.Type.chat);
connection.addPacketListener(this,filter);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.getId() == R.id.imgBtnSend)
{
EditText msg = (EditText)this.findViewById(R.id.editChat);
String s = msg.getText().toString();
Message message = new Message(user, Message.Type.chat);
message.setBody(s);
connection.sendPacket(message);
ArrayList<ChatMessage> m = conv.messages;
String currentDate = DateFormat.getDateInstance().format(new Date());
m.add(new ChatMessage(s,currentDate));
adapter.addItem("I said",s,currentDate,Constants.SEND_LIST_TYPE);
//adapter.notifyDataSetChanged();
}
else
{
//View view = this.findViewById(R.id.linerLayoutChat);
chatView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
#Override
public void processPacket(Packet packet) {
// TODO Auto-generated method stub
System.out.println("in");
Message message = (Message) packet;
if (message.getBody() != null) {
System.out.println("in1");
String fromName = StringUtils.parseBareAddress(message.getFrom());
ArrayList<ChatMessage> m = conv.messages;
String currentDate = DateFormat.getDateInstance().format(new Date());
m.add(new ChatMessage(message.getBody(),currentDate));
adapter.addItem(fromName+" said",message.getBody(),currentDate,Constants.REC_LIST_TYPE);
//chatView.postInvalidate();
}
}
}
Adapter class:
public class ChatListViewCustomAdapter extends BaseAdapter
{
public ArrayList<ChatListItem> items;
public Activity context;
public LayoutInflater inflater;
public Boolean temp=false;
public ChatListViewCustomAdapter(Activity context) {
super();
this.context = context;
this.items = new ArrayList<ChatListItem>();
this.inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return items.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public static class ViewHolder
{
TextView txtViewTitle;
TextView txtViewDescription;
TextView txtViewDate;
}
public void addItem(String title,String desc,String d,int type)
{
ChatListItem item = new ChatListItem(title,desc,d,type);
items.add(item);
notifyDataSetChanged();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ChatListItem item = items.get(position);
ViewHolder holder;
System.out.println("Title:"+item.title+" type:"+item.type);
if(convertView==null)
{
holder = new ViewHolder();
int type = this.getItemViewType(position);
if(type == 0)
{
convertView = inflater.inflate(R.layout.list_item_even, null);
holder.txtViewTitle = (TextView) convertView.findViewById(R.id.txtViewTitleEven);
holder.txtViewDescription = (TextView) convertView.findViewById(R.id.txtViewDescriptionEven);
holder.txtViewDate = (TextView) convertView.findViewById(R.id.txtViewDateEven);
}
else
{
convertView = inflater.inflate(R.layout.list_item_odd, null);
holder.txtViewTitle = (TextView) convertView.findViewById(R.id.txtViewTitleOdd);
holder.txtViewDescription = (TextView) convertView.findViewById(R.id.txtViewDescriptionOdd);
holder.txtViewDate = (TextView) convertView.findViewById(R.id.txtViewDateOdd);
}
convertView.setTag(holder);
}
else
holder=(ViewHolder)convertView.getTag();
holder.txtViewTitle.setText(item.title);
holder.txtViewDescription.setText(item.desc);
holder.txtViewDate.setText(item.date);
return convertView;
}
#Override
public int getItemViewType(int position) {
ChatListItem item = items.get(position);
return item.type;
}
#Override
public int getViewTypeCount() {
return 2;
}
}
Handle all the updates within your Adapter and ensure you invoke notifyDataSetChanged() after you update it (within your Adapter)?
In cases where notifyDataSetChanged() does not work, re-set the adapter on the ListView by calling ListView.setAdapter() with the same Adapter again. This should refresh the view.
the only thing I can see not right are these methods:
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
These methods should return proper values.
items.get(position) and position respectively.