Execute after close dialog - java

I have a button that open a dialog for change a number. The button is in activity, and generate a new class names dialogs, for storage different dialogs.
Dialog consigna: Dialogs.class
public String consigna(){
AlertDialog.Builder alert = new AlertDialog.Builder(ctxt);
alert.setTitle("Nueva temperatura");
alert.setMessage("Agrega una nueva temperatura");
final EditText input = new EditText(ctxt);
input.setInputType(InputType.TYPE_CLASS_NUMBER);
input.setRawInputType(InputType.TYPE_CLASS_NUMBER);
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
data = input.getText().toString();
}
});
alert.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//Put actions for CANCEL button here, or leave in blank
}
});
alert.show();
return data;
}
on click button: MainActivity
//I need change these two values:
final public double temperatura = 200.3;
String newData;
...
public void onClick(View v) {
switch (v.getId()){
case R.id.tempConsigna:
dialog = new Dialogs(MainActivity.this);
String data = dialog.consigna();
newData = data;
break;
...//other cases...
The issue is in newData = data; I doesn't have a data, because the dialog not are closed. The dialog work in other thread,no?
How to change newData var with the dialog result? It is posible into a dialogs class?

You need a callback method implemented via an interface:
public String consigna(final OnConfirm confirm){
final String[] data = new String[1];
AlertDialog.Builder alert = new AlertDialog.Builder(activity);
alert.setTitle("Nueva temperatura");
alert.setMessage("Agrega una nueva temperatura");
final EditText input = new EditText(activity);
input.setInputType(InputType.TYPE_CLASS_NUMBER);
input.setRawInputType(InputType.TYPE_CLASS_NUMBER);
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
data[0] = input.getText().toString();
confirm.onConfirm(data[0]);
}
});
alert.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//Put actions for CANCEL button here, or leave in blank
}
});
alert.show();
return data[0];
}
public interface OnConfirm {
void onConfirm(String s);
}
And in your Main Activity
Dialogs dialog = new Dialogs(MainActivity.this);
dialog.consigna(new Dialogs.OnConfirm() {
#Override
public void onConfirm(String s) {
Log.d("data", s);
}
});

It will not return result as you want but after click on dialog ok button then access data variable. no need to return.

Related

Set text Length of alert dialog in Android studio

How do I set the max of how many characters can be entered. So now the user can enter a lot in the alertdialog While it should have the max. it's not like XML. That would have been easier, any tips for this alert dialog?
private void RequestNewGroup()
{
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this, R.style.AlertDialog);
builder.setTitle("Enter Group Name ");
final EditText groupNameField = new EditText(MainActivity.this);
groupNameField.setHint("");
builder.setView(groupNameField);
builder.setPositiveButton("Create", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i)
{
String groupName = groupNameField.getText().toString();
if (TextUtils.isEmpty(groupName))
{
Toast.makeText(MainActivity.this, "Please write Group Name...", Toast.LENGTH_SHORT).show();
}
else
{
CreateNewGroup(groupName);
}
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i)
{
dialogInterface.cancel();
}
});
builder.show();
}
You need to add a InputFilter to your EditText
final EditText groupNameField = new EditText(MainActivity.this);
groupNameField.setHint("");
// ### -> max length
groupNameField.setFilters(new InputFilter[]{ new InputFilter.LengthFilter(###) });

Sending alert dialog entry to mysql database

Am new to android and i have successfully manged to show data from mysql database in a list and set an alert dialog for when an item is clicked.The Alert dialog has to take in a comment about the item clicked and send it to the mysql database but am stuck at making the connection.
Here is my code
public void showList(){
try {
JSONObject jsonObj = new JSONObject(myJSON);
peoples = jsonObj.getJSONArray(TAG_RESULTS);
for(int i=0;i<peoples.length();i++){
JSONObject c = peoples.getJSONObject(i);
String id = c.getString(TAG_ID);
String fname = c.getString(TAG_FNAME);
String lname = c.getString(TAG_LNAME);
String idnum = c.getString(TAG_IDNUM);
HashMap<String,String> persons = new HashMap<String,String>();
persons.put(TAG_ID,id);
persons.put(TAG_FNAME,fname);
persons.put(TAG_LNAME,lname);
persons.put(TAG_IDNUM,idnum);
personList.add(persons);
}
final ListAdapter adapter = new SimpleAdapter(
SearchActivity.this, personList, R.layout.list_activity,
new String[]{TAG_ID,TAG_FNAME,TAG_LNAME,TAG_IDNUM},
new int[]{R.id.id, R.id.textViewFname, R.id.textViewLname,R.id.textViewIdnum}
);
list.setAdapter(adapter);
//alert dialog
//Create onclick listener class
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
/* Alert Dialog Code Start*/
AlertDialog.Builder alert = new AlertDialog.Builder(context);
alert.setTitle("Alert id: "+TAG_IDNUM); //Set Alert dialog title here
alert.setMessage("Enter Your Comment here"); //Message here
// Set an EditText view to get user input
final EditText input = new EditText(context);
alert.setView(input);
alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// convert the input to a string and show in a toast.
String srt = input.getEditableText().toString();
Toast.makeText(SearchActivity.this,"Commenting Added", Toast.LENGTH_LONG).show();
} // End of onClick(DialogInterface dialog, int whichButton)
}); //End of alert.setPositiveButton
alert.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
Toast.makeText(SearchActivity.this,"Commenting cancled",Toast.LENGTH_LONG).show();
dialog.cancel();
}
}); //End of alert.setNegativeButton
AlertDialog alertDialog = alert.create();
alertDialog.show();
/* Alert Dialog Code End*/
// End of onClick(View v)
}
});}
catch (JSONException e){}
}
So i managed to come up with the following but the variables am sending to the php file don't seem to be getting there.
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
/* Alert Dialog Code Start*/
AlertDialog.Builder alert = new AlertDialog.Builder(context);
final String id_number =((TextView)view.findViewById(R.id.textViewIdnum)).getText().toString();
alert.setTitle("Alert id: "+id_number); //Set Alert dialog title here
alert.setMessage("Enter Your Comment here"); //Message here
// Set an EditText view to get user input
final EditText input = new EditText(context);
alert.setView(input);
alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// convert the input to a string and show in a toast.
String reason = input.getEditableText().toString();
Toast.makeText(SearchActivity.this,"Commenting...", Toast.LENGTH_LONG).show();
final String reason_key = input.getText().toString().trim();
//final String id_number_key = textview;
StringRequest stringRequest = new StringRequest(Request.Method.POST, Config.RESULT_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(SearchActivity.this,response,Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(SearchActivity.this,error.toString(),Toast.LENGTH_LONG).show();
}
});
Map<String,String> params = new HashMap<String, String>();
params.put(TAG_IDNUM,id_number);
params.put(reason_key,reason);
RequestQueue requestQueue = Volley.newRequestQueue(SearchActivity.this);
requestQueue.add(stringRequest);
} // End of onClick(DialogInterface dialog, int whichButton)
}); //End of alert.setPositiveButton
alert.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
Toast.makeText(SearchActivity.this,"Commenting cancled",Toast.LENGTH_LONG).show();
dialog.cancel();
}
}); //End of alert.setNegativeButton
AlertDialog alertDialog = alert.create();
alertDialog.show();
/* Alert Dialog Code End*/
// End of onClick(View v)
}
});}
catch (JSONException e){}
}

Remember what was selected in single choice AlertDialog

I have an AlertDialog which displays an array into a single selected choice:
protected boolean blFrom, blTo;
protected void showSelectToDialog() {
boolean[] checkedDate = new boolean[toDate.length];
int count = toDate.length;
DialogInterface.OnClickListener setD2 = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//TODO Auto-generated method stub
onChangeSelectedTo(which);
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select To Year");
builder.setSingleChoiceItems(toDate, count, setD2);
builder.setCancelable(true);
builder.setPositiveButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
dialog2 = builder.create();
dialog2.show();
}
protected void onChangeSelectedTo(int j) {
bTo.setText(toDate[j]);
sTo = ((AlertDialog)dialog2).getListView().getCheckedItemPosition();
blTo = true;
displayToast(String.valueOf(sTo));
to = j;
dialog.dismiss();
}
What I want to do is the first time it loads it should display the default. Once I select a choice and the dialog closes and I bring up the same dialog again it should show the previously selected choice I made and scroll to it.
How do I accomplish it?
As of right now, I can get the selected position but what next?
You can store the chosen value in a variable of your Activity or using SharedPreferences

Code breaks at AlertDialog creation. I think I have Context wrong...?

i can't seem to figure out why my app/code is crashing in this section. Any help would be appreciated. I think the problem lies on the creation of an AlertDialog in the else if statement.
Basically, this method is called on first launch of the application and asks the user to choose between two options: OCPS and Other. When OCPS is chosen, a SharedPreference is set. When other is selected, an AlertDialog with text box should pop up, allowing the user to input their own local URL, which is then saved to the SharedPreference.
Full code is available here: https://github.com/danielblakes/progressbook/
code follows:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
boolean firstrun = getSharedPreferences(
"com.danielblakes.progressbook", MODE_PRIVATE).getBoolean(
"firstrun", true);
if (firstrun) {
new AlertDialog.Builder(this).setTitle("First Run").show();
pickDistrict(this);
getSharedPreferences("com.danielblakes.progressbook", MODE_PRIVATE)
.edit().putBoolean("firstrun", false).commit();
}
else {
String saved_district = getSharedPreferences(
"com.danielblakes.progressbook", MODE_PRIVATE).getString(
"district", null);
startupWebView(saved_district);
}
}
public Dialog pickDistrict(final Context context) {
AlertDialog.Builder districtalert = new AlertDialog.Builder(context);
districtalert
.setTitle(R.string.choose_district)
.setItems(R.array.districts,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int i) {
if (i == 0) {
String district_site = "https://parentaccess.ocps.net/General/District.aspx?From=Global";
startupWebView(district_site);
getSharedPreferences(
"com.danielblakes.progressbook",
MODE_PRIVATE)
.edit()
.putString("district",
district_site).commit();
} else if (i == 1) {
AlertDialog.Builder customdistrict = new AlertDialog.Builder(context);
customdistrict
.setTitle(
R.string.custom_district_title)
.setMessage(
R.string.custom_district_message);
final EditText input = new EditText(
getParent());
customdistrict.setView(input);
customdistrict
.setPositiveButton(
"Ok",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
String custom_url = input
.getText()
.toString();
getSharedPreferences(
"com.danielblakes.progressbook",
MODE_PRIVATE)
.edit()
.putString(
"district",
custom_url)
.commit();
}
});
customdistrict
.setNegativeButton(
"Cancel",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
return;
}
}).show();
}
}
}).show();
return districtalert.create();
}
}
Change
AlertDialog.Builder customdistrict = new AlertDialog.Builder(this);
to
AlertDialog.Builder customdistrict = new AlertDialog.Builder(context);
also,
final EditText input = new EditText(getParent());
needed to be changed to
final EditText input = new EditText(context);

Returning through multiple functions

Alright, this might be kinda simple, but I cannot figure out how to do this. How can I change this function to return the String class_name? I know that I need to change the function from void to String, but what else do I need to do?
Much appreciated!
public void addClass() {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Add Class");
final EditText input = new EditText(this);
alert.setView(input);
alert.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String class_name = input.getText().toString();
}
});
alert.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
});
alert.show();
}
Returning the class_name value doesn't help. You have to implement a callback method that takes the value and performs the required action:
public void addClass() {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
// ...
alert.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
setClassName(input.getText().toString());
}
});
// ...
}
protected void setClassName(String class_name) {
// do what ever has to be done with class_name
}
The behavior (a synchronous dialog) you are trying to get deliberately does not exist in android. Whatever you want to happen when the dialog button is clicked has to be placed in the OnClickListener.OnClick method.
Assuming alert.show does not return until input.getText() contains the entered value, you could try:
public void addClass() {
final Vector<String> retval = new Vector<String>();
retval.add("");
...
...
alert.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String class_name = input.getText().toString();
retval.set(0,class_name);
}
});
...
...
return retval.get(0);
}
AlertDialog is asynchronous and therefore what you want to achieve is not possible through that code.
you could set String class_name as global ad then initialize it to
class_name = input.getText().toString();
inside the onClick method of alert Button.

Categories