Android App - trouble setting AlertDialog view with custom ListView - java

I am trying to use the following code to put a ListView with a custom ListAdapter into an AlertDialog. Currently the activity will display the AlertDialog, but with no ListView displayed:
public class EditMindMapActivity extends Activity {
private Button NewObjectButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_mind_map);
// Assign external resources
NewObjectButton = (Button)findViewById(R.id.button9);
// Set the listener for the interact button
NewObjectButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//create text field for user input
final EditText textField = new EditText(EditMindMapActivity.this); //the ed..this might be wrong
/* Create selection images ListView */
//just for placeholding really
ListView listView1 = new ListView(EditMindMapActivity.this);
listView1.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
listView1.setCacheColorHint(00000000);
ArrayList<Drawable> images = new ArrayList<Drawable>();
//fill up the list of images
images.add(getResources().getDrawable( R.drawable.shape01 ));
images.add(getResources().getDrawable( R.drawable.shape02 ));
images.add(getResources().getDrawable( R.drawable.shape03 ));
images.add(getResources().getDrawable( R.drawable.shape04 ));
images.add(getResources().getDrawable( R.drawable.shape05 ));
images.add(getResources().getDrawable( R.drawable.shape06 ));
images.add(getResources().getDrawable( R.drawable.shape07 ));
images.add(getResources().getDrawable( R.drawable.shape08 ));
// add to the list here
CustomListAdapter01 adapter = new CustomListAdapter01(images, EditMindMapActivity.this);
listView1.setAdapter(adapter);
listView1.setOnItemClickListener(new ListView.OnItemClickListener()
{
public void onItemClick(AdapterView<?> listView, View itemView, int position, long itemId)
{
//nothing
//probably set some variable
}
});
/* ^^^^^^^^^^^ */
/* Display Select Image AlertDialog */
//may want to make this an external function
// 1. Instantiate an AlertDialog.Builder with its constructor
final AlertDialog.Builder builder = new AlertDialog.Builder(EditMindMapActivity.this);
// 2. Chain together various setter methods to set the dialog characteristics
builder.setMessage("where will this be?")
.setView( listView1 )
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//since the user hit 'ok', set imageLocation and ask the user to name the object ->
//this int holds the selected image location
final int imageLocation = R.drawable.shape05;
//final int imageLocation = listView1
/* Display Input Text AlertDialog */
//might have problem because of overwriting previous builder methods
builder.setMessage("Enter a name for the New Object")
.setView(textField)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//since the user hit 'ok', create the object specified ->
//need this to reference mindMapView and access it's arrays
MindMapView mindMapView = (MindMapView)findViewById(R.id.MindMapView);
//get the string from the input, set it to the label of the new object
mindMapView.mindMapArrayListLabels.add( textField.getText().toString() );
//add the correct image.
mindMapView.mindMapArrayListImgs.add(imageLocation);
//move the index to the end position of the arrays
mindMapView.imageIndex = (mindMapView.mindMapArrayListLabels.size() - 1);
//redraw the view
mindMapView.invalidate();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//since the user hit 'cancel', don't do anything
}
})
.setTitle("Might not need this")
.show();
/* ^^^^^^^^^^^ */
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//since the user hit 'cancel', don't do anything
}
})
.setTitle("Choose an image:")
.show();
/* ^^^^^^^^^^^ */
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.edit_mind_map, menu);
return true;
}
}
Here is my CustomListAdapter01 class:
public class CustomListAdapter01 extends BaseAdapter {
//contains all of the images that will be displayed
ArrayList<Drawable> images;
Context context;
public CustomListAdapter01(ArrayList<Drawable> images, Context context) {
super();
// TODO Auto-generated constructor stub
this.images = images;
this.context = context;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return 0;
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
Drawable image = images.get(position);
if (convertView == null)
{
LayoutInflater infalInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.child_layout, null);
}
ImageView imageView = (ImageView)convertView.findViewById(R.id.image);
imageView.setBackgroundDrawable(image);
return convertView;
}
}
Here is the XML file 'child_layout':
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<ImageView android:id="#+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</RelativeLayout>
Any help would be appreciated.

#Override
public int getCount() {
// TODO Auto-generated method stub
return 0;
}
should be the below as the adapter needs to know the size of the list:
#Override
public int getCount() {
// TODO Auto-generated method stub
images.size();
}

Related

Remove all my item in Listview

I have a Listview in my row, I have check box to select a item to delete.
I want to have a button to select all my items and delete them at same time.
When I click my button to select all the items, only the last item gets selected.
Here is my code:
all.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
for(int i=0;i<listview.getChildCount();i++){
Log.i("mhs",listview.getChildCount()+"");
checkBox.setChecked(true);
}
}
});
Here is my Adaptor :
public class CustomArrayAdapter extends ArrayAdapter<String> {
private LayoutInflater inflater;
// This would hold the database objects i.e. Blacklist
private List<Blacklist> records;
#SuppressWarnings("unchecked")
public CustomArrayAdapter(Context context, int resource, #SuppressWarnings("rawtypes") List objects) {
super(context, resource, objects);
this.records = objects;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
//Reuse the view to make the scroll effect smooth
if (convertView == null)
convertView = inflater.inflate(R.layout.list_item, parent, false);
// Fetch phone number from the database object
final Blacklist phoneNumber = records.get(position);
// Set to screen component to display results
((TextView) convertView.findViewById(R.id.serial_tv)).setText("" + (position + 1));
((TextView) convertView.findViewById(R.id.phone_number_tv)).setText(phoneNumber.phoneNumber);
checkBox = (CheckBox) convertView.findViewById(R.id.check);
final LinearLayout me = (LinearLayout) convertView.findViewById(R.id.me);
if (position + 1 >= 1) {
me.setVisibility(View.VISIBLE);
}
checkBox.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {
final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);
// Set the appropriate message into it.
alertDialogBuilder.setMessage(getResources().getString(R.string.block));
// Add a positive button and it's action. In our case action would be deletion of the data
alertDialogBuilder.setPositiveButton(getResources().getString(R.string.yes),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
try {
blackListDao.delete(blockList.get(position));
// Removing the same from the List to remove from display as well
blockList.remove(position);
listview.invalidateViews();
// Reset the value of selectedRecordPosition
selectedRecordPosition = -1;
populateNoRecordMsg();
} catch (Exception e) {
e.printStackTrace();
}
}
});
// Add a negative button and it's action. In our case, just hide the dialog box
alertDialogBuilder.setNegativeButton(getResources().getString(R.string.no),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
checkBox.setChecked(false);
}
});
// Now, create the Dialog and show it.
final AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
}
});
all.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
for(int i=0;i<listview.getChildCount();i++){
Log.i("mhs",listview.getChildCount()+"");
checkBox.setChecked(true);
listview.removeView(i);
}
}
});
return convertView;
}
}
How to select all the items together?
The issue with a listview is that the views are recycled! That means that calling
checkBox.setChecked(true);
Will simply just edit the current active item. If you want to remove all the items the best way to do so is to clear the list you are using, and the notifyingDataSetChanged().
In the for loop add this:
currentCheckBox = listView.getChildAt(i);
//now you should have the correct checkBox
Edit: if your needs is simply deleting the data and clearing, I'd make a method just for that. Call it, delete the items from db, then .clear() the adapter. (can't remember if notifyDatasetChanged() is called autmatically here, do it if not)

capturing images from camera and setting into listview in android

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

Hide items in GridView if two items have same images using Android

i am developing a project using GridView where i need to hide items if a user click such two items having same images then both item should be hide.
First time when project will load it will have one Question Marks image on all item.
when user click item the background image will show then if he click another item having the same picture then both item should be hide if not, it again show the Question Marks image.
How this is possible?
here is my MainActivity.java
public class MainActivity extends Activity {
Context ctx;
int imagesArray[];
GridViewContent adapter;
List<Integer> pictures;
boolean flage=false;
int img1=-1,img2=-1;
public int OriginalArray[] = { R.drawable.sample_0, R.drawable.sample_1,
R.drawable.sample_2, R.drawable.sample_3,R.drawable.sample_0, R.drawable.sample_1,
R.drawable.sample_2, R.drawable.sample_3 };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
shuffleArray();
adapter= new GridViewContent(this);
final GridView grid = (GridView) findViewById(R.id.gv_memory);
grid.setAdapter(new GridViewContent(this));
}
private void shuffleArray() {
// TODO Auto-generated method stub
pictures= new ArrayList<Integer>();
for (int index = 0; index < OriginalArray.length; index++)
{
pictures.add(OriginalArray[index]);
}
Collections.shuffle(pictures);
}
public class GridViewContent extends BaseAdapter {
private Context context;
//abstract change();
public int pictureArray[]={
R.drawable.question,
R.drawable.question,
R.drawable.question,
R.drawable.question,
R.drawable.question,
R.drawable.question,
R.drawable.question,
R.drawable.question,
};
public GridViewContent(Context c){
context=c;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return (pictureArray.length);
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return pictureArray[position];
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup arg2) {
// TODO Auto-generated method stub
convertView=LayoutInflater.from(context).inflate(R.layout.main, null);
final ImageView myimage=new ImageView(context);
myimage.setImageResource(pictureArray[position]);
//myimage.setImageResource(pictures.get(pictureArray[position]));
myimage.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
myimage.setLayoutParams(new GridView.LayoutParams(70, 70));
myimage.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// int post1,post2;
myimage.setImageResource(pictures.get(position));
if(flage==false)
{
img1=pictures.get(position);
flage=true;
}else if(flage==true){
//post2=position;
img2=pictures.get(position);
checkResult();
//notifyDataSetChanged();
flage=false;
}
//else if(f)
}
});
return myimage;
}
}
public void checkResult() {
if(img1==img2)
{
//pictures.remove(post2);
adapter.notifyDataSetChanged();
Toast.makeText(MainActivity.this, "Congratualatin !!!!", Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(MainActivity.this, "Sorry!!!!", Toast.LENGTH_LONG).show();
final GridView grid = (GridView) findViewById(R.id.gv_memory);
grid.setAdapter(new GridViewContent(this));
}
}
}
You could try and remember the index of a GridView item you clicked. When a second click occurs, check the remembered index. If it is populated (meaning the user already clicked on an arbitrary image once), extract both drawables from the adapter and check if they are equal. If they are, remove them from the adapter and update it. Do not forget to reset the remembered index.
In code, this might look something like this:
int firstClickIndex = -1;
grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView <? > parent, View view, int position, long id) {
if (-1 == firstClickIndex) {
firstClickIndex = position;
} else {
final int fstDrawable = adapter.get(firstClickIndex);
final int sndDrawable = adapter.get(position);
if (fstDrawable == sndDrawable) {
// Remove stuff, then reset firstClickIndex.
} else {
// Reset firstClickIndex.
}
}
}
});

Show List if contains data else AlertDialog

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

How to delete a selected item from the listview?

SORRY FOR THIS CONFUSION:
UPDATED QUESTION:
I'm trying to remove a list item from the listview. when the item is clicked, the alertdialog is shown. If i click OK, then the selected item must be removed from the listview.
My Code goes below:
case R.id.lvinc:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Delete Event ");
builder.setMessage("Delete this Event ?");
builder.setPositiveButton("Ok, Delete",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
try
{
???? //What code to delete the selected list item?
}catch(Exception e)
{
e.printStackTrace();
}
}
});
AlertDialog alert = builder.create();
alert.show();
displaylist();
break;
Any help is really appreciated and thanks in advance...
I tried to solve it and got one solution pls go through the code below:
listview.java
public class listview extends Activity implements OnItemClickListener{
ListView list;
ListAdapter adapter;
ArrayList<String> nameArray;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);//xml should have an ListView element
nameArray = new ArrayList<String>();
nameArray.add("Item1");
nameArray.add("Item2");
nameArray.add("Item3");
nameArray.add("Item4");
nameArray.add("Item5");
list = (ListView) findViewById(R.id.listView);
list.setOnItemClickListener(listview.this);
adapter=new ListAdapter(listview.this, nameArray);
list.setAdapter(adapter);
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
showDialog(arg2);
}
#Override
protected Dialog onCreateDialog(final int id) {
Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Delete Event")
.setCancelable(true)
.setPositiveButton("Ok, Delete",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
nameArray.remove(id);
adapter=new ListAdapter(listview.this, nameArray);
list.setAdapter(adapter);
}
})
.setNegativeButton("No",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog dialog = builder.create();
dialog.show();
return super.onCreateDialog(id);
}
}
//Adapter Class
ListAdapter.java
public class ListAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<String> name;
private static LayoutInflater inflater=null;
public ListAdapter(Activity a, ArrayList<String> nameArray) {
activity = a;
name = nameArray;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return name.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public static class ViewHolder{
public TextView text;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
ViewHolder holder;
if(convertView==null){
vi = inflater.inflate(R.layout.list_item, null);
holder=new ViewHolder();
holder.text=(TextView)vi.findViewById(R.id.title);
vi.setTag(holder);
}
else
holder=(ViewHolder)vi.getTag();
holder.text.setText(name.get(position));
return vi;
}
}
I don't know what kind of data you are using.
I imagine Cursor, database or List, feel free to tell us, so it will be easier to help.
This example is for a list:
protected void onListItemClick(View v, int pos, long id) {
Log.i(TAG, "onListItemClick id=" + id);
//Display your Dialog
(...)
builder.setPositiveButton("Ok, Delete",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
myList.remove(pos);
myAdapter.notifyDataChanged();
}
});
}
You propably have some kind of Adapter, that you have feed with some kind of data.
Remove the item from that list, and notifyDataChanged to the ListView.
And finally: dialog.dismiss();
itemLayout.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
indexClick = position;
}
}
if ((indexClick) == (position)) {
itemLayout.setBackgroundResource(R.drawable.tab_select);
}
otherwise put tab_unselected image.

Categories

Resources