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();
}
});
Related
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')
}
In first activity i have button(Named btIndividual) inside listview from that one custom dialog layout opens. In that custom dialog i have one text and edittext field inside listview and one save Button for posting data to server. Now i want that after posting data to server the button named btIndividual in first activity will go invisible.
Custom Adapter for first activity:
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ProductChoosed productChoosed = productChoosedAr.get(position);
convertView = View.inflate(SolutionActivity.this, R.layout.custom_solution_row, null);
ImageView categoryImageView = (ImageView) convertView.findViewById(R.id.categoryImageView);
TextView categoryNameTextView = (TextView) convertView.findViewById(R.id.categoryNameTextView);
productsListTextView = (TextView) convertView.findViewById(R.id.productsListTextView);
btIndividual = (Button) convertView.findViewById(R.id.btIndividual);
String catgoryImage = "";
String isTradeProduct = productChoosed.isTradeProduct;
if(isTradeProduct.equals("0")){
btIndividual.setVisibility(View.VISIBLE);
productsListTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showTradDialog(position, productChoosedAr.get(position));
}
});
}else{
btIndividual.setVisibility(View.GONE);
}
btIndividual.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showIndividualTradDialog(position,productChoosedAr.get(position));
individual_productChoosedAr.clear();
myList.clear();
idIndividual = "";
mIndCount =1;
checkHideButton = position ;
checkButtonPosition = position;
idIndividual = productChoosedAr.get(position).categoryId;
GetIndividualProducts getIndividualProducts = new GetIndividualProducts();
getIndividualProducts.execute();
showDialog();
Toast toast = Toast.makeText(getApplicationContext(),"Loading...",Toast.LENGTH_LONG);
toast.show();
}
});
Custom Dialog layout :
private void showDialog(){
dialog1 = new Dialog(this);
final Dialog tradDialog = new Dialog(this, android.R.style.Theme_Light_NoTitleBar);
View view = getLayoutInflater().inflate(R.layout.trad_dialog_layout_individual, null);
tradDialog.setCanceledOnTouchOutside(false);
lv = (ListView) view.findViewById(R.id.productsListView);
RelativeLayout saveBtnLayout = (RelativeLayout) view.findViewById(R.id.saveBtnLayout);
// Change MyActivity.this and myListOfItems to your own values
clad = new CustomListAdapterDialog(SolutionActivity.this, individual_productChoosedAr);
lv.setAdapter(clad);
clad.notifyDataSetChanged();
mCount = lv.getChildCount();
saveBtnLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int getChildCount1 = lv.getChildCount();
System.out.print(getChildCount1);
for (int i = 0; i < myList.size(); i++) {
// v = lv.getChildAt(i);
// etPrice = (EditText) v.findViewById(R.id.etPrice);
if(myList.get(i).toString().equals("")){
ProductPrice = "NULL";
}else {
ProductPrice = myList.get(i).toString();
}
// if(ProductPrice.equals("")){
// ProductPrice = "NULL";
// }
productPriceAr.add(ProductPrice);
}
Toast toast = Toast.makeText(getApplicationContext(),"Please wait...",Toast.LENGTH_LONG);
toast.show();
SendIndividualDatatoServer sendIndividualData = new SendIndividualDatatoServer();
sendIndividualData.execute();
}
});
//lv.setOnItemClickListener(........);
dialog1.setContentView(view);
dialog1.show();
}
AsyncTask class for posting data from where i want to disable btIndividual button:
protected void onPostExecute(Void paramVoid) {
super.onPostExecute(paramVoid);
try {
String typeId = "", messageReceived = "";
JSONObject localJSONObject = new JSONObject(this.sendDataResponse);
typeId = localJSONObject.getString("type_id");
messageReceived = localJSONObject.getString("msg");
if (typeId.equals("1")) {
//if i reached here i want to disable that button
// if(checkHideButton == checkButtonPosition){
// btIndividual.setVisibility(View.GONE);
// customSelectedProductsAdapter.notifyDataSetChanged();
// customSelectedProductsAdapter.notifyDataSetInvalidated();
// }
Toast toast = Toast.makeText(SolutionActivity.this,"Individual Data Posted",Toast.LENGTH_LONG);
toast.show();
dialog1.dismiss();
customSelectedProductsAdapter.notifyDataSetChanged();
productPriceAr.clear();
individual_productChoosedAr.clear();
} else
Toast.makeText(SolutionActivity.this, messageReceived, Toast.LENGTH_SHORT).show();
btIndividual.setVisibility(View.VISIBLE);
} catch (Exception localException) {
localException.printStackTrace();
Toast.makeText(SolutionActivity.this, "Network Error Occured", Toast.LENGTH_SHORT).show();
}
I guess the problem is here:
} else
Toast.makeText(SolutionActivity.this, messageReceived, Toast.LENGTH_SHORT).show();
btIndividual.setVisibility(View.VISIBLE);
You set the button visible even if your condition below is true.
I suggest to modify the code something like this:
protected void onPostExecute(Void paramVoid) {
super.onPostExecute(paramVoid);
try {
//1. By default button is visible
btIndividual.setVisibility(View.VISIBLE);
String typeId = "", messageReceived = "";
JSONObject localJSONObject = new JSONObject(this.sendDataResponse);
typeId = localJSONObject.getString("type_id");
messageReceived = localJSONObject.getString("msg");
if (typeId.equals("1")) {
if(checkHideButton == checkButtonPosition){
//2. if condition is true - hide the button
btIndividual.setVisibility(View.GONE);
customSelectedProductsAdapter.notifyDataSetChanged();
customSelectedProductsAdapter.notifyDataSetInvalidated();
}
Toast toast = Toast.makeText(SolutionActivity.this,"Individual Data Posted",Toast.LENGTH_LONG);
toast.show();
dialog1.dismiss();
customSelectedProductsAdapter.notifyDataSetChanged();
productPriceAr.clear();
individual_productChoosedAr.clear();
} else
Toast.makeText(SolutionActivity.this, messageReceived, Toast.LENGTH_SHORT).show();
//3. it is not needed
//btIndividual.setVisibility(View.VISIBLE);
} catch (Exception localException) {
localException.printStackTrace();
Toast.makeText(SolutionActivity.this, "Network Error Occured", Toast.LENGTH_SHORT).show();
}
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();
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);
}
Here is a little initialization of the AlertDialog in Android and a method to verify a user using HttpClient
private void loginBox() {
USERS = db.getUserData();
login_layout = (LinearLayout) findViewById(R.id.loginlayout);
loginLayout = (LinearLayout) View.inflate(this, R.layout.login, null);
usernameEditText = (EditText) loginLayout.findViewById(R.id.username);
passwordEditText = (EditText) loginLayout.findViewById(R.id.password);
rememmber = (CheckBox) loginLayout.findViewById(R.id.checkBox1);
gallery = (Gallery) loginLayout.findViewById(R.id.users_gallery);
notificationText = (TextView) loginLayout
.findViewById(R.id.notificationtext);
userChooseText = (TextView) loginLayout
.findViewById(R.id.user_choose_text);
breakLine = (View) loginLayout.findViewById(R.id.login_break_line);
registerForContextMenu(loginLayout);
galleryVisibility();
gallery.setAdapter(new AddImgAdp(this));
if (userPrefs.getUserName() == null
&& userPrefs.getUserPassword() == null) {
if (!USERS.isEmpty()) {
System.out.println("not empty");
usernameEditText.setText(
USERS.get(gallery.getSelectedItemPosition())
.getUsername(), TextView.BufferType.EDITABLE);
passwordEditText.setText(
USERS.get(gallery.getSelectedItemPosition())
.getPassword(), TextView.BufferType.EDITABLE);
}
}
gallery.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
selectedUser = USERS.get(arg2).getUsername();
if (!USERS.isEmpty()) {
System.out.println("not empty");
usernameEditText.setText(USERS.get(arg2).getUsername(),
TextView.BufferType.EDITABLE);
passwordEditText.setText(USERS.get(arg2).getPassword(),
TextView.BufferType.EDITABLE);
}
return false;
}
});
gallery.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
usernameEditText.setText(USERS.get(position).getUsername(),
TextView.BufferType.EDITABLE);
passwordEditText.setText(USERS.get(position).getPassword(),
TextView.BufferType.EDITABLE);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
// rememmber.setOnClickListener(new View.OnClickListener() {
//
// #Override
// public void onClick(View v) {
// if (rememmber.isChecked()) {
// Toast toast = Toast.makeText(getApplicationContext(),
// "Try to avoid this option, it is unsecure!",
// Toast.LENGTH_LONG);
// toast.show();
//
// // TODO: store in DB
// }
// }
// });
Button loginButton = (Button) loginLayout
.findViewById(R.id.action_login);
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
username = usernameEditText.getText().toString();
password = passwordEditText.getText().toString();
if (rememmber.isChecked()) {
db.createNewUser(username, password);
}
if (testUser()) {
// gallery.removeAllViewsInLayout();
username = usernameEditText.getText().toString();
password = passwordEditText.getText().toString();
userPrefs.savePrefs(username, password);
alert.dismiss();
// alert.cancel();
// login = null;
// alert = null;
} else {
userPrefs.clearPrefs();
System.out.println("Gallery children: "
+ gallery.getChildCount());
notificationText.setText("Username or password incorrect!");
notificationText.setTextColor(Color.RED);
USERS = db.getUserData();
galleryVisibility();
((BaseAdapter) gallery.getAdapter()).notifyDataSetChanged();
gallery.setSelection(gallery.getCount());
}
}
});
if (!initialized) {
System.out.println("Run login box initialization");
initialized = true;
login = new AlertDialog.Builder(this);
login.setView(loginLayout).setTitle("Logon Credentials")
.setCancelable(false);
alert = login.create();
alert.show();
}
}
private void galleryVisibility() {
if (USERS.size() < 1) {
gallery.setEnabled(false);
gallery.setVisibility(LinearLayout.INVISIBLE);
breakLine.setEnabled(false);
breakLine.setVisibility(LinearLayout.INVISIBLE);
userChooseText.setEnabled(false);
userChooseText.setVisibility(LinearLayout.INVISIBLE);
} else {
gallery.setEnabled(true);
gallery.setVisibility(LinearLayout.VISIBLE);
breakLine.setEnabled(true);
breakLine.setVisibility(LinearLayout.VISIBLE);
userChooseText.setEnabled(true);
userChooseText.setVisibility(LinearLayout.VISIBLE);
}
}
private boolean testUser() {
System.out.println("Testing user");
if (usernameEditText.getText().toString()!= null
&& , passwordEditText.getText().toString() != null) {
try {
System.out.println("getting viewwstate");
String viewState = client
.httpGetViewstate("http://website/Login.aspx");
HttpResponse response = client.httpPost1(viewState,
"http://website/Login.aspx",
usernameEditText.getText().toString(), passwordEditText
.getText().toString());
System.out.println("posted!");
HttpEntity entity = response.getEntity();
String responseText = EntityUtils.toString(entity);
System.out.println(responseText);
// String commentsHtml = client
// .httpGet("http://website/PriceTables.aspx");
// System.out.println(commentsHtml);
if (responseText.contains("Log Out")) {
success = true;
System.out.println("username is ok");
this.finish();
return true;
} else {
System.out.println("back again..");
fail = true;
// loginBox();
return false;
}
} catch (SocketTimeoutException socket) {
System.out.println("login socket timeout");
} catch (IOException e) {
System.out.println("Login io exception");
}
return false;
} else {
// Intent login = new Intent(getApplicationContext(),
// Login.class);
// startActivity(login);
fail = true;
// loginBox();
return false;
}
}
The problem is that when I click login button for the first time, everything works fine, but when I click it the second time, the testUserMethod, try{ statement is ignored.. Found the problem - again, my own mistake, everything is ok now. Thank you everybody who helped
Can you check with setCancelable().. you are setting it to true once and again to false...
It looks like problem isn't here. Maybe, you did some field static?