Its a game in which at the end activity the score is displayed But before that the input alert box is displayed where user need to add their name,and that name and score should go to the database. score is getting stored but not the name. how to get name from input alert dialog box and set it on db.insertScore(Score,Name).how am i suppose to add input value of alert dialog box to extra.getString(""); there is getter & setter method.here is my code
Bundle extra = getIntent().getExtras();
if (extra != null)
{
showInputDialog();
final String Name=extra.getString("");
final int Score = extra.getInt("SCORE");
final int totalQuestion = extra.getInt("TOTAL");
int correctAnswer = extra.getInt("CORRECT");
txtTotalScore.setText(String.format("SCORE : %d", Score));
txtTotalQuestion.setText(String.format("PASSED : %d/%d", correctAnswer, totalQuestion));
progressBarResult.setMax(totalQuestion);
progressBarResult.setProgress(correctAnswer);
db.insertScore(Score, Name);
}
}
protected void showInputDialog() {
// get prompts.xml view
LayoutInflater layoutInflater = LayoutInflater.from(Done.this);
View promptView = layoutInflater.inflate(R.layout.dialog, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(Done.this);
alertDialogBuilder.setView(promptView);
final EditText editText = (EditText) promptView.findViewById(R.id.edittext);
// setup a dialog window
alertDialogBuilder.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
String Name = editText.getText().toString();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
try this
protected void showInputDialog() {
// get prompts.xml view
LayoutInflater layoutInflater = LayoutInflater.from(Done.this);
View promptView = layoutInflater.inflate(R.layout.dialog, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(Done.this);
alertDialogBuilder.setView(promptView);
final EditText editText = (EditText) promptView.findViewById(R.id.edittext);
// setup a dialog window
alertDialogBuilder.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
String Name = editText.getText().toString();
//call a function which do in background and have a connection with database
new setname(Name);
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
private void setname(final String name){
#Override
protected String doInBackground(String... params){
Data = new HashMap<String, String>();
Data.put("name", name);
try {
JSONObject json = Connection.UrlConnection("http://url", Data);
int succ = json.getInt("success");
if (succ == 0) {
s = "false";
} else {
s = "true";
}
} catch (Exception e) {
}
return s;
}
}
}
Also write a php file which code insert to db
Make the Name variable global and don't use the following line :
String Name;
Bundle extra = getIntent().getExtras();
if (extra != null)
{
showInputDialog();
final int Score = extra.getInt("SCORE");
final int totalQuestion = extra.getInt("TOTAL");
int correctAnswer = extra.getInt("CORRECT");
txtTotalScore.setText(String.format("SCORE : %d", Score));
txtTotalQuestion.setText(String.format("PASSED : %d/%d", correctAnswer, totalQuestion));
progressBarResult.setMax(totalQuestion);
progressBarResult.setProgress(correctAnswer);
db.insertScore(Score, Name);
}
}
protected void showInputDialog() {
// get prompts.xml view
LayoutInflater layoutInflater = LayoutInflater.from(Done.this);
View promptView = layoutInflater.inflate(R.layout.dialog, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(Done.this);
alertDialogBuilder.setView(promptView);
final EditText editText = (EditText) promptView.findViewById(R.id.edittext);
// setup a dialog window
alertDialogBuilder.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Name = editText.getText().toString();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
Related
I only want my AlertDialog to be dismissed when certain conditions are met (when name and surname given are valid) - else it should always be on top of the parent view. My code is this:
final AlertDialog.Builder alert = new AlertDialog.Builder(this);
final TextView instructions = new TextView(this);
instructions.setText(R.string.alert_enter_data);
final EditText name = new EditText(this);
name.setHint(R.string.name);
final EditText surname = new EditText(this);
surname.setHint(R.string.surname);
LinearLayout ll=new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
ll.addView(instructions);
ll.addView(name);
ll.addView(surname);
alert.setView(ll);
alert.setNeutralButton(R.string.enter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String name_txt = name.getText().toString();
String surname_txt = surname.getText().toString();
if ((name_txt.length() > 1) && (surname_txt.length() > 1)) {
dialog.dismiss();
}
}
});
final AlertDialog alert_dialog = alert.create();
alert_dialog.setCanceledOnTouchOutside(false);
alert_dialog.show();
With this code the AlertDialog disappears when the button is pressed, regardless of the input text. I then tried this:
alert_dialog.setOnShowListener(new DialogInterface.OnShowListener() {
#Override
public void onShow(DialogInterface dialog) {
Button b = alert.getButton(AlertDialog.BUTTON_POSITIVE);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String name_txt = name.getText().toString();
String surname_txt = surname.getText().toString();
String email_txt = email.getText().toString();
String cellphone_txt = cellphone.getText().toString();
String postcode_txt = postcode.getText().toString();
if ((name_txt.length() > 1) && (surname_txt.length() > 1) && (email_txt.length() > 4)) {
if (debug_mode) {Log.i(TAG,"clause 1");}
String data_to_upload = name_txt + ", " + surname_txt + ", " + email_txt + ", "+ cellphone_txt + ", " + postcode_txt + "\n";
// upload_to_github(data_to_upload);
alert_dialog.dismiss();
}
}
});
}
});
But this way I get not Button at all. The Alert Dialog only contains the EditText fields.
alert.setNeutralButton(R.string.enter, new DialogInterface.OnClickListener() {
and
Button b = alert.getButton(AlertDialog.BUTTON_POSITIVE);
both are different buttons.
try
Button b = alert.getButton(AlertDialog.BUTTON_NEUTRAL);
I'm using alert dialog to show some records.those records are comming from db and display in Alertdialog.when user click on item i want to get item name to Log.this is my code.it show item as [test] but i want it showing as test
ArrayList arrayList and String [] categoryStrings initialized on top
List<Video> vd=Video.findWithQuery(Video.class, "select * from Video");
if (vd.size()>0) {
for (Video v : vd) {
arrayList.add(v.getTitle());
}
final List<String> list = Arrays.asList(arrayList.toString());
categoryStrings=new String[list.size()];
categoryStrings=list.toArray(categoryStrings);
AlertDialog.Builder alert = new AlertDialog.Builder(Editmedia.this);
alert.setTitle("Media List");
alert.setCancelable(false);
final int selected = 0; // or whatever you want
alert.setSingleChoiceItems(categoryStrings, selected, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
//onclick
String categoryString = categoryStrings[item];
Log.d("sel", " " + item+" "+categoryString);
edit();
}
});
alert.show();
log value showing
0 [test] i want it as test
Log
Try this, it should help
String categoryString = categoryStrings[item];
categoryString = categoryString.replaceAll("[\\p{Ps}\\p{Pe}]","");
Log.d("sel", " " +" "+categoryString);
[EDIT]
String categoryString = categoryStrings[item];
categoryString = categoryString.replace("[","");
categoryString = categoryString.replace("]","");
Log.d("sel", " " +" "+categoryString);
Try this:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Media List");
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1);
arrayAdapter.clear();
for (int i = 0; i < list.size(); i++) {
Log.i(LOG_TAG, list.get(i));
arrayAdapter.add(list.get(i));
}
builder.setAdapter(arrayAdapter, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), list.get(which),
Toast.LENGTH_LONG).show();
}
});
builder.setPositiveButton("Cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
I have 2 EditTexts that get a String and when the Button is clicked it converts char of this String to int. It then sums all int of chars and when sum of int is odd (totals&1 == 0) a Dialog shows "that is odd". And after else, the second Dialog shows "that is even". I need to set AlertDialog to show that.
final EditText ed1 = (EditText) findViewById(R.id.edtFather);
final EditText ed2 = (EditText) findViewById(R.id.edtMother);
//final TextView tv = (TextView) findViewById(R.id.txtfather);
Button btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String dataF = ed1.getText().toString();
char[] charArray = dataF.toCharArray();
int totalF = 0;
for (char ch: charArray) {
totalF += characterMap.get(ch);
}
String dataM = ed2.getText().toString();
char[] charArr = dataM.toCharArray();
int totalM = 0;
for (char ch2: charArr) {
totalM += characterMap.get(ch2);
}
int sum = totalF + totalM;
int totals = sum % 5;
if ((totals & 1) == 0)
//alert dialog 1 show "that is odd"
else {
//alert dialog 2 show "that is even"
}
}
});
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage("that is odd");
builder.setCancelable(true);
AlertDialog alert = builder.create();
alert.show();
Just write "that is even" instead of "that is odd" for the second dialog.
Use Toast for this purpose, they are a lot easier and fast for a single message.
Toast.makeText(this, "Your Message here",
Toast.LENGTH_LONG).show();
i found that i use AlertDialog like this :
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
AlertDialog.Builder builder = new AlertDialog.Builder(StartActivity.this);
builder.setMessage("that is odd");
builder.setCancelable(true);
AlertDialog alert = builder.create();
String dataF = ed1.getText().toString();
char[] charArray = dataF.toCharArray();
int totalF = 0;
for (char ch: charArray) {
totalF += characterMap.get(ch);
}
String dataM = ed2.getText().toString();
char[] charArr = dataM.toCharArray();
int totalM = 0;
for (char ch2: charArr) {
totalM += characterMap.get(ch2);
}
int sum = totalF + totalM;
int totals = sum % 5;
if ((totals & 1) == 0)
alert.show();
else {
AlertDialog.Builder builder1 = new AlertDialog.Builder(StartActivity.this);
builder1.setMessage("that is even");
builder1.setCancelable(true);
AlertDialog alert1 = builder1.create();
alert1.show();
}
}
});
I have a spinner, how can i bind it to an AlertDialog? It is possible to do that?
please try this :
public class WvActivity extends Activity {
TextView tx;
String[] s = { "India ", "Arica", "India ", "Arica", "India ", "Arica",
"India ", "Arica", "India ", "Arica" };
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final ArrayAdapter<String> adp = new ArrayAdapter<String>(WvActivity.this,
android.R.layout.simple_spinner_item, s);
tx= (TextView)findViewById(R.id.txt1);
final Spinner sp = new Spinner(WvActivity.this);
sp.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
sp.setAdapter(adp);
AlertDialog.Builder builder = new AlertDialog.Builder(WvActivity.this);
builder.setView(sp);
builder.create().show();
}
}
Instead why don't you use an activity and set it to Dialog style. Should be like the same visual approach and you can design your dialog just as you want it.
public void CreateAlertDialog1() {
LayoutInflater inflater = getLayoutInflater();
View alertLayout = inflater.inflate(R.layout.note_dialog, null);
final EditText etName = (EditText) alertLayout.findViewById(R.id.enter_name);
final TextView call_date = alertLayout.findViewById(R.id.call_date);
call_date.setVisibility(View.GONE);
date_time_display = alertLayout.findViewById(R.id.date_time_display);
date_time_select = alertLayout.findViewById(R.id.date_time_select);
final Spinner spSex = (Spinner) alertLayout.findViewById(R.id.spinner);
String[] status_note = new String[] {
"Laceflower",
"Sugar maple",
"Mountain mahogany",
"Butterfly weed"
};
final List<String> plantsList = new ArrayList<>(Arrays.asList(status_note));
// Initializing an ArrayAdapter
#SuppressLint({"NewApi", "LocalSuppress"}) final ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(
Objects.requireNonNull(getActivity()),R.layout.spinner_item,plantsList);
spinnerArrayAdapter.setDropDownViewResource(R.layout.spinner_item);
spSex.setAdapter(spinnerArrayAdapter);
date_time_select.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getActivity().getSupportFragmentManager(), "datePicker");
}
});
AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
alert.setTitle(client_name_display);
alert.setIcon(getActivity().getResources().getDrawable(R.drawable.addnote));
alert.setView(alertLayout);
alert.setCancelable(false);
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getActivity().getBaseContext(), "Cancel clicked", Toast.LENGTH_SHORT).show();
OkHttpHandler okHttpHandler = new OkHttpHandler(status, res, start_date_time, end_date_time, etName.getText().toString());
okHttpHandler.execute("https://management.reflectdm.com/api/call-management");
}
});
alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String user = etName.getText().toString();
String sex = String.valueOf(spSex.getSelectedItem());
//Toast.makeText(getBaseContext(), "Name: " + user + "\nBirthday: " + bday + "\nSex: " + sex + "\nHungry: " + hungry, Toast.LENGTH_SHORT).show();
OkHttpHandler okHttpHandler = new OkHttpHandler(status, res, start_date_time, end_date_time, etName.getText().toString());
okHttpHandler.execute("https://management.reflectdm.com/api/call-management");
}
});
AlertDialog dialog = alert.create();
dialog.show();
}
I have a function to find an employee's id number from my sqlite database. The function allows the user to look up by id or name (first and/or last); therefore it creates several dialog boxes and finds the data through an If Else Then tree. Here's the code for those who like that sort of thing:
public String getEmployeeID() {
final CharSequence[] items = {"By ID", "By Name", "Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(LibraryScreen.this);
builder.setTitle("Find Employee");
builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if(items[item].equals("Cancel")) {
dialog.cancel();
empid = "";
} else if(items[item].equals("By ID")) {
dialog.cancel();
final Dialog dialog2 = new Dialog(LibraryScreen.this);
dialog2.setContentView(R.layout.peopledialog);
dialog2.setTitle("Employee ID");
dialog2.setCancelable(true);
//Set Visibility of the Rows
TableRow tblrow1 = (TableRow) dialog2.findViewById(R.id.trGeneral);
tblrow1.setVisibility(0);
//Set Captions for Rows
TextView txtvw1 = (TextView) dialog2.findViewById(R.id.tvGeneral);
txtvw1.setText("Employee ID");
//Set Up Edit Text Boxes
EditText edttxt1 = (EditText) dialog2.findViewById(R.id.txtGeneral);
//Set Input Type
edttxt1.setRawInputType(0x00000002);//numbers
edttxt1.setText("");
//set max lines
edttxt1.setMaxLines(1);
//Set MaxLength
int maxLength;
maxLength = 15;
InputFilter[] FilterArray = new InputFilter[1];
FilterArray[0] = new InputFilter.LengthFilter(maxLength);
edttxt1.setFilters(FilterArray);
Button button = (Button) dialog2.findViewById(R.id.btnTxtDiaSav);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
EditText emplid = (EditText) dialog2.findViewById(R.id.txtGeneral);
String newemp = "";
db.open();
Cursor c = db.getEmployee(emplid.getText().toString());
if(c.moveToFirst()) {
empid = c.getString(c.getColumnIndex("employeeid"));
} else {
Toast.makeText(LibraryScreen.this, "No ID Match", Toast.LENGTH_LONG).show();
empid = "";
}
c.close();
db.close();
dialog2.dismiss();
}
});
Button buttonCan = (Button) dialog2.findViewById(R.id.btnTxtDiaCan);
buttonCan.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog2.dismiss();
empid = "";
}
});
dialog2.show();
} else if(items[item].equals("By Name")) {
dialog.cancel();
final Dialog dialog1 = new Dialog(LibraryScreen.this);
dialog1.setContentView(R.layout.peopledialog);
dialog1.setTitle("Employee's Name");
dialog1.setCancelable(true);
//Set Visibility of the Rows
TableRow tblrow1 = (TableRow) dialog1.findViewById(R.id.trGeneral);
tblrow1.setVisibility(0);
//Set Captions for Rows
TextView txtvw1 = (TextView) dialog1.findViewById(R.id.tvGeneral);
txtvw1.setText("Employee Name");
//Set Up Edit Text Boxes
EditText edttxt1 = (EditText) dialog1.findViewById(R.id.txtGeneral);
//Set Input Type
edttxt1.setRawInputType(0x00002001);//cap words
edttxt1.setText("");
//set max lines
edttxt1.setMaxLines(1);
//Set MaxLength
int maxLength;
maxLength = 50;
InputFilter[] FilterArray = new InputFilter[1];
FilterArray[0] = new InputFilter.LengthFilter(maxLength);
edttxt1.setFilters(FilterArray);
Button button = (Button) dialog1.findViewById(R.id.btnTxtDiaSav);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
EditText emplid = (EditText) dialog1.findViewById(R.id.txtGeneral);
String firstname = emplid.getText().toString();
String lastname = "";
String matchlist = "";
String temptext = "";
int matchcount = 0;
if(firstname.lastIndexOf(" ") <= 0) {
lastname = firstname;
firstname = "X";
} else {
lastname = firstname.substring(firstname.lastIndexOf(" ") + 1);
firstname = firstname.substring(0, firstname.lastIndexOf(" "));
}
db.open();
Cursor c1, c2;
String titletext = "";
if(firstname.length() > 0) {
c1 = db.getEmployeeByName(lastname, firstname);
if(c1.getCount() == 0) {
c1 = db.getRowByFieldTextOrdered("employees", "lastname", lastname, "lastname, firstname");
if(c1.getCount() == 0) {
Toast.makeText(LibraryScreen.this, "No matching Employees.", Toast.LENGTH_LONG).show();
empid = "";
}
}
if(c1.getCount() > 0) {
do {
c2 = db.getRowByField("orgcodes", "manager", c1.getString(c1.getColumnIndex("employeeid")));
if(c2.moveToFirst()) {
if(c2.getString(c2.getColumnIndex("orgcode")).substring(9, 10).equals("0")) {
if(c2.getString(c2.getColumnIndex("orgcode")).substring(7, 8).equals("0")) {
if(c2.getString(c2.getColumnIndex("orgcode")).substring(5, 6).equals("0")) {
if(c2.getString(c2.getColumnIndex("orgcode")).substring(4, 5).equals("0")) {
if(c2.getString(c2.getColumnIndex("orgcode")).substring(3, 4).equals("0")) {
titletext = "Top Brass";
} else {
titletext = "Senior VP";
}
} else {
titletext = "VP";
}
} else {
titletext = "Director";
}
} else {
titletext = "Senior Manager";
}
} else {
titletext = "Manager";
}
} else {
titletext = "Employee";
}
matchcount++;
matchlist = matchlist + c1.getString(c1.getColumnIndex("employeeid")) + ": " + c1.getString(c1.getColumnIndex("firstname")) + " " + c1.getString(c1.getColumnIndex("lastname")) + ": " + titletext + "|";
} while(c1.moveToNext());
}
} else {
empid = "";
}
if(matchcount == 0) {
db.close();
Toast.makeText(LibraryScreen.this, "No matching Employees.", Toast.LENGTH_LONG).show();
empid = "";
} else {
final CharSequence[] items = new CharSequence[matchcount + 1];
items[0] = "(Cancel)";
for(int i = 1; i <= matchcount; i++) {
items[i] = matchlist.substring(0, matchlist.indexOf("|"));
matchlist = matchlist.substring(matchlist.indexOf("|") + 1);
}
db.close();
AlertDialog.Builder builder1 = new AlertDialog.Builder(LibraryScreen.this);
builder1.setTitle("Select Employee");
builder1.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if(items[item].equals("(Cancel)")) {
dialog.cancel();
empid = "";
} else {
String wasted = items[item].toString();
empid = wasted.substring(0, wasted.indexOf(":"));
dialog.cancel();
}
}
});
AlertDialog alert1 = builder1.create();
alert1.show();
}
dialog1.dismiss();
}
});
Button buttonCan = (Button) dialog1.findViewById(R.id.btnTxtDiaCan);
buttonCan.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog1.dismiss();
empid = "";
}
});
dialog1.show();
}
}
});
AlertDialog alert = builder.create();
alert.show();
return empid;
}
I use the employee id for a variety of functions through multiple activities in my program. Up to now, I've simply pasted the code under each listener that needs the id, but that is such a waste of space IMHO.
My question:
Is there a way to put this function somewhere that can be called from many different activities?
If so:
How do I do that?
How do I set the context for the dialog boxes for multiple activities?
How do I get the employee id back to the function that needs it?
I'm sure this has been asked before, but I haven't been able to find it online: actually, I'm not even sure how to word the query right. My attempts have come up woefully short.
A little late to the party - but recorded for posterity:
Read up on the Application class:
Base class for those who need to maintain global application state.
You can provide your own implementation by specifying its name in your
AndroidManifest.xml's tag, which will cause that class
to be instantiated for you when the process for your
application/package is created.
Basically, this would give you the ability to obtain a single object that represents your running application (think of it as a singleton that returns an instance of your running app).
You first start off by creating a class that extends Application base class and defining any common code that is used throughout your application
import android.app.Application;
public class MyApplication extends Application {
public void myGlobalBusinessLogic() {
//
}
}
Then tell your application to use the MyApplication class instead of the default Application class via the <application> node in your app manifest:
<application android:icon="#drawable/icon" android:label="#string/app_name"
android:name="MyApplication">
Finally, when you need to get to your common function just do something like:
MyApplication application = (MyApplication) getApplication();
application.myGlobalBusinessLogic();
If you need to get the context from any part of your application, you can simple return it by calling getApplicationContext() (defined in the base Application class) via a getter method within your custom application class.