I am try to dismiss dialog in if condition true part but it is not worked.
In dialog entered in if condition but not dismiss.in If condition toast message display properly.
public void showIncomingCall() {
int getTotal = 0;
if(showincoming != null && showincoming.isShowing() )
{
//adapter1.notifyDataSetChanged();
//showincoming.dismiss();
return;
}
else {
showincoming = new Dialog(MainActivity.this);
showincoming.requestWindowFeature(Window.FEATURE_NO_TITLE);
showincoming.setContentView(R.layout.custome_dialog);
listdialog = (ListView) showincoming.findViewById(R.id.incoming_list);
//adapter1 = new CustomeListAdapter(MainActivity.this);
listdialog.setAdapter(adapter1);
//adapter1.notifyDataSetChanged();
close = (ImageButton) showincoming.findViewById(R.id.dialog_close);
close.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showincoming.dismiss();
adapter1.notifyDataSetChanged();
}
});
adapter1.notifyDataSetChanged();
for (int i = 0; i < listdialog.getCount(); i++) {
parentView = getViewByPosition(i, listdialog);
String getString = ((TextView) parentView.findViewById(R.id.tvLineStatus)).getText().toString();
if (getString.toString().equals("Idle") || getString.toString().equals("Disconnect") || getString.toString().equals("Dialing")) {
getTotal += 1;
}
}
if (getTotal >= 7) {
showincoming.dismiss();
Toast.makeText(getApplicationContext(),"getTotal" + getTotal,Toast.LENGTH_LONG).show();
adapter1.notifyDataSetChanged();
//adapter1.setNotifyOnChange(true);
}
//Toast.makeText(MainActivity.this,getTotal+"getTotal",Toast.LENGTH_LONG).show();
adapter1.notifyDataSetChanged();
listdialog.invalidateViews();
if(!showincoming.isShowing()) {
showincoming.show();
}
}
}
showincoming = new Dialog(MainActivity.this);
declare this below int getTotal = 0;
i.e outside else statement
then you can get referance of dialog object and can dissmiss dialog. try this and let me know
Related
I making android application,I need error popup in one moment and when popup is showing and I click OK,popup is closing but main layout is dark and doesn't work,it is freezing.
please see my code,Can I refresh or reactivate this layout?
I need any solution for this.
please help and thank you
package com.example.granturismo.binaryconverter;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.calculate:
try {
EditText decimal = findViewById(R.id.decimal_value);
EditText binary = findViewById(R.id.binary);
Dialog dlg = new Dialog(this);
dlg.setCancelable(false);
dlg.setTitle("Please Input Any Number");
dlg.show();
int decimal_value = Integer.parseInt(decimal.getText().toString());
List<Integer> binary_nums = new ArrayList<Integer>();
String result = "";
int nashti = 1;
for (int i = decimal_value; i >= 2; ) {
binary_nums.add((i % 2));
i = i / 2;
nashti = i;
}
binary_nums.add((nashti % 2));
for (int i = 0; i < binary_nums.size(); i++) {
result += "" + binary_nums.get(i);
}
binary.setText(new StringBuilder(result).reverse().toString());
}
catch(Exception e){
AlertDialog.Builder alert=new AlertDialog.Builder(this);
alert.setTitle("Error");
alert.setMessage("Please Input Any Number");
alert.setCancelable(true);
alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
}).show();
}
break;
case R.id.clear:
EditText decimal1=findViewById(R.id.decimal_value);
EditText binary1=findViewById(R.id.binary);
decimal1.setText("");
binary1.setText("");
break;
case R.id.shecvla:
Button shecvla=(Button) findViewById(R.id.shecvla);
TextView convertSign=(TextView) findViewById(R.id.convertSign);
if(shecvla.getText()==getString(R.string.dectobin)) {
shecvla.setText(getString(R.string.dectobin));
convertSign.setText(R.string.bintodec);
}
else{
shecvla.setText(getString(R.string.bintodec));
convertSign.setText(R.string.dectobin);
}
break;
}
}
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
public class MainActivity extends Activity {
private static final String TAG = "MainActivity";
ProductDatabase.ProductDatabaseHelper controller = new ProductDatabase.ProductDatabaseHelper(this);
EditText mBarcodeEdit;
EditText mFormatEdit;
EditText mTitleEdit;
EditText mPriceEdit;
private static final int ZBAR_SCANNER_REQUEST = 0;
private static final int ZBAR_QR_SCANNER_REQUEST = 1;
private static final ProductData mProductData = new ProductData();
Button mScanButton;
Button mAddButton;
Button mSelectButton;
Button mExportButton;
Button btnimport;
ProductDatabase mProductDb;
ListView ls;
TextView infotext;
File file = null;
// DatabaseHelper dbhelper = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ls = (ListView) findViewById(R.id.placeslist);
mBarcodeEdit = (EditText) findViewById(R.id.barcodeEdit);
mFormatEdit = (EditText) findViewById(R.id.codeFormatEdit);
mTitleEdit = (EditText) findViewById(R.id.titleEdit);
mPriceEdit = (EditText) findViewById(R.id.priceEdit);
mScanButton = (Button) findViewById(R.id.scan_btn);
mAddButton = (Button) findViewById(R.id.addButton);
mSelectButton = (Button) findViewById(R.id.selelctButton);
mProductDb = new ProductDatabase(this); // not yet shown
infotext = (TextView) findViewById(R.id.txtresulttext);
mExportButton = (Button) findViewById(R.id.exportbtn);
mSelectButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, product_list.class);
startActivity(i);
}
});
mAddButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String barcode = mBarcodeEdit.getText().toString();
String format = mFormatEdit.getText().toString();
String title = mTitleEdit.getText().toString();
String price = mPriceEdit.getText().toString();
String errors = validateFields(barcode, format, title, price);
if (errors.length() > 0) {
showInfoDialog(MainActivity.this, "Please fix errors", errors);
} else {
mProductData.barcode = barcode;
mProductData.format = format;
mProductData.title = title;
mProductData.price = new BigDecimal(price);
mProductDb.insert(mProductData);
showInfoDialog(MainActivity.this, "Success", "Product saved successfully");
resetForm();
}
}
});
mExportButton.setOnClickListener(new View.OnClickListener() {
SQLiteDatabase sqldb = controller.getReadableDatabase(); //My Database class
Cursor c =null;
#Override
public void onClick(View view) { //main code begins here
try {
c = sqldb.rawQuery("select * from spot_pay.db", null);
int rowcount = 0;
int colcount = 0;
File sdCardDir = Environment.getExternalStorageDirectory();
String filename = "MyBackUp.csv";
// the name of the file to export with
File saveFile = new File(sdCardDir, filename);
FileWriter fw = new FileWriter(saveFile);
BufferedWriter bw = new BufferedWriter(fw);
rowcount = c.getCount();
colcount = c.getColumnCount();
if (rowcount > 0) {
c.moveToFirst();
for (int i = 0; i < colcount; i++) {
if (i != colcount - 1) {
bw.write(c.getColumnName(i) + ",");
} else {
bw.write(c.getColumnName(i));
}
}
bw.newLine();
for (int i = 0; i < rowcount; i++) {
c.moveToPosition(i);
for (int j = 0; j < colcount; j++) {
if (j != colcount - 1)
bw.write(c.getString(j) + ",");
else
bw.write(c.getString(j));
}
bw.newLine();
}
bw.flush();
infotext.setText("Exported Successfully.");
}
} catch (Exception ex) {
if (sqldb.isOpen()) {
sqldb.close();
infotext.setText(ex.getMessage().toString());
}
} finally {
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
private void showInfoDialog(Context context, String title, String information) {
new AlertDialog.Builder(context)
.setMessage(information)
.setTitle(title)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).show();
}
private void resetForm() {
// TODO Auto-generated method stub
mBarcodeEdit.getText().clear();
mFormatEdit.getText().clear();
mTitleEdit.getText().clear();
mPriceEdit.getText().clear();
}
public void launchScanner(View v) {
if (isCameraAvailable()) {
Intent intent = new Intent(this, ZBarScannerActivity.class);
startActivityForResult(intent, ZBAR_SCANNER_REQUEST);
} else {
Toast.makeText(this, "Rear Facing Camera Unavailable", Toast.LENGTH_SHORT).show();
}
}
public void launchQRScanner(View v) {
if (isCameraAvailable()) {
Intent intent = new Intent(this, ZBarScannerActivity.class);
intent.putExtra(ZBarConstants.SCAN_MODES, new int[]{Symbol.QRCODE});
startActivityForResult(intent, ZBAR_SCANNER_REQUEST);
} else {
Toast.makeText(this, "Rear Facing Camera Unavailable", Toast.LENGTH_SHORT).show();
}
}
public boolean isCameraAvailable() {
PackageManager pm = getPackageManager();
return pm.hasSystemFeature(PackageManager.FEATURE_CAMERA);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case ZBAR_SCANNER_REQUEST:
case ZBAR_QR_SCANNER_REQUEST:
if (resultCode == RESULT_OK) {
mBarcodeEdit.setText(data.getStringExtra(ZBarConstants.SCAN_RESULT));
// Toast.makeText(this, "Scan Result = " + data.getStringExtra(ZBarConstants.SCAN_RESULT), Toast.LENGTH_SHORT).show();
} else if (resultCode == RESULT_CANCELED && data != null) {
String error = data.getStringExtra(ZBarConstants.ERROR_INFO);
if (!TextUtils.isEmpty(error)) {
Toast.makeText(this, error, Toast.LENGTH_SHORT).show();
}
}
break;
}
}
private static String validateFields(String barcode, String format,
String title, String price) {
StringBuilder errors = new StringBuilder();
if (barcode.matches("^\\s*$")) {
errors.append("Barcode required\n");
}
if (format.matches("^\\s*$")) {
errors.append("Format required\n");
}
if (title.matches("^\\s*$")) {
errors.append("Title required\n");
}
if (!price.matches("^-?\\d+(.\\d+)?$")) {
errors.append("Need numeric price\n");
}
return errors.toString();
}
}
I think string may be null somewhere. Please type something in textfield or check for null string.
I want to use an a dialog to display a message contained in the method below instead of just setText, but each time I use the alertBuilder, the message does not display. Can someone please point me in the right direction?
below is the code:
#Override
public void onPreviewFrame(byte[] data, Camera cam) {
if (data == null) throw new NullPointerException();
Camera.Size size = cam.getParameters().getPreviewSize();
if (size == null) throw new NullPointerException();
if (!processing.compareAndSet(false, true)) return;
int width = size.width;
int height = size.height;
int imgAvg = ImageProcessing.decodeYUV420SPtoRedAvg(data.clone(), height, width);
Log.i(TAG, "imgAvg="+imgAvg);
if (imgAvg == 0 || imgAvg == 255) {
processing.set(false);
return;
}
int averageArrayAvg = 0;
int averageArrayCnt = 0;
for (int i = 0; i < averageArray.length; i++) {
if (averageArray[i] > 0) {
averageArrayAvg += averageArray[i];
averageArrayCnt++;
}
}
int rollingAverage = (averageArrayCnt > 0) ? (averageArrayAvg / averageArrayCnt) : 0;
TYPE newType = currentType;
if (imgAvg < rollingAverage) {
newType = TYPE.RED;
if (newType != currentType) {
beats++;
// Log.d(TAG, "BEAT!! beats="+beats);
}
} else if (imgAvg > rollingAverage) {
newType = TYPE.GREEN;
}
if (averageIndex == averageArraySize) averageIndex = 0;
averageArray[averageIndex] = imgAvg;
averageIndex++;
// Transitioned from one state to another to the same
if (newType != currentType) {
currentType = newType;
image.postInvalidate();
}
long endTime = 20;
//System.currentTimeMillis();
double totalTimeInSecs = (endTime - startTime) / 1000d;
if (totalTimeInSecs >= 20) {
double bps = (beats / totalTimeInSecs);
int dpm = (int) (bps * 60d);
if (dpm < 30 || dpm > 180) {
startTime = System.currentTimeMillis();
beats = 0;
processing.set(false);
return;
}
Log.d(TAG,
"totalTimeInSecs="+totalTimeInSecs+" beats="+beats);
if (beatsIndex == beatsArraySize) beatsIndex = 0;
beatsArray[beatsIndex] = dpm;
beatsIndex++;
int beatsArrayAvg = 0;
int beatsArrayCnt = 0;
for (int i = 0; i < beatsArray.length; i++) {
if (beatsArray[i] > 0) {
beatsArrayAvg += beatsArray[i];
beatsArrayCnt++;
}
}
int beatsAvg = (beatsArrayAvg / beatsArrayCnt);
//maybe here
startTime = System.currentTimeMillis();
beats = 0;
text.setText(String.valueOf(beatsAvg) + "bpm");
}
The code works fine, but I just want to use a dialog to display the text.setText message. How do I do this?
public class DialogCaller {
public static void showDialog(Context context,String title,String message,
DialogInterface.OnClickListener onClickListener) {
AlertDialog.Builder dialog = new AlertDialog.Builder(context);
dialog.setTitle(title);
dialog.setMessage(message);
dialog.setPositiveButton("Ok",onClickListener);
dialog.show();
}
}
Add this class to your android project.
whenever you want to display an message just call the class with with context,title,message, and a listener for okay button in dialog. Like this.
Add the below code in the place of text.setText(String.valueOf(beatsAvg) + "bpm");
DialogCaller.showDialog(getActivity()/getApplicationContext(),"Kingmeka dialog ",String.valueOf(beatsAvg) + "bpm",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage(String.valueOf(beatsAvg) + "bpm");
alertDialogBuilder.setPositiveButton("yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
// Do what needs to be done
}
});
alertDialogBuilder.setNegativeButton("No",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
Use above code for showing your message in alert dialog. Customize it according to your need. For details see this
My Requirement is using count.when we press the button three times i want to appear toast message as Blocked ??please any one can show the code or condition.Any Error in Programming?
public void empbtn(View v) {
EditText et11,et22;
int counter = 3;
int i;
String unames[] = {"Anil","Ramesh","Khaja"};
String passwds[] = {"anil","ramesh","khaja"};
et11 = (EditText)findViewById(R.id.empname);
et22 = (EditText)findViewById(R.id.emppass);
String uname = et11.getText().toString();
String pass = et22.getText().toString();
if(uname.equals(""))
{
et11.setError("PLS ENTER NAME");
}
else if (pass.equals(passwds))
{
//et22.setError("pls enter password");
Toast.makeText(main.this, "valid", Toast.LENGTH_SHORT).show();
}
else {
counter++;
if (counter > 3)
{
Toast.makeText(main.this, "blocked", Toast.LENGTH_SHORT).show();
}
else {
for (i = 0; i < unames.length; i++) {
if (uname.equals(unames[i]) && pass.equals(passwds[i])) {
setContentView(R.layout.home);
TextView tv = (TextView) findViewById(R.id.names);
tv.setText(uname);
break;
}
}
if (i == unames.length) {
Toast.makeText(main.this, "INVALID", Toast.LENGTH_SHORT).show();
}
}
}
You could put a boolean as a flag to know when is valid:
boolean isValid = false;
for (i = 0; i < unames.length; i++) {
if (uname.equals(unames[i]) && pass.equals(passwds[i])) {
setContentView(R.layout.home);
TextView tv = (TextView) findViewById(R.id.names);
tv.setText(uname);
isValid=true
break;
}
}
if (!isValid) {
Toast.makeText(main.this, "INVALID", Toast.LENGTH_SHORT).show();
}
EDIT
Try with this:
if (i == unames.length-1) {
Toast.makeText(main.this, "INVALID", Toast.LENGTH_SHORT).show();
}
I am having some problem when trying to refresh the rating bar after user submitted their rating. So basically I am passing the existing rating amount when certain button on my other Activity was triggered:
viewDtlEventBtn.setOnClickListener(new OnClickListener(){
public void onClick(View v){
Object[] obj = new Object[2];
obj[0] = String.valueOf(eventIDTV.getText());
obj[1] = eventReviewModel;
new GetEventDetailAsyncTask(new GetEventDetailAsyncTask.OnRoutineFinished() {
public void onFinish() {
// Passing whole object with value into another activity
Intent eventDtlIntent = new Intent(context, EventDetailMain.class);
// Pass in a list of rating star together with amount
eventDtlIntent.putExtra("eventPopulateStarObj", populateRatingStar);
context.startActivity(eventDtlIntent);
}
}).execute(obj);
}
});
And I am populating the rating bar when onCreate():
ratingStarList = (ArrayList<EventReview>) i
.getSerializableExtra("eventPopulateStarObj");
public void populateRatingProgressBar() {
int totalStar = 0;
// Get the total amount of rate records
for (int j = 0; j < ratingStarList.size(); j++) {
if (ratingStarList.get(j).getStarAmt() != null) {
totalStar += Integer.parseInt(ratingStarList.get(j)
.getStarAmt());
}
}
txtTotalRate.setText(totalStar + " Ratings for this event");
// Set progress bar based on the each rates
for (int i = 0; i < ratingStarList.size(); i++) {
if (ratingStarList.get(i).getStarAmt() != null) {
if (ratingStarList.get(i).getEventReviewRate().equals("5")) {
pb5Star.setProgress(Integer.parseInt(ratingStarList.get(i)
.getStarAmt()));
} else if (ratingStarList.get(i).getEventReviewRate()
.equals("4")) {
pb4Star.setProgress(Integer.parseInt(ratingStarList.get(i)
.getStarAmt()));
} else if (ratingStarList.get(i).getEventReviewRate()
.equals("3")) {
pb3Star.setProgress(Integer.parseInt(ratingStarList.get(i)
.getStarAmt()));
} else if (ratingStarList.get(i).getEventReviewRate()
.equals("2")) {
pb2Star.setProgress(Integer.parseInt(ratingStarList.get(i)
.getStarAmt()));
} else if (ratingStarList.get(i).getEventReviewRate()
.equals("1")) {
pb1Star.setProgress(Integer.parseInt(ratingStarList.get(i)
.getStarAmt()));
}
}
}
}
It did populated correctly. However, I not sure how to refresh the rating bar after user submitted their rating. Here is the code when user submit their rating:
public void promptSubmitStar() {
AlertDialog.Builder Dialog = new AlertDialog.Builder(getActivity());
Dialog.setTitle("Confirm Rating");
LayoutInflater li = (LayoutInflater) getActivity().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
View dialogView = li.inflate(R.layout.option_submit_star, null);
txtPromptStarRate = (TextView) dialogView
.findViewById(R.id.txtPromptStarRate);
txtPromptStarRate.setText("Confirm to submit " + starRate
+ " stars for this event?");
Dialog.setView(dialogView);
Dialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
EventReview eventReviewModel = new EventReview();
eventReviewModel.setEventID(eventID);
eventReviewModel.setEventReviewBy(userID);
eventReviewModel.setEventReviewRate(String.valueOf(starRate));
new CreateEventReviewAsyncTask(context)
.execute(eventReviewModel);
dialog.dismiss();
// Disable the rating bar by setting a touch listener which
// always return true
ratingBar.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View view, MotionEvent event) {
return true;
}
});
}
});
Dialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
});
Dialog d = Dialog.show();
EventDialogueBox.customizeDialogueBox(context, d);
}
Any ideas? Thanks in advance.
Use setRating(starRate); to programmatically set the rating on the RatingBar.