Android 4.4 SQLite Not Updating - android

I have a fully functional SQLite database in my Android App which works perfect on my testing devices (Android 4.0 - 4.3), but I have a user running KitKat and they are unable to update the database. To summarize my code, I have a user click a switch, then asks whether they want to make the change, if so it updates the database table.
Here is my calls to the database from the Activity:
StatusData statusData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_macro);
statusData = new StatusData(getBaseContext());
}
#Override
public void onClick(View v) {
AlertDialog.Builder alertDialogBuilder;
AlertDialog alertDialog;
switch (v.getId())
case R.id.switchOffSeason:
String season,
seasonHeading = "";
alertDialogBuilder = new AlertDialog.Builder(this);
// set dialog message
if (switchOffSeason.isChecked()) {
season = "This will delete all your current settings and default to the standard diet. This cannot be undone";
seasonHeading = "Set Standard Diet";
} else {
season = "This will delete all your current settings and default to Off-Season diet. This cannot be undone.";
seasonHeading = "Set Off-Season Diet";
}
// set title
alertDialogBuilder.setTitle(seasonHeading);
alertDialogBuilder
.setMessage(season)
.setCancelable(false)
.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
String passedTask = "offSeason";
dropTable task = new dropTable(passedTask);
task.execute(passedTask);
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
if (switchOffSeason.isChecked()) {
switchOffSeason.setChecked(false);
} else {
switchOffSeason.setChecked(true);
}
dialog.cancel();
}
});
alertDialog = alertDialogBuilder.create();
private class dropTable extends AsyncTask<String, Void, String> {
String task;
public dropTable(String passedTask) {
super();
task = passedTask;
}
#Override
protected String doInBackground(String... params) {
if (task.equals("reset")) {
String offSeason = statusData.profileTable()[10];
profileTable = statusData.profileTable();
statusData.dropReloadMacrosTable(new String[] {
profileTable[11], profileTable[12], profileTable[13],
profileTable[14], profileTable[15], profileTable[16],
profileTable[17], offSeason });
} else if (task.equals("offSeason")) {
if (switchOffSeason.isChecked()) {
statusData.updateFieldProfile(new String[] { "offseason",
"1" });
} else {
statusData.updateFieldProfile(new String[] { "offseason",
"0" });
}
String offSeason = statusData.profileTable()[10];
statusData.dropReloadMacrosTable(new String[] {
profileTable[11], profileTable[12], profileTable[13],
profileTable[14], profileTable[15], profileTable[16],
profileTable[17], offSeason });
}
return "Executed";
}
Here is my StatusData (Database) class:
public void updateFieldProfile(String updateArray[]) {
open();
Log.i("log", "in method");
String fieldToUpdate = updateArray[0];
String valueToUpdate = updateArray[1];
String query = "UPDATE PROFILE SET " + fieldToUpdate + "="
+ "= ?";
Log.i("logQuery", query);
Cursor c = db.rawQuery(query, new String[] {valueToUpdate});
c.moveToFirst();
c.close();
db.close();
}

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')
}

Widgets Initialization Crash

My program is to get the Tutor's LastName, FirstName, and MiddleName from an EditText in DialogFragment. Here's the code of my DialogFragment:
public class AddInstructorDialog extends android.app.DialogFragment
{
DatabaseHelper myDb;
View myView;
public AlertDialog.Builder builder;
private EditText tutorLastName, tutorFirstName, tutorMiddleName;
private dialogListener listener;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
myDb = new DatabaseHelper(getActivity());
View mView = getActivity().getLayoutInflater().inflate(R.layout.alert_dialog_add_instructor, null);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Add Instructors")
.setPositiveButton("Add", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
myDb.getInstructorNumber();
if(myDb.instructorNumber == null)
{
Toast.makeText(getActivity(), "IN1", Toast.LENGTH_SHORT).show();
}
else
{
String sum = myDb.instructorNumber;
String total = "IN" + sum;
EditText txtLastName = myView.findViewById(R.id.tutor_LastName);
EditText txtMiddleName = myView.findViewById(R.id.tutor_MiddleName);
EditText txtFirstName = myView.findViewById(R.id.tutor_FirstName);
String LastName = txtLastName.getText().toString();
String MiddleName = txtMiddleName.getText().toString();
String FirstName = txtFirstName.getText().toString();
listener.applyValuse(LastName, FirstName, MiddleName);
String fullName = LastName + ", " + FirstName + LastName;
boolean isInserted = myDb.addInstructorData(
total,
LastName,
FirstName,
MiddleName,
fullName
);
if(isInserted == true)
{
Toast.makeText(getActivity(), "Inserted", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getActivity(), "Not inserted", Toast.LENGTH_SHORT).show();
}
}
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
myDb.insertInsData();
}
});
builder.setView(mView);
AlertDialog dialog = builder.create();
dialog.show();
return dialog;
}
I have no problem in getting the value of instructorID. My problem is that, after getting the value of instructorID, it will proceed in fetching the inputted data from the EditText of DialogBox the the app will crash. It doesn't read the line of
EditText txtLastName = myView.findViewById(R.id.tutor_LastName);
inthat line, the app will crash.
Did I miss somethin? I tried moving that line around but it doesn't work.

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.

Android AsyncTask Dialog fast close

My code:
private class selectBookInAutor extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
arr_book_title.clear();
arr_book_href.clear();
mProgressDialog = new ProgressDialog(_context);
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
#Override
protected String doInBackground(String... params) {
Document doc = null;
StringBuilder sb = new StringBuilder();
try {
doc = Jsoup.connect(params[0]).userAgent("Mozilla").get();
Elements links = doc.select("li>a");
for (Element link : links) {
sb.append(link.text());
arr_book_title.add(link.text());
arr_book_href.add(Jsoup.clean(link.attr("abs:href"), Whitelist.basic()));
}
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
#Override
protected void onPostExecute(String result) {
if (result != ""){
final CharSequence[] items = arr_book_title.toArray(new CharSequence[arr_book_title.size()]);
final ArrayList seletedItems = new ArrayList();
AlertDialog.Builder builder = new AlertDialog.Builder(_context);
builder.setTitle("Select The Difficulty Level");
builder.setMultiChoiceItems(items, null, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int indexSelected, boolean isChecked) {
if (isChecked) {
seletedItems.add(indexSelected);
}else if(seletedItems.contains(indexSelected)){
seletedItems.remove(Integer.valueOf(indexSelected));
}
}
}).setPositiveButton(R.string.button_ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
for (Object s : seletedItems){
String[] separated = selGroupParam.split(";");
String _idautor = separated[0].toString();
long id_book = db.insertBOOK(_idautor, arr_book_href.get(Integer.valueOf(s.toString())).toString(), "", arr_book_title.get(Integer.valueOf(s.toString())).toString());
new **saveBookInAutor().execute(arr_book_href.get(Integer.valueOf(s.toString())).toString(), _idautor, String.valueOf(id_book));**
}
refreshList();
}
}).setNegativeButton(R.string.button_cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
}
}).create().show();
}else{
Toast.makeText(_context, "Error", Toast.LENGTH_SHORT).show();
}
mProgressDialog.dismiss();
}
}
private class saveBookInAutor extends AsyncTask<String, Void, String> {
String _idautor, _idbook;
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog2 = new ProgressDialog(_context);
mProgressDialog2.setMessage("Save to file");
mProgressDialog2.setIndeterminate(false);
mProgressDialog2.show();
}
#Override
protected String doInBackground(String... params) {
Document doc = null;
String _html = "";
_idautor = params[1];
_idbook = params[2];
try {
doc = Jsoup.connect(params[0]).userAgent("Mozilla").get();
_html = doc.select("dd").outerHtml();
} catch (IOException e) {
e.printStackTrace();
}
return Jsoup.clean(_html, Whitelist.basic());
}
#Override
protected void onPostExecute(String result) {
if (result != ""){
Toast.makeText(_context, "Save file", Toast.LENGTH_SHORT).show();
String html = "<html lang='ru'><head><meta http-equiv='Content-Type' content='text/html; charset=UTF-8'/></head><body>"+result+"</body></html>";
//String html = result;
**savePageToFile(_idautor + "_" + String.valueOf(_idbook), html);**
}else{
Toast.makeText(_context, "Error", Toast.LENGTH_SHORT).show();
}
mProgressDialog2.dismiss();
}
}
public void refreshList() {
Intent intent = new Intent(_context, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
_context.startActivity(intent);
}
public void savePageToFile(String filename, String html) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(_context.openFileOutput(filename, Context.MODE_PRIVATE));
outputStreamWriter.write(html);
outputStreamWriter.close();
}
catch (IOException e) {
//Log.e("Exception", "File write failed: " + e.toString());
}
}
When you select a page and clicking "Ok" ProgressDialog mProgressDialog2 opens and displays just a 1 second. Because of this, I do not see the download Page or not.
How to make mProgressDialog2 displayed all the while to save the page as a file?
Thank you!
UPD
What i want is :
Start mProgressDialog.
After downloading the page disappears and AlertDialog comes with the question what to choose.
After choosing, mProgressDialog2 should be displayed as long as it downloads and saves the file in the webpage.
However mProgressDialog2 disappears in 1 second, and process of saving the file goes on in silence.
In your onPostExecute method, you unconditionally call
mProgressDialog2.dismiss();
This is closing the dialog immediately after it is displayed. That call should be moved to the handler code for each of the buttons. (i.e.the onClick method for the positive and negative buttons)
in onPostExecute(), compare Strings like
if(!result.equals(""))
and try once.
use equals() method for String comparisons.

Categories

Resources