Why OnClickListner is not called on clicking? - android

This is my code for the BASE class, i am inheriting this class to another child class. And from that class i am calling this function ActiveSMSPackage(). My code is perfect which has not kind of any error but yet the method is not called. Can you guys tell me where i am doing wrong?
public class PrepaidSMSBase extends Activity {
private String smsNumber = "";
private String smsPackageName;
private String smsPrice;
private String smsTitle;
private String smsText;
public PrepaidSMSBase(){}
public void setSmsPackageInformation(String smsTitle, String smsPackageName, String smsPrice, String smsNumber, String smsText)
{
this.smsTitle = smsTitle;
this.smsPackageName = smsPackageName;
this.smsPrice = smsPrice;
this.smsNumber = smsNumber;
this.smsText = smsText;
}
public void activeSMSPackage()
{
try
{AlertDialog.Builder builder = new AlertDialog.Builder(PrepaidSMSBase.this);
builder.setTitle(smsTitle);
builder.setMessage("Are you sure you want to active" + PrepaidSMSBase.this.smsPackageName + "in RS: " +
PrepaidSMSBase.this.smsPrice);
builder.setPositiveButton("Activate", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Uri uri = Uri.parse("smsto:" + smsNumber);
Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
intent.putExtra("sms_body", smsText);
startActivity(intent);
Toast.makeText(getApplicationContext(), "Please click send button to activate desire Package", Toast.LENGTH_LONG).show();
}
});
}catch (ActivityNotFoundException e){
e.printStackTrace();
}
}
Code of Child class is:
public class SMSCheckClass extends PrepaidSMSBase implements View.OnClickListener{
Button checkButton;
public SMSCheckClass(){
setSmsPackageInformation("Test 1","Some Thing","50","660","Sub");
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.checksms);
checkButton = (Button)findViewById(R.id.chkBtn);
checkButton.setOnClickListener(this);
}
#Override
public void onClick(View v)
{
activeSMSPackage();
}

Use this code
{AlertDialog.Builder builder = new AlertDialog.Builder(PrepaidSMSBase.this);
builder.setTitle(smsTitle);
builder.setMessage("Are you sure you want to active" + PrepaidSMSBase.this.smsPackageName + "in RS: " +
PrepaidSMSBase.this.smsPrice);
builder.setPositiveButton("Activate", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Uri uri = Uri.parse("smsto:" + smsNumber);
Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
intent.putExtra("sms_body", smsText);
startActivity(intent);
Toast.makeText(getApplicationContext(), "Please click send button to activate " + PrepaidSMSBase.this.smsPackageName, Toast.LENGTH_LONG).show();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
you just need to add builder.show() in the end of AlertDialog because your function is written inside of AlertDialog and that show() method is used to show AlertDialog

At first, you should show you dialog in activeSMSPackage, please add this code in that method:
builder.show()

Related

Camera app gets closed in android marshmallow

I have created an app in which the user can take pics using their default camera.It works fine in older versions that is till lollipop but when i try to run the app in marshmallow the app gets closed.
So i have added some codes to give permission for the camera app by the user but even it is not working.
public class Cam extends Activity{
String receivingdata;
TextView namecat;
String amount,vat;
private static final String TAG = Cam.class.getSimpleName();
ImageButton imgview,imgchart,imgexit;
Boolean isInternetPresent = false;
ConnectionDetector cd;
AlertDialog alert;
ImageButton btgoback,btcaptureagain,btnpreview;
static TextView tv;
private ImageView imgPreview;
private ProgressDialog pDialog;
public static final int progress_bar_type = 0;
public static Bitmap bitmap;
final Context context=this;
ConnectionClass connectionClass;
private static final String IMAGE_CAPTURE_FOLDER = "Receipt";
private static final int CAMERA_PIC_REQUEST = 1111;
private static File file;
private Uri ImagefileUri;
private static final String PREF_FIRSTLAUNCH_HELP = "helpcmaera";
private boolean helpDisplayed = false;
private static final String LOGIN_URL = "http://balajee2777-001-site1.1tempurl.com/backup-07032016/Receiptphp/receipts.php";
#Override
public void onBackPressed() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
alertDialogBuilder.setTitle("Receipt");
alertDialogBuilder
.setMessage("Would you Like to go previous Page!")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
Intent i=new Intent(Cam.this,ListAct.class);
startActivity(i);
Cam.this.finish();
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.camcod);
cd = new ConnectionDetector(getApplicationContext());
isInternetPresent = cd.isConnectingToInternet();
Bundle b = getIntent().getExtras();
receivingdata = b.getString("key");
tv = (TextView)findViewById(R.id.camcodname);
tv.setText(receivingdata);
tv.setVisibility(View.INVISIBLE);
String[] bits=receivingdata.split("_");
String catname = bits[0];
String vatname= bits[1];
connectionClass= new ConnectionClass();
imgPreview = (ImageView) findViewById(R.id.imgpreview);
namecat=(TextView)findViewById(R.id.tvcatnamess);
namecat.setText(catname);
imgview=(ImageButton)findViewById(R.id.camlinearrecep);
imgchart=(ImageButton)findViewById(R.id.camlinearchart);
imgexit=(ImageButton)findViewById(R.id.camlinearexit);
btgoback=(ImageButton)findViewById(R.id.bgoback);
btnpreview=(ImageButton)findViewById(R.id.btnpreview);
btcaptureagain=(ImageButton)findViewById(R.id.bcaptureagain);
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
showcamera();
}else {
Intent intent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
ImagefileUri = Uri.fromFile(getFile());
intent.putExtra(MediaStore.EXTRA_OUTPUT, ImagefileUri);
startActivityForResult(intent, CAMERA_PIC_REQUEST);
}
showHelpForFirstLaunch();
btgoback.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(isInternetPresent) {
showreceipt();
}else{
neti();
}
}
});
btnpreview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(Cam.this,DeleteMainAct.class);
startActivity(i);
}
});
btcaptureagain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
showcamera();
}else {
Intent intent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
ImagefileUri = Uri.fromFile(getFile());
intent.putExtra(MediaStore.EXTRA_OUTPUT, ImagefileUri);
startActivityForResult(intent, CAMERA_PIC_REQUEST);
}
}
});
imgview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
// set title
alertDialogBuilder.setTitle("Receipt");
// set dialog message
alertDialogBuilder
.setMessage("Would you Like to view receipts!")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, close
// current activity
Intent i =new Intent(Cam.this,Viewreceipt.class);
startActivity(i);
Cam.this.finish();
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
});
imgchart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
// set title
alertDialogBuilder.setTitle("Receipt");
// set dialog message
alertDialogBuilder
.setMessage("Would you Like to see report!")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, close
// current activity
Intent i =new Intent(Cam.this,Chartboy.class);
startActivity(i);
Cam.this.finish();
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
});
imgexit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
// set title
alertDialogBuilder.setTitle("Receipt");
// set dialog message
alertDialogBuilder
.setMessage("Would you Like to exit!")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, close
// current activity
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if(requestCode==CAMERA_PIC_REQUEST){
if(grantResults[0]==PackageManager.PERMISSION_GRANTED){
Intent intent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
ImagefileUri = Uri.fromFile(getFile());
intent.putExtra(MediaStore.EXTRA_OUTPUT, ImagefileUri);
startActivityForResult(intent, CAMERA_PIC_REQUEST);
}else{
Toast.makeText(this,"Camera permission not granted",Toast.LENGTH_SHORT).show();
}
}else{
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
private void showcamera() {
if(checkSelfPermission(android.Manifest.permission.CAMERA)== PackageManager.PERMISSION_GRANTED){
Intent intent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
ImagefileUri = Uri.fromFile(getFile());
intent.putExtra(MediaStore.EXTRA_OUTPUT, ImagefileUri);
startActivityForResult(intent, CAMERA_PIC_REQUEST);
}else{
if(shouldShowRequestPermissionRationale(Manifest.permission.CAMERA)){
Toast.makeText(this,"Camera permission is needed to show the preview",Toast.LENGTH_SHORT).show();
}
requestPermissions(new String[]{Manifest.permission.CAMERA}, CAMERA_PIC_REQUEST);
}
}
private void showHelpForFirstLaunch() {
helpDisplayed = getPreferenceValue(PREF_FIRSTLAUNCH_HELP, false);
if (!helpDisplayed) {
showHelp();
savePreference(PREF_FIRSTLAUNCH_HELP, true);
}else if(helpDisplayed){
return;
}
}
private void showHelp() {
final View instructionsContainer = findViewById(R.id.container_help);
instructionsContainer.setVisibility(View.VISIBLE);
instructionsContainer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
instructionsContainer.setVisibility(View.INVISIBLE);
}
});
}
private boolean getPreferenceValue(String key, boolean defaultValue) {
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
return preferences.getBoolean(key, defaultValue);
}
private void savePreference(String key, boolean value) {
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean(key, value);
editor.commit();
}
private File getFile() {
String filepath = Environment.getExternalStorageDirectory().getPath();
file = new File(filepath, IMAGE_CAPTURE_FOLDER);
if (!file.exists()) {
file.mkdirs();
}
String names=tv.getText().toString();
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
return new File(file + File.separator + names+"_"+timeStamp
+ ".jpg");
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == CAMERA_PIC_REQUEST) {
imgPreview.setVisibility(View.VISIBLE);
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int dw = size.x;
int dh = size.y;
// Load up the image's dimensions not the image itself
BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
bmpFactoryOptions.inJustDecodeBounds = true;
Bitmap bmp = BitmapFactory.decodeFile(ImagefileUri.getPath(),
bmpFactoryOptions);
int heightRatio = (int) Math.ceil(bmpFactoryOptions.outHeight
/ (float) dh);
int widthRatio = (int) Math.ceil(bmpFactoryOptions.outWidth
/ (float) dw);
Log.v("HEIGHTRATIO", "" + heightRatio);
Log.v("WIDTHRATIO", "" + widthRatio);
if (heightRatio > 1 && widthRatio > 1) {
if (heightRatio > widthRatio) {
// Height ratio is larger, scale according to it
bmpFactoryOptions.inSampleSize = heightRatio;
} else {
// Width ratio is larger, scale according to it
bmpFactoryOptions.inSampleSize = widthRatio;
}
}
// Decode it for real
bmpFactoryOptions.inJustDecodeBounds = false;
bmp = BitmapFactory.decodeFile(ImagefileUri.getPath(),
bmpFactoryOptions);
imgPreview.setImageBitmap(bmp);
}
} else if (resultCode == RESULT_CANCELED) {
// user cancelled Image capture
Toast.makeText(getApplicationContext(),
"User cancelled image capture", Toast.LENGTH_SHORT).show();
} else {
// failed to capture image
Toast.makeText(getApplicationContext(),
"Sorry! Failed to capture image", Toast.LENGTH_SHORT)
.show();
}
}
private void neti() {
final LayoutInflater layoutInflater = LayoutInflater.from(Cam.this);
final View promptView = layoutInflater.inflate(R.layout.connectionlost, null);
final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(Cam.this);
alertDialogBuilder.setView(promptView);
alertDialogBuilder.setCancelable(false);
final Button retry=(Button)promptView.findViewById(R.id.btnretry);
retry.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent=getIntent();
finish();
startActivity(intent);
}
});
alert= alertDialogBuilder.create();
alert.show();
}
private void showreceipt() {
LayoutInflater repcard=LayoutInflater.from(Cam.this);
View promptView=repcard.inflate(R.layout.moneyreceipt,null);
AlertDialog.Builder alertDialogBuilder=new AlertDialog.Builder(Cam.this);
alertDialogBuilder.setCancelable(false);
alertDialogBuilder.setView(promptView);
final EditText amt=(EditText)promptView.findViewById(R.id.edamt);
final EditText vta=(EditText)promptView.findViewById(R.id.edvat);
final TextView tvs=(TextView)promptView.findViewById(R.id.tvamount);
final TextView tvat=(TextView)promptView.findViewById(R.id.tvvat);
tvs.setVisibility(View.INVISIBLE);
tvat.setVisibility(View.INVISIBLE);
amt.setRawInputType(Configuration.KEYBOARD_12KEY);
vta.setRawInputType(Configuration.KEYBOARD_12KEY);
final Button save=(Button)promptView.findViewById(R.id.btnmoneysave);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
tvs.setText(amt.getText().toString());
tvat.setText(vta.getText().toString());
amount=tvs.getText().toString();
vat=tvat.getText().toString();
// Toast.makeText(Cam.this, amount, Toast.LENGTH_LONG).show();
//Toast.makeText(Cam.this, vat, Toast.LENGTH_LONG).show();
detailsreceiptupload();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
private void detailsreceiptupload() {
String[] bits=receivingdata.split("_");
String catname = bits[0];
String cdte=bits[1];
String[] nyte=cdte.split("#");
String email=nyte[0];
String cdate=nyte[1];
String cimagetag=tv.getText().toString();
//String amt=tvs.getText().toString();
userLogin(catname, cdate,email,cimagetag,amount,vat);
}
private void userLogin(String catname, String cdate, String email, String cimagetag, String amount, String vat) {
class UserLoginClass extends AsyncTask<String,Void,String> {
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(Cam.this, "Connecting to Cloud", null, true, true);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
if(s.equalsIgnoreCase("success")) {
DoLogin dologin=new DoLogin();
dologin.execute("");
}
else
{
Toast.makeText(Cam.this,s,Toast.LENGTH_LONG).show();
}
}
#Override
protected String doInBackground(String... params) {
HashMap<String,String> data = new HashMap<>();
data.put("catname",params[0]);
data.put("cdate",params[1]);
data.put("email",params[2]);
data.put("cimagetag",params[3]);
data.put("amount",params[4]);
data.put("vat",params[5]);
RegisterUserClass ruc = new RegisterUserClass();
String result = ruc.sendPostRequest(LOGIN_URL,data);
return result;
}
}
UserLoginClass ulc = new UserLoginClass();
ulc.execute(catname,cdate,email,cimagetag,amount,vat);
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case progress_bar_type:
pDialog = new ProgressDialog(this);
pDialog.setMessage("Processing...");
pDialog.setIndeterminate(true);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setProgressNumberFormat(null);
pDialog.setProgressPercentFormat(null);
pDialog.setCancelable(false);
pDialog.show();
return pDialog;
default:
return null;
}
}
class DoLogin extends AsyncTask<String,String,String> {
String z="";
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}
#Override
protected String doInBackground(String... params) {
String ExternalStorageDirectoryPath = Environment
.getExternalStorageDirectory()
.getAbsolutePath();
String targetPath = ExternalStorageDirectoryPath + "/Receipt";
File targetDirector = new File(targetPath);
File[] files = targetDirector.listFiles();
File destinationdir = new File(Environment.getExternalStorageDirectory() ,"/CompressedImage");
if (!destinationdir.exists()) {
destinationdir.mkdirs();
}
for(File file1:files){
FileOutputStream fos=null;
try{
File file=new File(destinationdir,file1.getName());
fos=new FileOutputStream(file);
Bitmap bm = BitmapFactory.decodeFile(file1.getAbsolutePath());
bm.compress(Bitmap.CompressFormat.JPEG, 25, fos);
fos.flush();
fos.close();
MediaStore.Images.Media.insertImage(getContentResolver(), destinationdir.getPath(), file.getName(), file.getName());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return z;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
String ExternalStorageDirectoryPath = Environment
.getExternalStorageDirectory()
.getAbsolutePath();
String targetPath = ExternalStorageDirectoryPath + "/Receipt";
File targetDirector = new File(targetPath);
File[] files = targetDirector.listFiles();
for (File file : files) {
file.delete();
}
Intent i=new Intent(Cam.this,ReceiptGrid.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
Cam.this.finish();
dismissDialog(progress_bar_type);
}
protected void onProgressUpdate(String... progress) {
pDialog.setProgress(Integer.parseInt(progress[0]));
}
}}
I have used an condition to check the phones version.If it is marshmallow then i have given a method name showcamera to do the functions for marshmallow
ShowCamera:
private void showcamera() {
if(checkSelfPermission(android.Manifest.permission.CAMERA)== PackageManager.PERMISSION_GRANTED){
Intent intent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
ImagefileUri = Uri.fromFile(getFile());
intent.putExtra(MediaStore.EXTRA_OUTPUT, ImagefileUri);
startActivityForResult(intent, CAMERA_PIC_REQUEST);
}else{
if(shouldShowRequestPermissionRationale(Manifest.permission.CAMERA)){
Toast.makeText(this,"Camera permission is needed to show the preview",Toast.LENGTH_SHORT).show();
}
requestPermissions(new String[]{Manifest.permission.CAMERA}, CAMERA_PIC_REQUEST);
}
}

Barcode Scanner in Fragment

I'm trying to insert a barcode scanner in my ListFragment and use this tutorial: BarcodeScanner
But if I click on of the two buttons (QR or barcode-scan), it seems that my app doesn't find the downloaded XZing Barcode Scanner. But it is installed! I don't get an issue :-( ...
I think something is wrong in the try-part
Here is the code of my ListFragment:
private Button b1;
private Button b2;
static final String ACTION_SCAN = "com.google.xzing.client.android.SCAN";
#Override
public void onActivityCreated(final Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
b1 = (Button) getView().findViewById(R.id.button_scan_barcode_ean);
b2 = (Button) getView().findViewById(R.id.button_scan_qr_code);
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
scanQR(v);
}
});
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
scanBar(v);
}
});
}
public void scanBar(View v){
try {
Intent intent = new Intent(ACTION_SCAN);
intent.putExtra("SCAN_MODE", "PRODUCT_MODE");
startActivityForResult(intent, 0);
}
catch (ActivityNotFoundException anfe){
showDialog(getActivity(), "No Scanner Found", "Download a scanner code activity?", "Yes", "No").show();
}
}
public void scanQR(View v){
try {
Intent intent = new Intent(ACTION_SCAN);
intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
startActivityForResult(intent, 0);
}
catch (ActivityNotFoundException anfe){
showDialog(getActivity(), "No Scanner Found", "Download a scanner code activity?", "Yes", "No").show();
}
}
private static AlertDialog showDialog(final Activity act, CharSequence title,
CharSequence message,
CharSequence buttonYes,
CharSequence buttonNo) {
AlertDialog.Builder downloadDialog = new AlertDialog.Builder(act);
downloadDialog.setTitle(title);
downloadDialog.setMessage(message);
downloadDialog.setPositiveButton(buttonYes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Uri uri = Uri.parse("market://search?q=pname:" + "com.google.zxing.client.android");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
try {
act.startActivity(intent);
} catch (ActivityNotFoundException anfe) {
}
}
});
downloadDialog.setNegativeButton(buttonNo, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
return downloadDialog.show();
}
public void onActivityResult(int requestCode, int resultCode, Intent intent){
if (requestCode == 0){
if (resultCode == Activity.RESULT_OK){
String contents = intent.getStringExtra("SCAN_RESULT");
String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
Toast toast = Toast.makeText(getActivity(), "Content:" + contents + "Format" + format, Toast.LENGTH_LONG);
toast.show();
final EditText editTextBarcode = (EditText) getView().findViewById(R.id.editText_barcode);
editTextBarcode.setText(contents);
}
}
}
Any ideas?
There is a typo in your ACTION_SCAN String. You wrote "xzing" instead of "zxing".
The correct String is
"com.google.zxing.client.android.SCAN"

Properly setting up an alertdialog on Activity closing?

I have an activity with two score numbers. I want the user to choose a winner if they're the same when it closes (i.e. player 1 or player2). As a .NET person, I'm trying to basically do the MessageBox.
Unfortunately, from what I've read, android doesn't do UI threads the same way. And that the activity has "a leaked window". I looked on SO and I saw the idea was to put "dismiss" in "onPause". However, I didn't see a "onPause" function and was confused to how to implement it. So I tried what I have below, but got the same error.
What can I do to this guy in order to make sure this works properly?
public void onFinish(View v) {
//get scores
TextView score1tv = (TextView) findViewById(R.id.tvScore1);
score1 = score1tv.getText().toString();
TextView score2tv = (TextView) findViewById(R.id.tvScore2);
score2 = score2tv.getText().toString();
//Make sure they aren't the same
int i_Score1 = Integer.parseInt(score1);
int i_Score2 = Integer.parseInt(score2);
if (i_Score1 == i_Score2){
//alert user
new AlertDialog.Builder(this)
.setTitle("Duplicate score")
.setMessage("Whose score won the bout?")
.setPositiveButton(boutData[1], new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//fencer 1 won
score1 = "V" + score1;
dialog.dismiss();
}
})
.setNegativeButton(boutData[3], new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
score2 = "V" + score2;
dialog.dismiss();
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.create()
.show();
}
Intent intent = new Intent();
intent.putExtra("edittextvalue","value_here");
setResult(RESULT_OK, intent);
finish();
}
Edit: Here's the solution I came to thanks to the help I received:
public void onFinish(View v) {
//get scores
TextView score1tv = (TextView) findViewById(R.id.tvScore1);
score1 = score1tv.getText().toString();
TextView score2tv = (TextView) findViewById(R.id.tvScore2);
score2 = score2tv.getText().toString();
//Make sure they aren't the same
int i_Score1 = Integer.parseInt(score1);
int i_Score2 = Integer.parseInt(score2);
if (score1 == score2){
//alert user
new AlertDialog.Builder(this)
.setTitle("Duplicate score")
.setMessage("Whose score won the bout?")
.setPositiveButton(boutData[1], new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//fencer 1 won
score1 = "V" + score1;
//close out
Intent intent = new Intent();
intent.putExtra("edittextvalue","value_here");
setResult(RESULT_OK, intent);
finish();
}
})
.setNegativeButton(boutData[3], new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
score2 = "V" + score2;
//close out
Intent intent = new Intent();
intent.putExtra("edittextvalue","value_here");
setResult(RESULT_OK, intent);
finish();
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.create()
.show();
}
else{
Intent intent = new Intent();
intent.putExtra("edittextvalue","value_here");
setResult(RESULT_OK, intent);
finish();
}
}
Put the last four lines into an else clause and do something similar in your onClick methods.
Also you shouldn't have to call dialog.dismiss() manually.

Error: The constructor Object(EditText) is undefined

I'm getting an error in this method: "The constructor Object(EditText) is undefined"
private void setupAlert()
{
Log.d(TAG, "setupAlert()");
LayoutInflater li = LayoutInflater.from(this);
View promptsView = li.inflate(R.layout.emaildialog, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setView(promptsView);
final EditText userInput = (EditText)promptsView.findViewById(R.id.editTxtEmailAddress);
alertDialogBuilder.setCancelable(false).setPositiveButton("OK", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
updatePref(userInput.getText().toString());
Log.d(MainActivity.TAG, "setupAlert: getPreference()=" + getPreference());
takeSnapNow();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.colour_selector);
Log.d(TAG, "onCreate: getPreference()=" + getPreference());
if (getPreference().equals("")) {
setupAlert();
takeSnapNow();
} else {
takeSnapNow();
}
}
private void takeSnapNow()
{
String fileName = "TempImage.jpg";
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
values.put(MediaStore.Images.Media.DESCRIPTION, "Captured by XYZ app");
imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
Please suggest the solution to this error.
Edit: Corrected the above error by removing UserInput as suggested by others. However the alertDialog is still not shown. The logic is to check the sharedpref initially in onCreate, and if not found, call setupAlert() method to get email ID from user.
Any clues? Changed code updated in the above snippet.
DialogInterface.OnClickListener doesn't take an EditText as a constructor parameter and you don't need to do that ! you can use userInput without passing it to DialogInterface.OnClickListener, just use it as follow
alertDialogBuilder.setCancelable(false).setPositiveButton("OK", new DialogInterface.OnClickListener() {
Why are you using "new DialogInterface.OnClickListener(userInput)"?
Just use new DialogInterface.OnClickListener()

making phone call from DialogBox in Android

I have one DialogBox with 2 buttons. If we click the +ve button, it attempts to open the Dialing Pad; else if we click the -ve button it closes the dialog. When I click the +ve button it shows the null exception. If the same code executes without the DialogBox, it is fine.
Here is my code:
callDialog.setPositiveButton("Call Now", new android.DialogInterface.
OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent dial = new Intent();
dial.setAction("android.intent.action.DIAL");
try {
dial.setData(Uri.parse("tel:9951037343"));
startActivity(dial);
} catch (Exception e) {
Log.e("Calling", "" + e.getMessage());
}
}
}
I've given permissions in the manifest file as <uses-permission android:name="android.permission.CALL_PHONE"/>
Try this..
Intent call = new Intent(Intent.ACTION_DIAL);
call.setData(Uri.parse("tel:phonenumber");
startActivity(call);
Remove the #Overrride line.
Like this:
callDialog.setPositiveButton("Call Now", new android.DialogInterface.
OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent dial = new Intent();
dial.setAction("android.intent.action.DIAL");
try {
dial.setData(Uri.parse("tel:9951037343"));
startActivity(dial);
} catch (Exception e) {
Log.e("Calling", "" + e.getMessage());
}
}
}
----UPDATE-----
Since you havent posted any logcat, its hard to know where it crashes. Try this block:
AlertDialog.Builder callDialog = new AlertDialog.Builder(this);
callDialog.setTitle("My title");
callDialog.setMessage("My message");
callDialog.setPositiveButton("Call", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent dial = new Intent();
dial.setAction("android.intent.action.DIAL");
try {
dial.setData(Uri.parse("tel:9951037343"));
startActivity(dial);
} catch (Exception e) {
Log.e("Calling", "" + e.getMessage());
}
}
});
callDialog.setNegativeButton("Cancel", null);
callDialog.show();
Try the following---
Intent dial = new Intent(Intent.ACTION_DIAL);
//dial.setAction("android.intent.action.DIAL");
try {
dial.setData(Uri.parse("tel:9951037343"));
startActivity(dial);
} catch (Exception e) {
Log.e("Calling", "" + e.getMessage());
}
startActivity(dial);
Use
Intent callIntent = new Intent(Intent.ACTION_CALL);
instead of this
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setAction("android.intent.action.DIAL"); // but this line is an optional one
callIntent.setData(Uri.parse("tel:044 6000 6000"));
startActivity(callIntent);
use this code......
String number = "tel:" + phonenumber;
Intent intent = new Intent(Intent.ACTION_CALL, Uri
.parse(number));
startActivity(intent);
give permission in manifest: <uses-permission android:name="android.permission.CALL_PHONE" />
updated.....
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.menu_icon_pager).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new AlertDialog.Builder(MainActivity.this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Exit")
.setMessage(
"Texting from dialog")
.setNegativeButton(android.R.string.cancel, null)
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// Exit the activity
String number = "tel:"+phonenumber ;
Intent intent = new Intent(Intent.ACTION_CALL, Uri
.parse(number));
startActivity(intent);
}
})
.show();
}
});
}
Actually I called the AlertDialog from another Activity,so I need the context of called
Activity's Context reference.So I passed the Context as a parameter to Called Activity
Here is Called Activity's code
if(position == 1)new CalledByActivity().dailingDialogBox(param1,
param2,context);//Here I'm passing the context as param
Here CalledBy activity's implemented function
public void dailingDialogBox(final String param1,String param2,final Context context){
Here I implemented in +ve button click
Intent dail = new Intent(Intent.ACTION_DIAL);
dail.setData(Uri.parse("tel:"+station_Number));
context.startActivity(dail);//Here the "context" is reference of called Activity's context

Categories

Resources