AlertDialog in custom Hashmap array adapter - android

I am creating a custom Hash map array adapter.In that,when the user clicks on an element, an AlertDialog pops up,in that user can see his messaages,
For this I am using this code,
final AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("PassWord Protected Message");
alert.setMessage("Please Enter The Password to See The Messages");
// Set an EditText view to get user input
final EditText input = new EditText(this);
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int whichButton)
{
// Editable value = input.getText();
// Do something with value!
String we=input.getText().toString();
// Toast.makeText(getApplicationContext(), we, Toast.LENGTH_SHORT ).show();
if (we.equalsIgnoreCase("password"))
{
try
{
String[] splitted = smsList.get( pos ).split("\n");
String sender = splitted[0];
for ( int i = 1; i < splitted.length; ++i )
{
//some code here
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});
alert.show();
This AlertDialog will ask user to enter a password.Then user will be able to see the messages.
But I am getting error ,
String[] splitted = smsList.get( pos ).split("\n");
In this,I am getting error on split function and the error is "The method split(String) is undefined for the type HashMap".

You'll have to type cast the smsList to String
String[] splitted = ((String)smsList.get( pos )).split("\n");

Related

how to show values in the second edittext only if user puts all the correct values in the first edit text

what should add in the code so that values are shown in the other text box only when the user have entered only corrected values...because with this code it is showing both the corrected values in the text box and incorrect in the dialog box..
String s=editText1.getText().toString();
String z[]=s.split("\\s");
editText2.setText("");
String a = "";
String b = " Not valid";
boolean is_open_dialog=false;
for(int i=0;i<z.length;i++)
{
int j=Integer.parseInt(z[i]);
if(j>=65 && j<=97)
{
editText2.setText(editText2.getText() + "" + String.valueOf((char) j));
}
else {
is_open_dialog = true;
a += z[i]+"\t";
}
}
if(is_open_dialog){
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle("Error");
alertDialogBuilder.setCancelable(false);
alertDialogBuilder.setMessage(a+b)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
I do not know if I have clear your problem, but try this:
...
if(is_open_dialog){
editText2.setText("");
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle("Error");
...
}

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: how to send a httppost request after n dialog inputs

I have a method which retrieves an array of user requests. I iterate through this array, showing a Dialog with positive and negative buttons. When the last Dialog has been confirmed whether with yes or no, a httppost is sended to a server to process the data. I builded up the function like this:
private void processRequests(String resJSON){
try {
JSONArray array = new JSONArray(resJSON);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Neue Herausvorderung");
builder.setCancelable(false);
final int ARRAY_LENGTH = array.length();
for(int i=0; i<array.length(); i++){
JSONObject obj = array.getJSONObject(i);
final String NAME= obj.getString("userName");
final long ID= obj.getLong("userID");
final int INDEX= i;
builder.setMessage(name + " fordert dich zu einem Duell heraus! Willst du annehmen?");
builder.setPositiveButton("JA", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
acceptedUsers.add(new User(ID, NAME));
if(INDEX== ARRAY_LENGTH-1){
sendRequestStuff();
}
}
});
builder.setNegativeButton("NEIN", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
declinedUsers.add(new User(ID, NAME));
if(INDEX== ARRAY_LENGTH-1){
sendRequestStuff();
}
}
});
AlertDialog alert = builder.create();
alert.show();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
The problem is, as soon as the first Dialog is confirmed, sendRequestStuff() gets called. I suspect the Listeners to cause the bug, but I am not sure. How can this be solved?
You send the request after getting a response from the last dialog: if(INDEX== ARRAY_LENGTH-1).
Because you are running a loop over the whole array (from 0 to ARRAY_LENGTH-1) and show a dialog for each, the dialogs will be shown in this order: 0, 1, 2, 3, ...., ARRAY_LENGTH-1, which means that the last one that will be shown is ARRAY_LENGTH-1. This is the first dialog that you confirm/decline, and when you do it, you actually make a callback for setPositiveButton or setNegativeButton, and (INDEX== ARRAY_LENGTH-1) is true.
To solve this, just change the condition in the callbacks: if(INDEX == 0).

Android: MessageBox not working

I am trying to do some data verification. In short, when an add button is pressed, if certain fields are not filled in then I want to display a message box and return from further processing.
This is the flow of my code without the messageBox code:
Button add = (Button) findViewById(R.id.addButton);
add.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
//local vars
String access;
String gender;
String avail;
String availCode;
// getting values from selected editItems
String name = textName.getText().toString();
String street = textStreet.getText().toString();
String city = textCity.getText().toString();
String state = textState.getText().toString();
String postal = textPostal.getText().toString();
String country = textCountry.getText().toString();
String directions = textDirections.getText().toString();
String comments = textComments.getText().toString();
//verify miniminal data
if((name.equals("")) || (street.equals(""))|| (city.equals("")) || (state.equals("")) || (postal.equals("")) || (country.equals("")))
{
}
I tried pasting in this code:
//verify miniminal data
if((name.equals("")) || (street.equals(""))|| (city.equals("")) || (state.equals("")) || (postal.equals("")) || (country.equals("")))
{
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setCancelable(false);
builder.setTitle("Title");
builder.setInverseBackgroundForced(true);
builder.setMessage("Must enter minimal data.");
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
return;
}
});
AlertDialog alert = builder.create();
alert.show();
}
But...I cannot get this line to build:
AlertDialog.Builder builder = new AlertDialog.Builder(context);
Eclipse is saying context cannot be resolved to a variable.
I am confused as to what to do. Can someone help?
I don't see a context variable anywhere in the code above, and AlertDialog.Builder's constructor needs a Context instance passed to it.
However, since you're doing this from an OnClickListener's onClick(), you can use View#getContext() to get a Context instance.
AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());

Categories

Resources