Use only one AlertDialog for a ListView - java

I have a list view with 5 items. If i click on an item, it start an AlertDialog that ask me if i want to download the file. Each item, have a different url download.
Instead of create 5 AlertDialog, can i just create a single AlertDialog and start the correct download url on item selected?
public class MapsListActivity extends Downloader implements OnItemClickListener{
private static final File MAP4 = new File(Environment.getExternalStorageDirectory().getPath() + "/osmdroid/tiles/", "map4.map");
private static final File MAP3 = new File(Environment.getExternalStorageDirectory().getPath() + "/osmdroid/tiles/", "map3.map");
private static final File MAP2 = new File(Environment.getExternalStorageDirectory().getPath() + "/osmdroid/tiles/", "map2.map");
private static final File MAP = new File(Environment.getExternalStorageDirectory().getPath() + "/osmdroid/tiles/", "map.map");
ListView listView;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String osmdroidFolder = "/osmdroid/";
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File myOsmdroidFolder = new File(extStorageDirectory + osmdroidFolder);
myOsmdroidFolder.mkdir();
String tilesFolder = "/osmdroid/tiles/";
File myTilesFolder = new File(extStorageDirectory + tilesFolder);
myTilesFolder.mkdir();
listView = (ListView) findViewById(R.id.mapsList);
listView.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
switch (position){
case 0:{
Intent Info = new Intent(MapsListActivity.this, MyMapsActivity.class);
startActivity(Info);
}
break;
case 1:{
if (MAP.exists()) {
Intent Info = new Intent(MapsListActivity.this, MyMapsActivity.class);
startActivity(Info);
}
else{
DialogDownload();
}
}
break;
case 2:{
if (MAP2.exists()) {
Intent Info = new Intent(MapsListActivity.this, MyMapsActivity.class);
startActivity(Info);
}
else{
DialogDownload();
}
}
break;
case 3:{
if (MAP3.exists()) {
Intent Info = new Intent(MapsListActivity.this, MyMapsActivity.class);
startActivity(Info);
}
else{
DialogDownload();
}
}
break;
case 4:{
if (MAP4.exists()) {
Intent Info = new Intent(MapsListActivity.this, MyMapsActivity.class);
startActivity(Info);
}
else{
DialogDownload();
}
}
break;
}
}
protected void DialogDownload() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Maps not present. Would you like to download ?");
builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
/* functions that start the download
downloadmap();
downloadmap2();
downloadmap3();
downloadmap4();
*/
dialog.dismiss();
}
});
builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}

public void DialogDownLoad(String message,int pos)
{
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
// set title
alertDialogBuilder.setTitle("title");
// set dialog message
alertDialogBuilder.setMessage(message)
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
if(pos == 0){
// call downloadMap1();
}
if(pos == 1){
// call downloadMap2();
}
......................
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
............... //your code
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
and in your onItemClick() method
#Override
public void onItemClick(AdapterView<?> av, View v, int pos, long id) {
message = "Your url";
DialogDownload(message,pos);
}

Related

I want to add same value in shared preference each time click button

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?

Rate my app dialog when the user want to exit my app

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

How to force user to deal with dialog before allowing access to activity? AND What's wrong with my licensing code?

Ok so I recently completed an android app - my first one :D! - and because it is a paid app Google tells me I have to add the licensing stuff. That's fine and dandy, except I've been getting mind f*cked by it for the past five hours. Finally think I understand it a little and got it going, but in testing it in my emulator I come up with two issues:
I'm using the google API for 4.1, as instructed by their handy how-to on the developer console, but nomatter what I always end up coming up with my Connection Error dialog. Code here:
public void dontAllow(int reason) {
if(isFinishing()){
return;
}
displayResults("Access Denied");
if(reason==Policy.RETRY){
showDialog(DIALOG_RETRY);
}else{
showDialog(DIALOG_ERROR);
}
}
public void applicationError(int errorCode) {
dontAllow(0);
}
public void displayResults(String result){
}
And cooresponding dialog being called:
protected Dialog onCreateDialog(int id){
switch(id){
case DIALOG_RETRY:
Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Connection Error: Retry?");
builder.setCancelable(true);
builder.setPositiveButton("Retry", new RetryOnClickListener());
builder.setNegativeButton("Cancel", new CancelOnClickListener());
AlertDialog dialog = builder.create();
dialog.show();
break;
case DIALOG_ERROR:
Builder builder1 = new AlertDialog.Builder(this);
builder1.setMessage("Would you like to purchase Landscape ID! ?");
builder1.setCancelable(true);
builder1.setPositiveButton("Yes!", new BuyOnClickListener());
builder1.setNegativeButton("No.", new CancelOnClickListener());
AlertDialog dialog1 = builder1.create();
dialog1.show();
break;
}
return super.onCreateDialog(id);
}
private final class RetryOnClickListener implements
DialogInterface.OnClickListener{
public void onClick(DialogInterface dialog, int which) {
checker.checkAccess(checkerCB);
}
}
private final class CancelOnClickListener implements
DialogInterface.OnClickListener{
public void onClick(DialogInterface dialog, int which) {
onDestroy();
finish();
}
}
private final class BuyOnClickListener implements
DialogInterface.OnClickListener{
public void onClick(DialogInterface dialog, int which) {
Intent open = new Intent(Intent.ACTION_VIEW);
open.setData(Uri.parse("market://details? id=com.mustaroenterprise.landscapeid"));
startActivity(open);
}
}
My first question: How come it isn't connecting to the server as it should be? I've constructed my testing apratus as instructed by their tutorial. I've gone over it three times!
Second question: When I do launch the app on the emulator, the Connection Error dialog shows up fine. I hit retry, and it works. I hit Cancel, and it kills the app. However, if I simply click anywhere else in the window, outside the dialog, it closes the dialog and the app works normally. That kindof defeats the whole purpose, eh? How do I make that... not so?
Just in case I'm an idiot and the error lies elsewhere, here's the whole class:
private static final int DIALOG_RETRY = 10;
private static final int DIALOG_ERROR=20;
private static final byte[] SALT = {1,2,3,4,5,6,72,88,-37,-55,-23,34,22,14,15,16,17,18,19,-20};
private static final String BASE64_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqvh1xrNmvio909T06vAUxW3rtc98E3xNLA6qR/zdq2zHNW tQUJkDmJGukrkWj4Vd38NiD+nW92MX3HY2/dfw4AIcwS2oyeYceYc3hi4y2KeVL84y3DrOO0fCKNqBr6/Ve0cefN9HVyy57Psl4B0y8OaG9500xuEUeguO+PyIAMqFrtHVyi/seimnrcYLTYJo9IfGTRhcwi6QqQE8OlplidaT+uYwR4hNfcNLbnWnr7xDeG5gL2usibFPg+cvhFVhIGKO/aFuAVUIH2Yoarudc888X3/ZjTbmYAGuGhS8GRxiHhTVknCznX3BcxBJNeMA+xPTZ4OnaryRkHVvoJx5WQIDAQAB";
private LicenseCheckerCallback checkerCB;
private LicenseChecker checker;
TextView title, description, cure;
ImageView image;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//LICENSING
checkerCB = new CallBack();
final TelephonyManager tm = (TelephonyManager) getBaseContext().getSystemService(Context.TELEPHONY_SERVICE);
checker = new LicenseChecker(
this, new ServerManagedPolicy(this,
new AESObfuscator(SALT, getPackageName(),tm.getDeviceId())),
BASE64_PUBLIC_KEY);
checker.checkAccess(checkerCB);
//END LICENSING
setContentView(R.layout.activity_main);
title = (TextView)findViewById(R.id.title);
description = (TextView)findViewById(R.id.description);
image = (ImageView)findViewById(R.id.image);
cure =(TextView)findViewById(R.id.cure);
Spinner dropdown = (Spinner)findViewById(R.id.mainMenu);
//List Menu Items
final String options[] = {
//TURF DISEASES
"-Turf Diseases-", "Dollar Spot","Red Thread","Pythium Blight", "Necrotic Ring","Summer Patch","Brown Patch","Fairy Ring"
,"White Patch","Rust"
//TURF INSECTS
,"-Turf Insects-","Chinch Bug","Army Worm","Hunting Billbug","Aphid","Black Cutworm","Leaf Hopper","White Grub"
//ORNAMENTAL DISEASES
,"-Ornamental Diseases-","Powdery Mildew","Leaf Spot"
//ORNAMENTAL INSECTS
,"-Ornamental Insects-","Aphid","Leaf Miner","Japanese Beatle","Spider Mites","White Fly","Euonymus Scale","Web Worm"
};
//End List Menu Items
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,options);
dropdown.setAdapter(adapter);
dropdown.setOnItemSelectedListener(new OnItemSelectedListener(){
public void onItemSelected(AdapterView<?> parent, View v,
int position, long id) {
newSelection(options[position]);
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void newSelection(String selection){
if(!selection.contains("-")){
title.setText(selection);
selection=selection.replace(" ", "_");
selection=selection.toUpperCase();
description.setText(getResourceID("DESC_"+selection, R.string.class));
image.setImageResource(getResourceID(selection.toLowerCase(), R.drawable.class));
}else{
title.setText("Select a disease or insect.");
description.setText("");
cure.setText("");
image.setImageResource(getResourceID("logo", R.drawable.class));
}
}
#SuppressWarnings("rawtypes")
public int getResourceID(String name, Class resType){
try{
Class res = null;
if(resType == R.drawable.class)
res=R.drawable.class;
if(resType==R.id.class)
res=R.id.class;
if(resType==R.string.class)
res=R.string.class;
java.lang.reflect.Field field = res.getField(name);
int retID = field.getInt(null);
return retID;
}catch(Exception e){
}return 0;
}
protected void onResume() {
newSelection("-");
super.onPause();
}
protected void onDestroy(){
super.onDestroy();
checker.onDestroy();
}
//LICENSING CALLBACK CLASS
private class CallBack implements LicenseCheckerCallback{
public void allow(int reason) {
if(isFinishing()){
return;
}
displayResults("Access Granted");
}
public void dontAllow(int reason) {
if(isFinishing()){
return;
}
displayResults("Access Denied");
if(reason==Policy.RETRY){
showDialog(DIALOG_RETRY);
}else{
showDialog(DIALOG_ERROR);
}
}
public void applicationError(int errorCode) {
dontAllow(0);
}
public void displayResults(String result){
}
}
//DIALOG CLASS AND ACTION LISTENERS
protected Dialog onCreateDialog(int id){
switch(id){
case DIALOG_RETRY:
Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Connection Error: Retry?");
builder.setCancelable(true);
builder.setPositiveButton("Retry", new RetryOnClickListener());
builder.setNegativeButton("Cancel", new CancelOnClickListener());
AlertDialog dialog = builder.create();
dialog.show();
break;
case DIALOG_ERROR:
Builder builder1 = new AlertDialog.Builder(this);
builder1.setMessage("Would you like to purchase Landscape ID! ?");
builder1.setCancelable(true);
builder1.setPositiveButton("Yes!", new BuyOnClickListener());
builder1.setNegativeButton("No.", new CancelOnClickListener());
AlertDialog dialog1 = builder1.create();
dialog1.show();
break;
}
return super.onCreateDialog(id);
}
private final class RetryOnClickListener implements
DialogInterface.OnClickListener{
public void onClick(DialogInterface dialog, int which) {
checker.checkAccess(checkerCB);
}
}
private final class CancelOnClickListener implements
DialogInterface.OnClickListener{
public void onClick(DialogInterface dialog, int which) {
onDestroy();
finish();
}
}
private final class BuyOnClickListener implements
DialogInterface.OnClickListener{
public void onClick(DialogInterface dialog, int which) {
Intent open = new Intent(Intent.ACTION_VIEW);
open.setData(Uri.parse("market://details? id=com.mustaroenterprise.landscapeid"));
startActivity(open);
}
}
}
For your second question, I would set setCanceledOnTouchOutside to false like so:
Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Connection Error: Retry?");
builder.setCancelable(true);
builder.setPositiveButton("Retry", new RetryOnClickListener());
builder.setNegativeButton("Cancel", new CancelOnClickListener());
AlertDialog dialog = builder.create();
//Add this
dialog.setCanceledOnTouchOutside(false);
dialog.show();

How to use return value of a method in a another class in android

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

Code breaks at AlertDialog creation. I think I have Context wrong...?

i can't seem to figure out why my app/code is crashing in this section. Any help would be appreciated. I think the problem lies on the creation of an AlertDialog in the else if statement.
Basically, this method is called on first launch of the application and asks the user to choose between two options: OCPS and Other. When OCPS is chosen, a SharedPreference is set. When other is selected, an AlertDialog with text box should pop up, allowing the user to input their own local URL, which is then saved to the SharedPreference.
Full code is available here: https://github.com/danielblakes/progressbook/
code follows:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
boolean firstrun = getSharedPreferences(
"com.danielblakes.progressbook", MODE_PRIVATE).getBoolean(
"firstrun", true);
if (firstrun) {
new AlertDialog.Builder(this).setTitle("First Run").show();
pickDistrict(this);
getSharedPreferences("com.danielblakes.progressbook", MODE_PRIVATE)
.edit().putBoolean("firstrun", false).commit();
}
else {
String saved_district = getSharedPreferences(
"com.danielblakes.progressbook", MODE_PRIVATE).getString(
"district", null);
startupWebView(saved_district);
}
}
public Dialog pickDistrict(final Context context) {
AlertDialog.Builder districtalert = new AlertDialog.Builder(context);
districtalert
.setTitle(R.string.choose_district)
.setItems(R.array.districts,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int i) {
if (i == 0) {
String district_site = "https://parentaccess.ocps.net/General/District.aspx?From=Global";
startupWebView(district_site);
getSharedPreferences(
"com.danielblakes.progressbook",
MODE_PRIVATE)
.edit()
.putString("district",
district_site).commit();
} else if (i == 1) {
AlertDialog.Builder customdistrict = new AlertDialog.Builder(context);
customdistrict
.setTitle(
R.string.custom_district_title)
.setMessage(
R.string.custom_district_message);
final EditText input = new EditText(
getParent());
customdistrict.setView(input);
customdistrict
.setPositiveButton(
"Ok",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
String custom_url = input
.getText()
.toString();
getSharedPreferences(
"com.danielblakes.progressbook",
MODE_PRIVATE)
.edit()
.putString(
"district",
custom_url)
.commit();
}
});
customdistrict
.setNegativeButton(
"Cancel",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
return;
}
}).show();
}
}
}).show();
return districtalert.create();
}
}
Change
AlertDialog.Builder customdistrict = new AlertDialog.Builder(this);
to
AlertDialog.Builder customdistrict = new AlertDialog.Builder(context);
also,
final EditText input = new EditText(getParent());
needed to be changed to
final EditText input = new EditText(context);

Categories