I am trying to make my own Alert dialogs using "utility" class that extends AppCompatDialogFragment. But when I try to set my own messages, they didn't change, but the default ones of the class I created continue to appear.
For example in my AlertDialogConnection class I made Override of onCreateDialog, but in my activity, while I perform http request, I can't make my own texts.
My own class that extends AppCompatDialogFragment
public class AlertDialogConnection extends AppCompatDialogFragment {
private Builder builder;
private String title;
private String text;
public AlertDialogConnection(){
this.builder = null;
this.text = "";
this.title = "";
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
if((this.title == "") || (this.text == "") || (this.builder == null)){
this.builder = new Builder(getActivity());
this.builder.setTitle("Error");
this.builder.setMessage("Default Error: Error! try later");
this.builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
System.exit(0);
}
});
}else {
this.builder = new Builder(getActivity());
this.builder.setTitle(this.title);
this.builder.setMessage(this.text);
this.builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
System.exit(0);
}
});
}
return builder.create();
}
public void setTitle(String title){
this.title = title;
}
public void setText(String text){
this.text = text;
}
}
Some code using that class
in this class, in case of error I continue to see the default error of the class AlertDialogConnection, instead of my serverError title and text.
private AlertDialogConnection serverError = new AlertdialogConnection();
private void requestData(String url) throws MalformedURLException {
Request request = new Request.Builder().url(url).build();
final Intent intent = new Intent(this, ModelResultData.class);
httpClient.connectTimeoutMillis(); //server timeout
httpClient.writeTimeoutMillis();
httpClient.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
Log.d("HTTP-Error", "HTTP request error!");
AlertDialogConnection errorDialog = new AlertDialogConnection();
errorDialog.setTitle("server error!");
errorDialog.setText("server messaging error, try later");
errorDialog.show(getSupportFragmentManager(), "messaging error!");
//Toast.makeText(getApplicationContext(), "results not found", Toast.LENGTH_LONG).show();
}
#Override
public void onResponse(#NotNull Call call, Response response) throws IOException {
if(response.isSuccessful()){
/* HTTP-code: 200 */
final String body = response.body().string();
ModelSearchActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
intent.putExtra("ACTIVITY_SOURCE", "ModelSearchActivity");
intent.putExtra("json_data", body);
startActivity(intent);
}
});
}else{
//System.out.println(response.code());
//if (response.code() == 403) {
//Toast.makeText(getApplicationContext(), "results not found", Toast.LENGTH_LONG).show();
//} else if (response.code() == 500) {
/* Http-code: 500 */
Log.d("HTTP-Error", "server error!");
serverError.setTitle("server error!");
serverError.setText("server error, try later");
serverError.show(getSupportFragmentManager(), "server error!");
//}
}
}
});
}
I have tried making comparisons with response code, but nothing change.
The default value (in the constructor) you've set for builder is null.
This causes it to always get through the if condition since builder == null would return true. Try something along the following lines,
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
this.builder = new Builder(getActivity());
if(this.title.isEmpty() || this.text.isEmpty()){
this.builder.setTitle("Error");
this.builder.setMessage("Default Error: Error! try later");
this.builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
System.exit(0);
}
});
}else {
this.builder.setTitle(this.title);
this.builder.setMessage(this.text);
this.builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
System.exit(0);
}
});
}
return builder.create();
}
You don't need to have a separate utility for creating your own alert dialogue you can simply create a view and use the setView method to show that view in your app. See the snippet below
private void showDialog()
{
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
View view = getLayoutInflater().inflate(R.layout.sortdialog,null);//Replace it
alertDialogBuilder.setView(view);
alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
This will allow you to create custom alert dialog boxes using the layout which you have created
I just want to clear app cache on exit when pressed, tried many answers out there but got errors and didn't work, so here is my code:
if (Config.ENABLE_EXIT_DIALOG) {
AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);
dialog.setIcon(R.mipmap.ic_launcher);
dialog.setTitle(R.string.app_name);
dialog.setMessage(R.string.dialog_close_msg);
dialog.setPositiveButton(R.string.dialog_option_yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
MainActivity.this.finish();
}
});
dialog.setNegativeButton(R.string.dialog_option_rate_us, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
final String appName = getPackageName();
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)));
}
MainActivity.this.finish();
}
});
dialog.setNeutralButton(R.string.dialog_option_more, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.play_more_apps))));
MainActivity.this.finish();
}
});
dialog.show();
} else {
super.onBackPressed();
}
got solved, i think it's old way but it's working fine found it here
i actually used his question code at the end of the my mainActivity file and it worked like a charm, though i guess it's an old way but it's ok.
and here is the code
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
clearApplicationData();
}
public void clearApplicationData() {
File cache = getCacheDir();
File appDir = new File(cache.getParent());
if (appDir.exists()) {
String[] children = appDir.list();
for (String s : children) {
if (!s.equals("lib")) {
deleteDir(new File(appDir, s));
Log.i("EEEEEERRRRRRROOOOOOORRRR", "**************** File /data/data/APP_PACKAGE/" + s + " DELETED *******************");
}
}
}
}
public static boolean deleteDir(File dir) {
if (dir != null && dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
return dir.delete();
}
I am trying to have an consumable item for my app.
i currently use this code:
private void BuyManager() {
mHelper.flagEndAsync();
mHelper.launchPurchaseFlow(this, "jm.admin", 1011, new IabHelper.OnIabPurchaseFinishedListener() {
#Override
public void onIabPurchaseFinished(IabResult result, Purchase info) {
AlertDialog.Builder succces = new AlertDialog.Builder(MainActivity.this);
int proccesed = 1;
try {
proccesed=mservice.consumePurchase(3,getPackageName(), "inapp:"+getPackageName()+":jm.admin");
} catch (RemoteException e) {
e.printStackTrace();
}
String succs = "nee";
if (proccesed==0){
succs = "ja";
}
succces.setMessage("We checken uw aankoop Aankoop gegevens: " + result + " Aankoop succesvol: "+succs);
succces.setPositiveButton("Oke", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
succces.show();
if (result.isSuccess()) {
AlertDialog.Builder succces2 = new AlertDialog.Builder(MainActivity.this);
succces2.setMessage("Uw aankoop is voltooid");
succces2.setPositiveButton("Oke", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
succces2.show();
}
}
});
}
but when i buy the item it not consumed at all and it haves the code 7 response (item already bought).
Whats wrong with my code?
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;
}
})