I have an item in my menu
case R.id.theme:
ShowRadioDialog();
return true;
With a method that shows an Alert dialog with 3 radio buttons. When i click the item the dialog shows but when i choose some item inside the dialog and i tap in the positiove buttons nothing happens. This is the method:
public void ShowRadioDialog() {
final CharSequence[] items={"Rosso","Verde","Blu"};
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setTitle("Seleziona un colore");
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#SuppressLint("NewApi")
#Override
public void onClick(DialogInterface dialog, int which) {
if (wich== 1) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().setStatusBarColor(MainActivity.this.getResources().getColor(R.color.red));
toolbar.setBackgroundColor(MainActivity.this.getResources().getColor(R.color.red));
Toast.makeText(MainActivity.this, "Rosso OK", Toast.LENGTH_SHORT).show();
Log.i("Colors", "Rosso Ok");
}
} else if (wich ==2) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().setStatusBarColor(MainActivity.this.getResources().getColor(R.color.green_welcome));
}
} else if (wich == 3){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().setStatusBarColor(MainActivity.this.getResources().getColor(R.color.primary_dark_blue));
}
}
}
});
builder.setSingleChoiceItems(items,-1, new DialogInterface.OnClickListener() {
#SuppressLint("NewApi")
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
if ("Rosso".equals(items[which])) {
which = 1;
} else if ("Verde".equals(items[which])) {
which = 2;
} else if ("Blu".equals(items[which])) {
which = 3;
}
}
});
builder.show();
}
I'm not sure it's the correct way. However, not either one (log in the logcat and the Toast in the application) appears. Seems that the positive button not accept the choice. Something is wrong?
Define a variable on top level and use that to access the selected item.
int index = -1;
public void ShowRadioDialog() {
final CharSequence[] items={"Rosso","Verde","Blu"};
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setTitle("Seleziona un colore");
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#SuppressLint("NewApi")
#Override
public void onClick(DialogInterface dialog, int which) {
if (index == 1) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().setStatusBarColor(MainActivity.this.getResources().getColor(R.color.red));
toolbar.setBackgroundColor(MainActivity.this.getResources().getColor(R.color.red));
Toast.makeText(MainActivity.this, "Rosso OK", Toast.LENGTH_SHORT).show();
Log.i("Colors", "Rosso Ok");
}
} else if (index ==2) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().setStatusBarColor(MainActivity.this.getResources().getColor(R.color.green_welcome));
}
} else if (index == 3){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().setStatusBarColor(MainActivity.this.getResources().getColor(R.color.primary_dark_blue));
}
}
}
});
builder.setSingleChoiceItems(items,-1, new DialogInterface.OnClickListener() {
#SuppressLint("NewApi")
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
if ("Rosso".equals(items[which])) {
index = 1;
} else if ("Verde".equals(items[which])) {
index = 2;
} else if ("Blu".equals(items[which])) {
index = 3;
}
}
});
builder.show();
}
If you want to save the value of index in shared preference on click of ok button do like this
Store in SharedPreferences
SharedPreferences preferences = getSharedPreferences("myPref", getApplicationContext().MODE_PRIVATE);
Editor editor = preferences.edit();
editor.putInt("choice", index);
editor.commit();
Fetch from SharedPreferences when required
SharedPreferences preferences = getSharedPreferences("myPref", getApplicationContext().MODE_PRIVATE);
int index = preferences.getInt("choice",-1);
Related
I've implemented a singleChoiceItems AlertDialog which opens from a navigation menu in my android app. I'm using it to change the app theme (Light, Dark, System default).
Now I'm trying to save the current state of the AlertDialog in sharedPrefernces along with the theme that the user selects. For e.g, if I've selected a dark theme previously, I want the AlertDialog to show the same while applying the theme to the app.
Here's the code I've been using.
String selectedTheme = "Light";
public static final String SHARED_PREFS = "sharedPrefs";
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
selectedTheme = sharedPreferences.getString("str", "Light");
public void openDialog() {
String[] themes = {"Light", "Dark", "System default"};
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Choose Theme");
builder.setSingleChoiceItems(themes, 2, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
selectedTheme = themes[which];
}
});
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
SharedPreferences sharedPreferences = getSharedPreferences("SHARED_PREFS", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("str", selectedTheme);
editor.apply();
if (selectedTheme.equals("Light")) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
}
else if (selectedTheme.equals("Dark")) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
}
else {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
}
dialog.dismiss();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.show();
}
With the above code, the sharedpreferences is not storing the current state. What changes do I need to do in order to make it work?
I was able to solve the problem by sharing the string related to the theme in sharedPreference.
I also implemented the AlertDialog issue where I wanted to check the items which was previously chosen inside the app.
Following is the code I used:
String selectedTheme = "Light";
int checkedItem = 0;
public static final String SHARED_PREFS = "sharedPrefs";
public static final String TEXT = "text";
public static final String RADIO = "selected";
Then I called loadData() and updateViews() from onCreate().
public void openDialog() {
String[] themes = {"Light", "Dark", "System default"};
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Choose Theme");
if (selectedTheme.equals("Light")) {
checkedItem = 0;
} else if (selectedTheme.equals("Dark")) {
checkedItem = 1;
} else {
checkedItem = 2;
}
builder.setSingleChoiceItems(themes, checkedItem, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
selectedTheme = themes[which];
}
});
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (selectedTheme.equals("Light")) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
}
else if (selectedTheme.equals("Dark")) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
}
else {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
}
saveData();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.show();
}
public void saveData() {
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(TEXT, selectedTheme);
editor.putInt("selected", checkedItem);
editor.apply();
Toast.makeText(MainActivity.this, "Data Saved", Toast.LENGTH_SHORT).show();
}
public void loadData() {
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
selectedTheme = sharedPreferences.getString(TEXT, "System default");
checkedItem = sharedPreferences.getInt("selected", 0);
}
public void updateViews() {
if (selectedTheme.equals("Light")) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
checkedItem = 0;
}
else if (selectedTheme.equals("Dark")) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
checkedItem = 1;
}
else {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
checkedItem = 2;
}
}
I followed the tutorial from this link.
My question is i have a list of food item. when user press add button to add the dish i am saving this dish name in shared preference. but when i press the same dish twice in shared preference should show 2 dishes with the same name. but each time i press same dish its showing me only one dish. this is my code below.
public class Cafetaria extends AppCompatActivity {
String title;
ListView listView;
View customNav;
public String value,secdish,thrDish,frthDish;
public String Drink,Drink2,Drink3,Drink4;
String selectedDrink;
Dialog ViewDialog;
TextView tv_foodtype,tv_drink;
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cafetaria);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
title = getIntent().getStringExtra("option");
getSupportActionBar().setTitle(title);
ActionBar actionBar = getSupportActionBar();
ActionBar.LayoutParams lp = new ActionBar.LayoutParams(ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT, Gravity.RIGHT | Gravity.CENTER_VERTICAL);
customNav = LayoutInflater.from(this).inflate(R.layout.food_actionbar_layout, null); // layout which contains your button.
actionBar.setCustomView(customNav, lp);
actionBar.setDisplayShowCustomEnabled(true);
customNav.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ViewDialog = new Dialog(Cafetaria.this);
ViewDialog.setContentView(R.layout.activity_order_detail);
ViewDialog.setTitle("Your Order Details");
tv_foodtype = (TextView)ViewDialog.findViewById(R.id.nameuser);
tv_drink = (TextView)ViewDialog.findViewById(R.id.passnum);
button = (Button)ViewDialog.findViewById(R.id.okBtn);
ViewDialog.show();
final SharedPreferences mSharedPreference= PreferenceManager.getDefaultSharedPreferences(getBaseContext());
value=(mSharedPreference.getString("firstDish", ""));
Drink=(mSharedPreference.getString("selectedDrinks", ""));
Drink2=(mSharedPreference.getString("selectedDrinks1", ""));
Drink3=(mSharedPreference.getString("selectedDrinks2", ""));
Drink4=(mSharedPreference.getString("selectedDrinks3", ""));
secdish=(mSharedPreference.getString("secdish", ""));
thrDish=(mSharedPreference.getString("thirdDish", ""));
frthDish=(mSharedPreference.getString("fourtDish", ""));
tv_foodtype.setText("Main Dishes"+ " \n"+value + " \n" + secdish +"\n"+thrDish+"\n"+frthDish);
tv_drink.setText("Drink"+" \n"+Drink + " \n" + Drink2 +"\n"+Drink3+"\n"+Drink4);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ViewDialog.dismiss();
}
});
}
});
listView =(ListView)findViewById(R.id.listView);
Drawable chic = this.getResources().getDrawable(R.drawable.chicktikka);
final Drawable plus = this.getResources().getDrawable(R.drawable.plus);
Drawable minus = this.getResources().getDrawable(R.drawable.minus);
ArrayList<FoodItemData> listofItem = new ArrayList<>();
FoodListViewAdapter listViewAdapter= new FoodListViewAdapter(this,R.layout.item_layout,listofItem);
listView.setAdapter(listViewAdapter);
listofItem.add(new FoodItemData("Chicken Tikka","spicey chicken tikka with mixures of indian spices",chic,plus,minus));
listofItem.add(new FoodItemData("Onion Bhaji","spicey chicken tikka with mixures of indian spices",chic,plus,minus));
listofItem.add(new FoodItemData("Chicken Pizza","spicey chicken tikka with mixures of indian spices",chic,plus,minus));
listofItem.add(new FoodItemData("Chicken Masala","spicey chicken tikka with mixures of indian spices",chic,plus,minus));
}
#RequiresApi(api = Build.VERSION_CODES.HONEYCOMB_MR1)
public void plusClick(View v)
{
if (listView.getPositionForView(v)==0) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(Cafetaria.this);
final SharedPreferences.Editor editor = prefs.edit();
editor.putString("firstDish","Chicken Tikka");
AlertDialog.Builder adb = new AlertDialog.Builder(this);
adb.setTitle("Please Choose your drink");
final String[] drinks = new String[]{"Coke", "Fanta", "Sprite"};
final ArrayList<Integer> selectedItems = new ArrayList<Integer>();
final boolean[] preCheckedItems = new boolean[]{false, false, false};
adb.setMultiChoiceItems(drinks, preCheckedItems, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
if (isChecked) {
selectedItems.add(which);
} else if (selectedItems.contains(which)) {
selectedItems.remove(which);
}
}
});
//Define the AlertDialog positive/ok/yes button
adb.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
for (int i = 0; i < selectedItems.size(); i++) {
int IndexOfColorsArray = selectedItems.get(i);
selectedDrink = Arrays.asList(drinks).get(IndexOfColorsArray);
editor.putString("selectedDrinks",selectedDrink);
editor.commit();
}
Toast.makeText(Cafetaria.this, "Your item has been added", Toast.LENGTH_SHORT).show();
}
});
//Define the Neutral/Cancel button in AlertDialog
adb.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
adb.show();
}
else if (listView.getPositionForView(v) == 1) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(Cafetaria.this);
final SharedPreferences.Editor editor = prefs.edit();
editor.putString("secdish","Onion Bhaji");
AlertDialog.Builder adb = new AlertDialog.Builder(this);
adb.setTitle("Choose your Drink");
final String[] drinks = new String[]{"Coke", "Fanta", "Sprite"};
final ArrayList<Integer> selectedItems = new ArrayList<Integer>();
final boolean[] preCheckedItems = new boolean[]{false, false, false};
adb.setMultiChoiceItems(drinks, preCheckedItems, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
if (isChecked) {
selectedItems.add(which);
} else if (selectedItems.contains(which)) {
selectedItems.remove(which);
}
}
});
//Define the AlertDialog positive/ok/yes button
adb.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
for (int i = 0; i < selectedItems.size(); i++) {
int IndexOfColorsArray = selectedItems.get(i);
selectedDrink = Arrays.asList(drinks).get(IndexOfColorsArray);
editor.putString("selectedDrinks1",selectedDrink);
editor.commit();
}
Toast.makeText(Cafetaria.this, "Your item has been added", Toast.LENGTH_SHORT).show();
}
});
adb.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//When user click the neutral/cancel button from alert dialog
}
});
adb.show();
}
else if (listView.getPositionForView(v) == 2) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(Cafetaria.this);
final SharedPreferences.Editor editor = prefs.edit();
editor.putString("thirdDish","Chicken Pizza");
AlertDialog.Builder adb = new AlertDialog.Builder(this);
adb.setTitle("Choose your Drink");
final String[] drinks = new String[]{"Coke", "Fanta", "Sprite"};
final ArrayList<Integer> selectedItems = new ArrayList<Integer>();
final boolean[] preCheckedItems = new boolean[]{false, false, false};
adb.setMultiChoiceItems(drinks, preCheckedItems, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
if (isChecked) {
selectedItems.add(which);
} else if (selectedItems.contains(which)) {
selectedItems.remove(which);
}
}
});
adb.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
for (int i = 0; i < selectedItems.size(); i++) {
int IndexOfColorsArray = selectedItems.get(i);
selectedDrink = Arrays.asList(drinks).get(IndexOfColorsArray);
editor.putString("selectedDrinks2",selectedDrink);
editor.commit();
}
Toast.makeText(Cafetaria.this, "Your item has beed added", Toast.LENGTH_SHORT).show();
}
});
adb.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//When user click the neutral/cancel button from alert dialog
}
});
adb.show();
}
else if (listView.getPositionForView(v) == 3) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(Cafetaria.this);
final SharedPreferences.Editor editor = prefs.edit();
editor.putString("fourtDish","Chicken Masala");
AlertDialog.Builder adb = new AlertDialog.Builder(this);
adb.setTitle("Choose your Drink");
final String[] drinks = new String[]{"Coke", "Fanta", "Sprite"};
final ArrayList<Integer> selectedItems = new ArrayList<Integer>();
final boolean[] preCheckedItems = new boolean[]{false, false, false};
adb.setMultiChoiceItems(drinks, preCheckedItems, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
if (isChecked) {
selectedItems.add(which);
} else if (selectedItems.contains(which)) {
//selectedItems.remove(which);
selectedItems.add(which);
}
}
});
adb.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
for (int i = 0; i < selectedItems.size(); i++) {
int IndexOfColorsArray = selectedItems.get(i);
selectedDrink = Arrays.asList(drinks).get(IndexOfColorsArray);
editor.putString("selectedDrinks3",selectedDrink);
editor.commit();
}
Toast.makeText(Cafetaria.this, "Your item has beed added", Toast.LENGTH_SHORT).show();
}
});
adb.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//When user click the neutral/cancel button from alert dialog
}
});
adb.show();
}
}
public void minusClick(View v)
{
if (listView.getPositionForView(v)==0) {
final SharedPreferences mSharedPreference= PreferenceManager.getDefaultSharedPreferences(getBaseContext());
mSharedPreference.edit().remove("firstDish").commit();
mSharedPreference.edit().remove("selectedDrinks").commit();
Toast.makeText(Cafetaria.this, "Your Item has been removed", Toast.LENGTH_SHORT).show();
}
else if (listView.getPositionForView(v)==1)
{
final SharedPreferences mSharedPreference= PreferenceManager.getDefaultSharedPreferences(getBaseContext());
mSharedPreference.edit().remove("secDish").commit();
mSharedPreference.edit().remove("selectedDrinks1").commit();
Toast.makeText(Cafetaria.this, "Your Item has been removed", Toast.LENGTH_SHORT).show();
}
else if (listView.getPositionForView(v)==2)
{
final SharedPreferences mSharedPreference= PreferenceManager.getDefaultSharedPreferences(getBaseContext());
mSharedPreference.edit().remove("thirdDish").commit();
mSharedPreference.edit().remove("selectedDrinks2").commit();
Toast.makeText(Cafetaria.this, "Your Item has been removed", Toast.LENGTH_SHORT).show();
}
else if (listView.getPositionForView(v)==3)
{
final SharedPreferences mSharedPreference= PreferenceManager.getDefaultSharedPreferences(getBaseContext());
mSharedPreference.edit().remove("fourtDish").commit();
mSharedPreference.edit().remove("selectedDrinks3").commit();
Toast.makeText(Cafetaria.this, "Your Item has been removed", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onResume() {
super.onResume();
if (getSupportActionBar() != null){
getSupportActionBar().setTitle(title);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
this.finish();
return true;
}
return false;
}
#Override
protected void onRestart() {
super.onRestart();
final SharedPreferences mSharedPreference= PreferenceManager.getDefaultSharedPreferences(getBaseContext());
mSharedPreference.edit().remove("firstDish").commit();
mSharedPreference.edit().remove("selectedDrinks").commit();
mSharedPreference.edit().remove("selectedDrinks1").commit();
mSharedPreference.edit().remove("selectedDrinks2").commit();
mSharedPreference.edit().remove("selectedDrinks3").commit();
mSharedPreference.edit().remove("secdish").commit();
mSharedPreference.edit().remove("thirdDish").commit();
mSharedPreference.edit().remove("fourtDish").commit();
}
}`
This is the result I am getting. I press this dish twice and its shown only once. It should be shown twice the same dish name. Please Guide.
The code is really long to follow on here. But speaking generally, do you save each dish with different key-value pair? Maybe think about such solution. OR you could store the dishes in an array, which can be stored in Shared prefs, and once you want to see your dishes, just read out the Array List and display the items inside it.
You store the String into an Array, whenever you want to do it in your code. It's just like mArrayList.add("String"); and then you can update yuor SharedPrefs the same you already do, just check the URL on how to store ArrayList to SharedPrefs. Would be a cleaner solution in my view.
Here you can see how to store ArrayList in SharedPreferences:
Save ArrayList to SharedPreferences
And the once you want to display the items from ArrayList, you pull ArrayList from SharedPrefs and display them in AlertDialog ListView.
And here it is explained how to display Array Items in AlertDialog:
How can I display a list view in an Android Alert Dialog?
I want to change the dialog of exit app with twi choices choice 1 = "rate" and choice 2 = "exit" now i can only show exit or stay dialog but i want to convert it to what i described here is the code :
#Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setNeutralButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
PicSelect.this.finish();
}
})
.setNegativeButton("No", null)
.show();
}
and this the class code `
public class PicSelect extends SherlockActivity {
private GridView photoGrid;
private int mPhotoSize, mPhotoSpacing;
private Itemadapter imageAdapter;
private AdView mAdView;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_picselct);
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#c5d951")));
mAdView = (AdView) findViewById(R.id.adViewad);
mAdView.loadAd(new AdRequest.Builder().build());
mPhotoSize = getResources().getDimensionPixelSize(R.dimen.photo_size);
mPhotoSpacing = getResources().getDimensionPixelSize(R.dimen.photo_spacing);
photoGrid = (GridView) findViewById(R.id.albumGrid);
Model.LoadModel();
String[] ids = new String[Model.Items.size()];
for (int i= 0; i < ids.length; i++){
ids[i] = Integer.toString(i+1);
}
imageAdapter=new Itemadapter(getApplicationContext(), R.layout.photo_item,ids,"CATIMAGE");
photoGrid.setAdapter(imageAdapter);
// get the view tree observer of the grid and set the height and numcols dynamically
photoGrid.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
if (imageAdapter.getNumColumns() == 0) {
final int numColumns = (int) Math.floor(photoGrid.getWidth() / (mPhotoSize + mPhotoSpacing));
if (numColumns > 0) {
final int columnWidth = (photoGrid.getWidth() / numColumns) - mPhotoSpacing;
imageAdapter.setNumColumns(numColumns);
imageAdapter.setItemHeight(columnWidth);
}
}
}
});
photoGrid.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
Log.e("FolderName", Model.GetbyId(position+1).FolderName);
String FolderName=Model.GetbyId(position+1).FolderName;
String CategoryName=Model.GetbyId(position+1).Name;
Intent i=new Intent(PicSelect.this,PicItem.class);
i.putExtra("Folder", FolderName);
i.putExtra("Category", CategoryName);
startActivity(i);
}
});
}
#Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setNeutralButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
PicSelect.this.finish();
}
})
.setNegativeButton("No", null)
.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.home, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem menuItem)
{
switch (menuItem.getItemId())
{
case R.id.rateapp:
final String appName = getPackageName();//your application package name i.e play store application url
try {
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("market://details?id="
+ appName)));
} catch (android.content.ActivityNotFoundException anfe) {
startActivity(new Intent(
Intent.ACTION_VIEW,
Uri.parse("http://play.google.com/store/apps/details?id="
+ appName)));
}
return true;
case R.id.moreapp:
startActivity(new Intent(
Intent.ACTION_VIEW,
Uri.parse(getString(R.string.play_more_apps))));
return true;
default:
return super.onOptionsItemSelected(menuItem);
}
}
}
`
finaly if anyone know how to style the text thank you for your help
.setNegativeButton("Rate App", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent i = new Intent(android.content.Intent.ACTION_VIEW);
i.setData(Uri.parse("market://details?id=[your package name]"));
startActivity(i);
}
})
This will give you a negative option that says Rate App that when clicked opens the market to your app.
Improve your app with this snippet in onBackPressed():
if(isTaskRoot()) {
if (this.lastBackPressTime < System.currentTimeMillis() - 2000) {
toast = Toast.makeText(this, getString(R.string.hinweisBeendeApp), Toast.LENGTH_SHORT);
toast.show();
this.lastBackPressTime = System.currentTimeMillis();
} else {
if (toast != null) {
toast.cancel();
}
super.onBackPressed();
}
}else {
super.onBackPressed();
}
I'm still new to Java and in Android programming so I'm a bit confused in some programming methods. I just want to ask, how do I use return value of method match_eye() in another class ?. I just want to use mmres.minVal and mmres.maxVal values in a another class (FdActivity) and display these values in my activity class.can anyone show me the code to do this :) thanks
class FdView extends SampleCvViewBase {
public void setMinFaceSize(float faceSize)
{
.........
}
........
........
double match_eye(Rect area, Mat mTemplate,int type){
Point matchLoc;
Mat mROI = mGray.submat(area);
int result_cols = mGray.cols() - mTemplate.cols() + 1;
int result_rows = mGray.rows() - mTemplate.rows() + 1;
//Check for bad template size
if(mTemplate.cols()==0 ||mTemplate.rows()==0){
return 0.0;
}
mResult = new Mat(result_cols,result_rows, CvType.CV_32FC1);
switch (type){
//TM_SQDIFF Matching Method
case TM_SQDIFF:
Imgproc.matchTemplate(mROI, mTemplate, mResult, Imgproc.TM_SQDIFF);
break;
//TM_SQDIFF Matching Method
case TM_SQDIFF_NORMED:
Imgproc.matchTemplate(mROI, mTemplate, mResult, Imgproc.TM_SQDIFF_NORMED);
break;
//TM_SQDIFF Matching Method
case TM_CCOEFF:
Imgproc.matchTemplate(mROI, mTemplate, mResult, Imgproc.TM_CCOEFF);
break;
//TM_SQDIFF Matching Method
case TM_CCOEFF_NORMED:
Imgproc.matchTemplate(mROI, mTemplate, mResult, Imgproc.TM_CCOEFF_NORMED) ;
break;
//TM_SQDIFF Matching Method
case TM_CCORR:
Imgproc.matchTemplate(mROI, mTemplate, mResult, Imgproc.TM_CCORR) ;
break;
//TM_SQDIFF Matching Method
case TM_CCORR_NORMED:
Imgproc.matchTemplate(mROI, mTemplate, mResult, Imgproc.TM_CCORR_NORMED) ;
break;
}
Core.MinMaxLocResult mmres = Core.minMaxLoc(mResult);
// there is difference in matching methods - best match is max/min value
if(type == TM_SQDIFF || type == TM_SQDIFF_NORMED)
{
matchLoc = mmres.minLoc;
}
else
{
matchLoc = mmres.maxLoc;
}
Point matchLoc_tx = new Point(matchLoc.x+area.x,matchLoc.y+area.y);
Point matchLoc_ty = new Point(matchLoc.x + mTemplate.cols() + area.x , matchLoc.y + mTemplate.rows()+area.y );
Core.rectangle(mRgba, matchLoc_tx,matchLoc_ty, new Scalar(255,255, 255, 255) ,2);
if(type == TM_SQDIFF || type == TM_SQDIFF_NORMED){
return mmres.maxVal;
}
else {
return mmres.minVal;
}
}
}
FdActivity Class
public class FdActivity extends Activity {
private static final String TAG = "Sample::Activity";
private MenuItem mItemFace50;
private MenuItem mItemFace40;
private MenuItem mItemFace30;
private MenuItem mItemFace20;
private MenuItem mItemType;
private FdView mView;
//Popup Window
private LayoutInflater inflater;
private PopupWindow pw;
private View popupView;
public static int method = 1;
//Timer Initializer
public int timer_start = 25000;
//Address Initializer
private String Address_location = "Ramakrishna Road, Colombo 00600, Sri Lanka";
//Sound Alerts
private MediaPlayer warning_sound;
private MediaPlayer lowbattery_alert;
private BaseLoaderCallback mOpenCVCallBack = new BaseLoaderCallback(this) {
#SuppressWarnings("deprecation")
#Override
public void onManagerConnected(int status) {
switch (status) {
case LoaderCallbackInterface.SUCCESS: {
Log.i(TAG, "OpenCV loaded successfully");
//Load native libs after OpenCV initialization
System.loadLibrary("detection_based_tracker");
// Create and set View
mView = new FdView(mAppContext);
mView.setDetectorType(mDetectorType);
mView.setMinFaceSize(0.2f);
//Start Tracking btn
Button btn_track = new Button(getApplicationContext());
btn_track.setText("Settings");
btn_track.setBackgroundResource(R.drawable.custombutton_settings);
btn_track.setTextColor(Color.WHITE);
btn_track.setTypeface(null, Typeface.BOLD);
RelativeLayout.LayoutParams btnp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
btnp.addRule(RelativeLayout. ALIGN_PARENT_RIGHT);
btn_track.setId(2);
btn_track.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//Popup Menu
pw = new PopupWindow(getApplicationContext());
pw.setTouchable(true);
pw.setFocusable(true);
pw.setOutsideTouchable(true);
pw.setTouchInterceptor(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
pw.dismiss();
return true;
}
return false;
}
});
pw.setWidth(WindowManager.LayoutParams.WRAP_CONTENT);
pw.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
pw.setOutsideTouchable(false);
pw.setContentView(popupView);
pw.showAsDropDown(v, 0, 0);
}
});
final TextView count_down = new TextView(getApplicationContext());
count_down.setText("Driver's State Recognition System");
count_down.setGravity(Gravity.CENTER);
count_down.setBackgroundColor(Color.BLACK);
count_down.setTextColor(Color.WHITE);
count_down.setTypeface(null, Typeface.BOLD);
RelativeLayout.LayoutParams textTimer = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
textTimer.setMargins(30, 0, 0, 30);
textTimer.addRule(RelativeLayout. ALIGN_PARENT_BOTTOM);
count_down.setId(6);
//Count Timer
final CountDownTimer cntr_aCounter = new CountDownTimer(timer_start, 1000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
//Start Alert Sound
warning_sound.start();
warning_sound.setLooping(true);
Toast.makeText(getBaseContext(), "Alerting Started...", Toast.LENGTH_LONG).show();
//Start Vibration
final Vibrator vibe = (Vibrator)getSystemService(VIBRATOR_SERVICE);
vibe.vibrate(20000);
//Start Alert Box and Emergency Text Alert
final AlertDialog alertDialog_warning = new AlertDialog.Builder(FdActivity.this).create();
alertDialog_warning.setCancelable(false);
alertDialog_warning.setTitle("WARNING");
alertDialog_warning.setMessage("Drowsiness Detected..Please Respond");
alertDialog_warning.setIcon(R.drawable.warning_icon);
alertDialog_warning.setButton("Respond", new DialogInterface.OnClickListener() {
final CountDownTimer timer_count_down = new CountDownTimer(25000, 1000) {
public void onTick(long millisUntilFinished) {
count_down.setText("Seconds Remaining To Respond : " + millisUntilFinished / 1000);
}
public void onFinish() {
//Emergency Text Alert
String phoneNo = "0712055056";
String sms = "Emergancy Alert !...Location : " + Address_location;
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, sms, null, null);
Toast.makeText(getApplicationContext(), "Emergancy Alert Sent !",Toast.LENGTH_LONG).show();
}
catch (Exception e) {
Toast.makeText(getApplicationContext(),"Emergancy Alert Sending Failed",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
//Stop all active alerts
count_down.setText("Not Responded Emergancy Alert Sent");
Animation anim = new AlphaAnimation(0.0f, 1.0f);
anim.setDuration(50); //You can manage the time of the blink with this parameter
anim.setStartOffset(20);
anim.setRepeatMode(Animation.REVERSE);
anim.setRepeatCount(Animation.INFINITE);
count_down.startAnimation(anim);
count_down.setTextColor(Color.RED);
alertDialog_warning.cancel();
warning_sound.pause();
vibe.cancel();
timer_count_down.cancel();
}
}.start();
public void onClick(final DialogInterface alertDialog_warning, final int which) {
alertDialog_warning.cancel();
//Stop Alert Sound
warning_sound.pause();
vibe.cancel();
timer_count_down.cancel();
count_down.setText("Driver's State Recognition System");
finish();
startActivity(getIntent());
}
});
alertDialog_warning.show();
}
};
cntr_aCounter.start();
//Turn off btn
Button btn_off = new Button(getApplicationContext());
btn_off.setText("Switch Off");
btn_off.setBackgroundResource(R.drawable.custombutton_settings);
btn_off.setTextColor(Color.WHITE);
btn_off.setTypeface(null, Typeface.BOLD);
RelativeLayout.LayoutParams btnp1 = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
btnp1.addRule(RelativeLayout. ALIGN_PARENT_LEFT);
btn_off.setId(3);
btn_off.setOnClickListener(new OnClickListener() {
public void onClick(View x) {
//Alert Dialog Box
AlertDialog.Builder alertDialog = new AlertDialog.Builder(FdActivity.this);
alertDialog.setTitle("WARNING");
alertDialog.setMessage(" Switch off Drowsiness Detection. \n Are you sure ?");
alertDialog.setIcon(R.drawable.warning_icon);
alertDialog.setCancelable(false); // This blocks the 'BACK' button
// Setting "Yes" Btn
alertDialog.setPositiveButton("YES",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
cntr_aCounter.cancel();
}
});
// Setting "NO" Btn
alertDialog.setNegativeButton("NO",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(),"Tracking Process Continued", Toast.LENGTH_LONG).show();
dialog.cancel();
}
});
alertDialog.show();
}
});
RelativeLayout frameLayout = new RelativeLayout(
getApplicationContext());
frameLayout.addView(mView, 0);
frameLayout.addView(btn_track, btnp);
frameLayout.addView(btn_off, btnp1);
frameLayout.addView(count_down, textTimer);
setContentView(frameLayout);
// Check native OpenCV camera
if (!mView.openCamera()) {
AlertDialog ad = new AlertDialog.Builder(mAppContext).create();
ad.setCancelable(false); // This blocks the 'BACK' button
ad.setMessage("Fatal Error: Can't Open Camera!");
ad.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
finish();
}
});
ad.show();
}
}
break;
default: {
super.onManagerConnected(status);
}
break;
}
}
};
private int mDetectorType = 0;
private String[] mDetectorName;
public FdActivity() {
Log.i(TAG, "Instantiated new " + this.getClass());
mDetectorName = new String[2];
mDetectorName[FdView.JAVA_DETECTOR] = "Java";
mDetectorName[FdView.NATIVE_DETECTOR] = "Native (tracking)";
}
#Override
protected void onPause() {
Log.i(TAG, "onPause");
super.onPause();
if (mView != null)
mView.releaseCamera();
}
#SuppressWarnings("deprecation")
#Override
protected void onResume() {
Log.i(TAG, "onResume");
super.onResume();
if (mView != null && !mView.openCamera()) {
AlertDialog ad = new AlertDialog.Builder(this).create();
ad.setCancelable(false); // This blocks the 'BACK' button
ad.setMessage("Fatal error: can't open camera!");
ad.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
finish();
}
});
ad.show();
}
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
Log.i(TAG, "onCreate");
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
//Sound Alert
warning_sound = MediaPlayer.create(this, R.raw.warning_alert);
lowbattery_alert = MediaPlayer.create(this, R.raw.low_battery);
//Popup menu
inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
popupView = inflater.inflate(R.layout.popup_menu_layout, null, false);
Log.i(TAG, "Trying to load OpenCV library");
if (!OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_2, this,mOpenCVCallBack)) {
Log.e(TAG, "Cannot connect to OpenCV Manager");
}
//battery
this.registerReceiver(this.batteryInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
Log.i(TAG, "onCreateOptionsMenu");
mItemFace50 = menu.add("Face size 50%");
mItemFace40 = menu.add("Face size 40%");
mItemFace30 = menu.add("Face size 30%");
mItemFace20 = menu.add("Face size 20%");
mItemType = menu.add(mDetectorName[mDetectorType]);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.i(TAG, "Menu Item selected " + item);
if (item == mItemFace50)
mView.setMinFaceSize(0.5f);
else if (item == mItemFace40)
mView.setMinFaceSize(0.4f);
else if (item == mItemFace30)
mView.setMinFaceSize(0.3f);
else if (item == mItemFace20)
mView.setMinFaceSize(0.2f);
else if (item == mItemType) {
mDetectorType = (mDetectorType + 1) % mDetectorName.length;
item.setTitle(mDetectorName[mDetectorType]);
mView.setDetectorType(mDetectorType);
}
return true;
}
//Popup Menu Actions
public void clickOne(View v) {
pw.dismiss();
mView.resetLearFramesCount();
Toast.makeText(getApplicationContext(), "Please wait..Template Recreating", Toast.LENGTH_LONG).show();
}
public void clickTwo(View v) {
pw.dismiss();
Toast.makeText(getBaseContext(), "Please wait..Switching Camera", Toast.LENGTH_LONG).show();
}
public void clickThree(View v) {
pw.dismiss();
Toast.makeText(getBaseContext(), "Please wait..Changing Tracking Method", Toast.LENGTH_LONG).show();
}
public void clickFour(View v) {
pw.dismiss();
Toast.makeText(getBaseContext(), "Please wait..Changing Tracking Method", Toast.LENGTH_LONG).show();
//Alert Dialog Box
AlertDialog.Builder alertDialog = new AlertDialog.Builder(FdActivity.this);
alertDialog.setCancelable(false);
alertDialog.setTitle("Exit Detection");
alertDialog.setMessage(" WARNING...You are about to exit system");
alertDialog.setIcon(R.drawable.warning_icon);
alertDialog.setPositiveButton("Continue", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.setNegativeButton("System Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
finish();
startActivity(new Intent("org.opencv.samples.facedetect.CLEARSCREENSETTINGS"));
}
});
alertDialog.show();
}
private BroadcastReceiver batteryInfoReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
int level= intent.getIntExtra(BatteryManager.EXTRA_LEVEL,0);
int plugged= intent.getIntExtra(BatteryManager.EXTRA_PLUGGED,0);
if(plugged==1){
Toast.makeText(getApplicationContext(), "Device Pluged In", Toast.LENGTH_LONG).show();
lowbattery_alert.pause();
}
if(plugged==0 && level > 20){
Toast.makeText(getApplicationContext(), "WARNING : Device Not Pluged In", Toast.LENGTH_LONG).show();
lowbattery_alert.pause();
}
else if(plugged==0 && level <= 20){
Toast.makeText(getApplicationContext(), "WARNING : Battery Low Please Plug In", Toast.LENGTH_LONG).show();
//alert sound
lowbattery_alert.start();
//Start Vibration
final Vibrator vibe = (Vibrator)getSystemService(VIBRATOR_SERVICE);
vibe.vibrate(20000);
//Alert Dialog Box
AlertDialog.Builder alertDialog = new AlertDialog.Builder(FdActivity.this);
alertDialog.setCancelable(false);
alertDialog.setTitle("Battery Low (" + level + "%)");
alertDialog.setMessage(" WARNING...Battery Low Please Connect The Charger");
alertDialog.setIcon(R.drawable.warning_icon);
// Setting "Switch Off" Btn
alertDialog.setPositiveButton("Switch Off", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
lowbattery_alert.pause();
vibe.cancel();
}
});
// Setting "Continue" Btn
alertDialog.setNegativeButton("Continue", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(),"Tracking Process Continued", Toast.LENGTH_LONG).show();
dialog.cancel();
vibe.cancel();
lowbattery_alert.pause();
}
});
alertDialog.show();
}
}
};
public void onBackPressed() {
Toast.makeText(getBaseContext(), "Please click Switch off button to deactivate the system", Toast.LENGTH_LONG).show();
}
}
As far as I understand you have Activity where you want to show two values which you want to get from another class. You can't return two values from one function that's why I suggest you to create your own Object which will hold these values and you can return your custom object from match_eye() for example and get your values from your Activity. Here is example code:
MyCustomObject.java
public MyObject{
private int mFirstValue;
private int mSecondValue;
// public constructor
public MyObject(int firstValue, int secondValue){
this.mFirstValue = firstValue;
this.mSecondValue = secondValue;
}
// first value getter
public int getFirstValue(){
return mFirstValue;
}
// second value getter;
public int getSecondValue(){
return mSecondValue;
}
}
and in your match_eye() you can do something similar to this:
public MyObject match_eye(Rect area, Mat mTemplate,int type){
//do your calculations here ...
int firstValue = 0; // get first value
int secondValue = 0; // get second value
return new MyObject(firstValue, secondValue);
}
and in your Activity you just need to call :
MyObject mCurrentObject = FdView.match_eye(/*params*/); // static call as example
if(mCurrentObject != null){
int myFirstValue = mCurrentObject.getFirstValue();
int mySecondValue = mCurrentObject.getSecondValue();
// Show these values in your Activity.
}
Take object of that class in which you defined your method into your second activity and use like below code:
testing t1 = new testing();
double returnval = t1.match_eye(yourarea, youmTemplate,yourtype);
System.out.println(returnval);
For sending value using Intent:
Intent i = new Intent(context,MainActivity.class)
.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra("var", returnval)
context.startActivity(i);
I'm trying to make a SingleChoiceItems dialog activated from a listview onItemLongCLick which has 3 options via radiobuttons 1.View Profile 2.Send Message 3.Delete Friends and from the way I have it set up,only the first option toast works on all 3 options.
How would I make it that options 2 and 3 does their actions instead of doing option 1's actions?
Here is the code to my dialog,
#Override
public Dialog onCreateDialog(int id) {
String[] items = { "View Profile", "Send Message", "Remove Friend" };
final DBAdapter db = new DBAdapter(this);
db.open();
switch (id) {
case 0:
return new AlertDialog.Builder(this)
.setIcon(R.drawable.icon)
.setTitle("Select a option")
.setSingleChoiceItems(items, id,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
int choice = 0;
// TODO Auto-generated method stub
mChoice = choice;
}
})
.setPositiveButton("OK", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int choice) {
// TODO Auto-generated method stub
if (mChoice == 0) {
Toast.makeText(getBaseContext(), "Test 1",
Toast.LENGTH_SHORT).show();
} else if (mChoice == 1) {
Toast.makeText(getBaseContext(), "Test2",
Toast.LENGTH_SHORT).show();
} else if (mChoice == 2) {
TextView friends = (TextView) findViewById(R.id.textview_friends);
String deletedfriend = friends.getText()
.toString();
db.DeleteFriends(deletedfriend);
Toast.makeText(getBaseContext(),
"Friend Removed", Toast.LENGTH_SHORT)
.show();
}
}
}
)
.setNegativeButton("Cancel", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int choice) {
}
})
.create();
}
return null;
}
Remove choice = 0;
.setSingleChoiceItems(items, id,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
mChoice = which;
}
})