how to fix NumberFormatException in android - android

private void increaseFontSize() {
String getSelction = getset.getFontSize();
int get_selection = Integer.parseInt(getSelction);
final CharSequence[] textSize = { "Tiny", "Small", "Medium", "Large",
"Huge" };
AlertDialog.Builder alert = new AlertDialog.Builder(DetailPage.this);
alert.setTitle("Text Size");
alert.setSingleChoiceItems(textSize, get_selection,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (textSize[which] == "Tiny") {
getset.setFontSize("0");
restartData();
dialog.dismiss();
} else if (textSize[which] == "Small") {
getset.setFontSize("1");
restartData();
dialog.dismiss();
} else if (textSize[which] == "Medium") {
getset.setFontSize("2");
restartData();
dialog.dismiss();
} else if (textSize[which] == "Large") {
getset.setFontSize("3");
restartData();
dialog.dismiss();
} else if (textSize[which] == "Huge") {
getset.setFontSize("4");
restartData();
dialog.dismiss();
}
}
private void restartData() {
Intent intent = new Intent(getApplicationContext(),
DetailPage.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent);
finish();
}
});
alert.show();
}
this is function fro set fontsize of text view i have create dialog for select text size . but i am getting NumberFormatException at line String getSelction = getset.getFontSize();
int get_selection = Integer.parseInt(getSelction); please tell me how to fix it while i have in GLobaldata class
String fontSize;
public String getFontSize() {
return fontSize;
}
public void setFontSize(String fontSize) {
this.fontSize = fontSize;
}
i have take fontsize as string and make set and get please how to fix this NumberFormatException .

You have to do two thing.
1st thing:
Used .equals() for String comparison. Like so
if (textSize[which].equals("Tiny")) {
2nd thing:
Also before parseInt() check whether your String is empty or not. Like so
if(!TextUtils.isEmpty(getSelction)){
int get_selection = Integer.parseInt(getSelction);
}

Related

How to save Checked Status of radio button in Quiz app using android studio with sharedpreferences

I am making a quiz app in android studio. I am facing an issue which is that I have hundreds of questions with four options, and also next and previous buttons in that. For options, I am using radio buttons. I want that after the user selects an option for the first question, goes to the next question and selects an option for the second question, he will be able to go to the previous question, and there the radio button will be checked with the option the user has been selected earlier.
How can I do that? please help!
This is my code:
public class MainActivity extends AppCompatActivity {
int score;
float percentage;
int answerSelected;
private TextView quizQuestion,questionNumber;
private RadioGroup radioGroup;
private RadioButton optionOne;
private RadioButton optionTwo;
private RadioButton optionThree;
private RadioButton optionFour;
private ImageView question_image;
private int currentQuizQuestion;
private int quizCount;
private QuizWrapper firstQuestion;
private List<QuizWrapper> parsedObject;
private boolean mIsDestroyed;
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
score = 0;
quizQuestion = (TextView)findViewById(R.id.quiz_question);
questionNumber = (TextView)findViewById(R.id.question_number);
radioGroup = (RadioGroup)findViewById(R.id.radioGroup);
optionOne = (RadioButton)findViewById(R.id.radio0);
optionTwo = (RadioButton)findViewById(R.id.radio1);
optionThree = (RadioButton)findViewById(R.id.radio2);
optionFour = (RadioButton)findViewById(R.id.radio3);
question_image = (ImageView)findViewById(R.id.question_image);
final Button previousButton = (Button)findViewById(R.id.previousquiz);
final Button nextButton = (Button)findViewById(R.id.nextquiz);
AsyncJsonObject asyncObject = new AsyncJsonObject();
asyncObject.execute("");
nextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int radioSelected = radioGroup.getCheckedRadioButtonId();
int userSelection = getSelectedAnswer(radioSelected);
int correctAnswerForQuestion = firstQuestion.getIs_correct();
if(userSelection == correctAnswerForQuestion){
// correct answer
score++;
// Toast.makeText(MainActivity.this, "You got the answer correct", Toast.LENGTH_LONG).show();
currentQuizQuestion++;
if(currentQuizQuestion >= quizCount){
previousButton.setVisibility(View.VISIBLE);
AlertDialog.Builder alertConfirm = new AlertDialog.Builder(MainActivity.this);
alertConfirm.setTitle("Confirm Submission");
alertConfirm.setMessage("Do you want to submit quiz?");
alertConfirm.setCancelable(true);
alertConfirm.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
alertConfirm.setPositiveButton("Submit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// submit(view);
}
});
AlertDialog dialog = alertConfirm.create();
dialog.show();
Toast.makeText(MainActivity.this, "End of the Quiz Questions", Toast.LENGTH_LONG).show();
return;
}
else{
previousButton.setVisibility(View.VISIBLE);
// uncheckedRadioButton();
firstQuestion = parsedObject.get(currentQuizQuestion);
questionNumber.setText(Integer.toString(firstQuestion.getQuestion_number()));
quizQuestion.setText(firstQuestion.getQuestions());
if(firstQuestion.getQuestion_image().isEmpty()){
// Picasso.get().load(firstQuestion.getQuestion_image()).into(question_image);
question_image.setVisibility(View.GONE);
}else{
Picasso.get().load(firstQuestion.getQuestion_image()).into(question_image);
question_image.setVisibility(View.VISIBLE);
}
// String[] possibleAnswers = firstQuestion.get.split(",");
optionOne.setText(firstQuestion.getOption_a());
optionTwo.setText(firstQuestion.getOption_b());
optionThree.setText(firstQuestion.getOption_c());
optionFour.setText(firstQuestion.getOption_d());
}
}
else{
currentQuizQuestion++;
// failed question
// Toast.makeText(MainActivity.this, "You chose the wrong answer", Toast.LENGTH_LONG).show();
if( currentQuizQuestion<quizCount) {
previousButton.setVisibility(View.VISIBLE);
// uncheckedRadioButton();
firstQuestion = parsedObject.get(currentQuizQuestion);
questionNumber.setText(Integer.toString(firstQuestion.getQuestion_number()));
quizQuestion.setText(firstQuestion.getQuestions());
if(firstQuestion.getQuestion_image().isEmpty()){
// Picasso.get().load(firstQuestion.getQuestion_image()).into(question_image);
question_image.setVisibility(View.GONE);
}else{
Picasso.get().load(firstQuestion.getQuestion_image()).into(question_image);
question_image.setVisibility(View.VISIBLE);
}
// String[] possibleAnswers = firstQuestion.get.split(",");
optionOne.setText(firstQuestion.getOption_a());
optionTwo.setText(firstQuestion.getOption_b());
optionThree.setText(firstQuestion.getOption_c());
optionFour.setText(firstQuestion.getOption_d());
}else {
AlertDialog.Builder alertConfirm = new AlertDialog.Builder(MainActivity.this);
alertConfirm.setTitle("Confirm Submission");
alertConfirm.setMessage("Do you want to submit quiz?");
alertConfirm.setCancelable(true);
alertConfirm.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
alertConfirm.setPositiveButton("Submit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// submit(view);
submit();
}
});
AlertDialog dialog = alertConfirm.create();
dialog.show();
// Toast.makeText(MainActivity.this, "End of the Quiz Questions", Toast.LENGTH_LONG).show();
return;
}
}
}
});
previousButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (currentQuizQuestion <= 0) {
previousButton.setVisibility(View.INVISIBLE);
}else {
currentQuizQuestion--;
firstQuestion = parsedObject.get(currentQuizQuestion);
questionNumber.setText(Integer.toString(firstQuestion.getQuestion_number()));
quizQuestion.setText(firstQuestion.getQuestions());
if (firstQuestion.getQuestion_image().isEmpty()) {
// Picasso.get().load(firstQuestion.getQuestion_image()).into(question_image);
question_image.setVisibility(View.GONE);
} else {
Picasso.get().load(firstQuestion.getQuestion_image()).into(question_image);
question_image.setVisibility(View.VISIBLE);
}
// String[] possibleAnswers = firstQuestion.getAnswers().split(",");
optionOne.setText(firstQuestion.getOption_a());
optionTwo.setText(firstQuestion.getOption_b());
optionThree.setText(firstQuestion.getOption_c());
optionFour.setText(firstQuestion.getOption_d());
// AlertDialog.Builder alertConfirm = new AlertDialog.Builder(MainActivity.this);
// alertConfirm.setTitle("Finish Test");
// alertConfirm.setMessage("You cannot resume once you submit.Are you sure you want to submit this test?");
// alertConfirm.setCancelable(true);
// alertConfirm.setNegativeButton("RESUME", new DialogInterface.OnClickListener() {
// #Override
// public void onClick(DialogInterface dialog, int which) {
//
// }
// });
// alertConfirm.setPositiveButton("Submit", new DialogInterface.OnClickListener() {
// #Override
// public void onClick(DialogInterface dialog, int which) {
// // submit(view);
// submit();
// }
// });
// AlertDialog dialog = alertConfirm.create();
// dialog.show();
//
}
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
mIsDestroyed = true;
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
private class AsyncJsonObject extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
HttpClient httpClient = new DefaultHttpClient(new BasicHttpParams());
String url = "";
HttpPost httpPost = new HttpPost(url);
String jsonResult = "";
try {
HttpResponse response = httpClient.execute(httpPost);
jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
System.out.println("Returned Json object " + jsonResult.toString());
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jsonResult;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
progressDialog = ProgressDialog.show(MainActivity.this, "Loading Quiz","Wait....", true);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
System.out.println("Resulted Value: " + result);
progressDialog.dismiss();
parsedObject = returnParsedJsonObject(result);
if(parsedObject == null){
return;
}
quizCount = parsedObject.size();
firstQuestion = parsedObject.get(0);
questionNumber.setText(Integer.toString(firstQuestion.getQuestion_number()));
quizQuestion.setText(firstQuestion.getQuestions());
if(firstQuestion.getQuestion_image().isEmpty()){
// Picasso.get().load(firstQuestion.getQuestion_image()).into(question_image);
question_image.setVisibility(View.GONE);
}else {
Picasso.get().load(firstQuestion.getQuestion_image()).into(question_image);
question_image.setVisibility(View.VISIBLE);
}
// String[] possibleAnswers = firstQuestion.getAnswers().split(",");
optionOne.setText(firstQuestion.getOption_a());
optionTwo.setText(firstQuestion.getOption_b());
optionThree.setText(firstQuestion.getOption_c());
optionFour.setText(firstQuestion.getOption_d());
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = br.readLine()) != null) {
answer.append(rLine);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return answer;
}
}
private List<QuizWrapper> returnParsedJsonObject(String result){
List<QuizWrapper> jsonObject = new ArrayList<QuizWrapper>();
JSONObject resultObject = null;
JSONArray jsonArray = null;
QuizWrapper newItemObject = null;
try {
resultObject = new JSONObject(result);
System.out.println("Testing the water " + resultObject.toString());
String test = "";
jsonArray = resultObject.optJSONArray(test);
} catch (JSONException e) {
e.printStackTrace();
}
for(int i = 0; i < jsonArray.length(); i++){
JSONObject jsonChildNode = null;
try {
jsonChildNode = jsonArray.getJSONObject(i);
int id = jsonChildNode.getInt("id");
String answera = jsonChildNode.getString("option_a");
String answerb = jsonChildNode.getString("option_b");
String answerc = jsonChildNode.getString("option_c");
String answerd = jsonChildNode.getString("option_d");
int correctAnswer = jsonChildNode.getInt("is_correct");
int questionnumber = jsonChildNode.getInt("question_number");
String question = jsonChildNode.getString("questions");
String questionimage = jsonChildNode.getString("question_image");
newItemObject = new QuizWrapper(id, answera,answerb,answerc,answerd, correctAnswer,questionnumber,question,questionimage);
jsonObject.add(newItemObject);
} catch (JSONException e) {
e.printStackTrace();
}
}
return jsonObject;
}
private int getSelectedAnswer(int radioSelected){
answerSelected = 0;
radioGroup.clearCheck();
if(radioSelected == R.id.radio0){
answerSelected = 1;
}
if(radioSelected == R.id.radio1){
answerSelected = 2;
}
if(radioSelected == R.id.radio2){
answerSelected = 3;
}
if(radioSelected == R.id.radio3){
answerSelected = 4;
}
return answerSelected;
}
private void uncheckedRadioButton() {
optionOne.setChecked(false);
optionTwo.setChecked(false);
optionThree.setChecked(false);
optionFour.setChecked(false);
}
#Override
public void onBackPressed() {
Toast.makeText(this, "Back Press is not allowed", Toast.LENGTH_LONG).show();
}
private void submit(){
// if (submit)
// checkScore();
// submit = false;
percentage = (float) (score * 100) /parsedObject.size();
//.setVisibility(View.INVISIBLE);
optionOne.setClickable(false);
optionTwo.setClickable(false);
optionThree.setClickable(false);
optionFour.setClickable(false);
LayoutInflater inflater = getLayoutInflater();
View alertLayout = inflater.inflate(R.layout.alert_dialog, null);
final ProgressBar progressBar = alertLayout.findViewById(R.id.circularProgressbar);
final TextView textView = alertLayout.findViewById(R.id.tv);
Drawable drawable = getResources().getDrawable(R.drawable.circular);
progressBar.setMax(parsedObject.size());
progressBar.setSecondaryProgress(parsedObject.size());
progressBar.setProgress(score);
progressBar.setProgressDrawable(drawable);
textView.setText((int) percentage + "%");
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("RESULT");
alert.setMessage("You scored " + score + " out of " + parsedObject.size() );
alert.setView(alertLayout);
alert.setCancelable(false);
alert.setNegativeButton("Exit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
moveTaskToBack(true);
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
}
});
alert.setPositiveButton("View Solutions", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//clickSolutions();
Intent intent = new Intent(MainActivity.this,SolutionActivity.class);
startActivity(intent);
}
});
AlertDialog dialog = alert.create();
dialog.show();
}
}
This is Kotlin, but it's the same way to write in Java.
ShareReference Function:
private val sharedPreferences = context.getSharedPreferences("YourFile", Context.MODE_PRIVATE)
Functions:
fun setInt(key: String, value: Int) {
with(sharedPreferences.edit()) {
putInt(key, value)
apply()
}
}
fun getInt(key: String): Int {
return sharedPreferences.getInt(key, -1)
}
Save the checked one:
// save to sharedPreferences
val CHECKED = "checkedRadio"
val checkedButtonId = radioGroup.checkedRadioButtonId
setInt(CHECKED, checkedButtonId)
Load the checked one:
val mRatioId = getInt(CHECKED)
radioGroup.check(mRatioId)
Let's use it in the listener:
val mRadioGroup = view?.findViewById<RadioGroup>(R.id...)
mRadioGroup?.setOnCheckedChangeListener { _, checkedId ->
setInt(checkedId)
}
Once you click any radio button, its radio-group will save the option to the shared preference. This code is saving R.id. But you can convert the id to ABCD.
static variables:
const val aRb = R.id.aRb
const val bRb = R.id.bRb
const val cRb = R.id.cRb
const val dRb = R.id.dRb
Instead saving integer. You can save it in string.
fun setString(key: String, value: String) {
with(sharedPreferences.edit()) {
putString(key, value)
apply()
}
}
fun getString(key: String): String {
return sharedPreferences.getString(key, "")!!
}
Selection for Question # 12 as example:
when (checkedId) {
aRb -> setString("Q12", 'a')
bRb -> setString("Q12", 'b')
cRb -> setString("Q12", 'c')
dRb -> setString("Q12", 'd')
}

Custom AlertDialog not showing on UI sometimes why?

I am showing my own AlertDialog. It works and shows fine in most cases but in when I call from the following activity it does not show on UI. The code executes completely with no exceptions, I have even checked my logs and with breakpoints, Did not find any issue. But the dialog does not appear on UI. Can anyone tell me what the problem might be?
This is the method in my activity that calls the dialog.
private void showCustomDialog(final int messageType,
final String titleString,
final String msgString,
final String specificMsgString,
final int positiveButtonString,
final int negativeButtonString,
final Runnable positiveButtonClickHandler,
final Runnable negativeButtonClickHandler) {
if (mDialog != null && mDialog.isShowing()) {
Log.d(TAG, "showCustomDialog: cannot display two dialogs at once.");
return;
}
runOnUiThread(() -> mDialog = DialogUtil.showDialog(this, mAlertDialogBuilder, 0, messageType, titleString, msgString,
specificMsgString, positiveButtonString, negativeButtonString, positiveButtonClickHandler, negativeButtonClickHandler));
}
DialogUtil.showDialog method:
public static AlertDialog showDialog(
Activity activity,
AlertDialog.Builder builder,
final int borderTopColorRes,
final int iconRes,
final String titleString,
final String msgString,
final String specificMsgString,
final int positiveButtonString,
final int negativeButtonString,
final Runnable positiveButtonClickHandler,
final Runnable negativeButtonClickHandler) {
final DialogCustomViewBinding binding = DataBindingUtil.inflate(LayoutInflater.from(activity), R.layout.dialog_custom_view, null, false);
binding.textSpecificMessage.setVisibility(View.GONE);
if (borderTopColorRes != 0) {
binding.viewBorderTop.setBackgroundColor(borderTopColorRes);
} else {
binding.viewBorderTop.setVisibility(View.GONE);
}
if (iconRes != 0) {
binding.imageCustomDialogMessageType.setImageResource(iconRes);
}
if (titleString != null) {
binding.textCustomDialogTitle.setText(titleString);
binding.textCustomDialogTitle.setVisibility(View.VISIBLE);
} else {
binding.textCustomDialogTitle.setText("");
binding.textCustomDialogTitle.setVisibility(View.GONE);
}
if (msgString != null) {
binding.textDialogMessage.setText(msgString);
binding.textDialogMessage.setVisibility(View.VISIBLE);
} else {
binding.textDialogMessage.setText("");
binding.textDialogMessage.setVisibility(View.GONE);
}
binding.textSpecificMessage.setVisibility(View.GONE);
if (specificMsgString != null) {
binding.textSpecificMessage.setText(specificMsgString);
binding.textDialogMessage.setOnClickListener(v -> {
if (binding.textSpecificMessage.getVisibility() == View.VISIBLE) {
binding.textSpecificMessage.setVisibility(View.GONE);
} else {
binding.textSpecificMessage.setVisibility(View.VISIBLE);
}
});
}
if (positiveButtonClickHandler != null) {
binding.buttonPositive.setText(positiveButtonString);
binding.buttonPositive.setOnClickListener(v -> positiveButtonClickHandler.run());
} else {
binding.buttonPositive.setVisibility(View.GONE);
}
if (negativeButtonClickHandler != null) {
binding.buttonNegative.setText(negativeButtonString);
binding.buttonNegative.setOnClickListener(v -> negativeButtonClickHandler.run());
} else {
binding.buttonNegative.setVisibility(View.GONE);
}
builder.setView(binding.getRoot());
AlertDialog dialog = builder.create();
try {
dialog.show();
dialog.setCancelable(false);
dialog.setCanceledOnTouchOutside(false);
return dialog;
} catch (Exception e) {
Log.e(TAG, "showDialog: Exception=" + e.getMessage());
e.printStackTrace();
}
return null;
}

Android call same alert dialog in the entire application

I have a menu on Action Bar to change the password. And below is the code for it. I want to place this code such that I can call the same code anywhere in my application by clicking that menu. Is there any way?
--- ChangingPassword.java---
public void showDialog(final Context ctx, final String user_id, final String storedPass)
{
LayoutInflater layoutInflater = LayoutInflater.from(ctx);
View promptView = layoutInflater.inflate(R.layout.change_password, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(ctx);
// set prompts.xml to be the layout file of the alertdialog builder
alertDialogBuilder.setView(promptView);
final EditText old_password = (EditText) promptView.findViewById(R.id.old_password);
final EditText new_password = (EditText) promptView.findViewById(R.id.new_password);
final EditText c_new_password = (EditText) promptView.findViewById(R.id.c_new_password);
final int error_count;
/*old_password.setTypeface(font);
new_password.setTypeface(font);
c_new_password.setTypeface(font);
*/
final String old_pwd = old_password.getText().toString();
final String new_pwd = new_password.getText().toString();
final String c_new_pwd = c_new_password.getText().toString();
// setup a dialog window
alertDialogBuilder
.setTitle("Change Login Password")
.setNeutralButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if(old_pwd.equalsIgnoreCase("") || (old_pwd.equalsIgnoreCase(storedPass)))
{
old_password.setError(Html.fromHtml("<font color='red'>Enter a valid password</font>"));
old_password.requestFocus();
}
else if( new_pwd.equalsIgnoreCase(""))
{
new_password.setError(Html.fromHtml("<font color='red'>Enter a valid password</font>"));
new_password.requestFocus();
}
else if( c_new_pwd.equalsIgnoreCase(""))
{
c_new_password.setError(Html.fromHtml("<font color='red'>Enter a valid password</font>"));
c_new_password.requestFocus();
}
else if(!new_pwd.equals(c_new_pwd))
{
c_new_password.setError(Html.fromHtml("<font color='red'>Password & Confirm Passwords do not match</font>"));
c_new_password.requestFocus();
}
else
{
try {
UserTask task = new UserTask();
String result = task.execute(new String[] {"changePassword",user_id,new_pwd}).get();
System.out.print(result);
}
catch (Exception e)
{
Toast.makeText(ctx, ""+e.toString(), Toast.LENGTH_LONG).show();
}
}
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
// create an alert dialog
AlertDialog alertD = alertDialogBuilder.create();
alertD.show();
//return alertD;
}
---Calling Activity ---
new ChangePassword().showDialog(TeacherMain.this, user_id, password);
return true;
public class MyDialog{
public void showDialog(Context ctx)
{
/* Create dialog here and do whatever you are doing right now in your method*/
dialog.show();
}
}
and call from your activity classes as below
new MyDialog().showDialog(ActivityName.this);
For your checking part you have to remove nested if statements
if(old_pwd.equalsIgnoreCase("")){
//print: Enter old password
}else if( new_pwd.equalsIgnoreCase("")){
//print: Enter new password
}else if( c_new_pwd.equalsIgnoreCase("")){
//print: Enter c_new_pwd
}else if(! new_pwd.equals(c_new_pwd)){
//print password doesnot match
}else
{
try {
UserTask task = new UserTask();
String result = task.execute(new String[] {"changePass",user_id}).get();
System.out.print(result);
}catch (Exception e){
Toast.makeText(TeacherMain.this, ""+e.toString(),Toast.LENGTH_LONG).show();
}
}
instead of creating new AlertDialog use
alertDialogBuilder.show();

Accessing Variables in AlertDialog in Android

In one of my Activity there are some calculations and total price will be calculated.After pressing the submit button it should show an alert dialog with Are you sure you want to pay Rupees:XXX...? here XXX should be the final price which I'm storing in the variable.
in alertdialog.setTitle() I should able to access the variable.
Please help me to solve this.
public void onPay()
{
getItems();
int rate = 0;
if(spare1_item.equals("Tyres") || qty_1.equals("Quantity"))
{
}
else
{
//Toast.makeText(getApplicationContext(), "Now you can pay", 5000).show();
db = this.openOrCreateDatabase("mobile_cycle_clinic", MODE_PRIVATE, null);
c = db.rawQuery("select price from sparelist where name = '"+spare1_item+"'", null);
if(c.moveToNext())
{
do{
price = c.getInt(c.getColumnIndex("price"));
}
while(c.moveToNext());
}
fianl1_qty = Integer.parseInt(qty_1);
rate = rate + price * fianl1_qty;
db.execSQL("insert into spares_items(cycle_id,item_name,quantity,total_price)values('"+cycle_id+"','"+spare1_item+"',"+fianl1_qty+","+rate+")");
//Toast.makeText(getApplicationContext(), ""+rate, 5000).show();
}
Here rate is a static variable and in another method I should use that variable in alertDialog.setMeaasge().
public void storeData(View v)
{
cycle_id = id.getText().toString();
if(cycle_id.equals("") || cycle_id.equals("null"))
{
Toast.makeText(getApplicationContext(), "Please Scan Cycle",5000).show();
}
else
{
AlertDialog.Builder pauseBuild = new AlertDialog.Builder(this);
pauseBuild.setTitle("Pay Alert");
pauseBuild.setMessage("Do you really want to Pay..?"+rate);
pauseBuild.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss");
//time = sdf.format(new Date());
onPay();
finish();
return;
} });
pauseBuild.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();
}
});
// show it
pauseBuild.show();
}
You can use a function to show or create the AlertDialog.
For example:
private void showConfirmAlertDialog(int price) {
AlertDialog.Builder builder = new AlertDialog.Builder();
builder.setTitle("Are you sure you want to pay rupees: " + price);
....
builder.show();
}
If you perfer getting an instance of AlertDialog, you can change the function to private AlertDialog createConfirmAlertDialg(int price), and use return builder.create(); at the end of function.

How to set error on dynamically added EditText without id?

I have a dynamically added EditTexts to my layout. They don't have id's. This EditTexts are all required and cannot be left empty. I have this function for validation:
private boolean validate() {
boolean valid = true;
for (int i = 0; i < layout.getChildCount(); i++) {
if (layout.getChildAt(i).getTag() != null && layout.getChildAt(i).getTag().toString().contains("required")) {
String viewClass = layout.getChildAt(i).getClass().getName();
if (viewClass.contains("EditText")) {
EditText et = (EditText) layout.getChildAt(i);
if (et.getText().toString().trim().isEmpty()) {
Log.d("#########", "EDIT TEXT ERROR");
et.setError("This field is required.", getResources().getDrawable(R.drawable.indicator_input_error));
valid = false;
}
}
}
}
}
where layout is my layout containing the EditTexts. It gives me the log but it's not showing the error. If I change the setError line with
et.setText("#########");
the text is changed properly. Why isn't the error showing?
It was some other mistake. The code in the question is working fine.
private boolean validate() {
boolean valid = false;
System.out.println("getChildCount:"+ll.getChildCount());
Log.d(TAG,"*****************1******************");
for (int i = 0; i < ll.getChildCount(); i++) {
if (ll.getChildAt(i).getTag() != null && ll.getChildAt(i).getTag().toString().contains("required")) {
Log.d(TAG,"*****************2******************");
String viewClass = ll.getChildAt(i).getClass().getName();
if (viewClass.contains("EditText")) {
Log.d(TAG,"*****************3******************");
EditText et = (EditText) ll.getChildAt(i);
if (et.getText().toString().trim().isEmpty()) {
Log.d(TAG,"*****************4******************");
Log.d("#########", "EDIT TEXT ERROR");
Utils.showAlertDialog(activity, "Error", "The fields are required",getResources().getDrawable(R.mipmap.ic_error), new DialogInterface.OnClickListener() {
#Override`enter code here`
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
valid = true;
}else{
Log.d(TAG,"**********else*******1******************");
valid = false;
}
}else{
Log.d(TAG,"********else*********2******************");
valid = false;
}
}else{
Log.d(TAG,"*********else********3******************");
valid = false;
}
}
return valid;
}
and try to call
if(validate()) {
Log.d(TAG,"********validate()*********1******************");
SaveRecords();
}else{
Log.d(TAG,"**********else*******1******************");
Utils.showAlertDialog(activity, "Error", "The fields are required",getResources().getDrawable(R.mipmap.ic_error), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});

Categories

Resources