Pop up window with dynamic list view - android

I have an Array list of xml files (xmlList) created like that :
private static ArrayList<File> xmlList = new ArrayList<File>();
public static ArrayList<File> XMLContact(File directory, File contactDirectory,
ArrayList<Contact> myContactList) {
if (!(directory.exists())) {
directory.mkdirs();}
if (!(contactDirectory.exists())) {
contactDirectory.mkdirs();
}
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy hh-mm-ss");
String FileName = df.format(c.getTime());
File newxmlfile = new File(Environment.getExternalStorageDirectory()+ "/newfile/contactfile/"+FileName+"xml");
xmlList.add(newxmlfile);
And then want to show the elements of this list in a pop up window (after clicking in a button: button contact ) .So I wrote this code
private void onClickButtonContact(View view) {
Button myButton = (Button) view.findViewById(R.id.buttonContact);
myButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
xmlList = CreateContactXML.getXmlList();
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
for (int i =1 ; i< xmlList.size(); i++)
{Log.e ( null, xmlList.get(i).getAbsolutePath());
final String path ;
path = xmlList.get(i).getName();
builder.setTitle("Backup Date");
builder.setItems(i, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
Toast.makeText(getActivity(), "Restore done for ", Toast.LENGTH_SHORT).show();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
}
});
}
The List is created and i can loggout its elements. But the problem is that the pop window contains only the title .

Show List in Alert as:
ArrayList<String> arrfile_path=new ArrayList<String>();
for (int i =1 ; i< xmlList.size(); i++)
arrfile_path.add(xmlList.get(i).getAbsolutePath());
builder.setTitle("Backup Date");
builder.setItems(arrfile_path, new DialogInterface.OnClickListener() {
// your code here
});
because currently you are passing only index(i) to builder.setItems

Related

Customizing my alertbox using inflater doesn't work

I am a beginner to Android Studio. I am working on my android quiz application for our school activity. The code shown below is what i have to check if my answer in my true or false question is correct. I want to display a custom AlertBox, but it doesn't work.The app stops and goes back its previous activity. I tried to change it to the default alertbox. It works fine, but if I add inflater it doesn't work. What is wrong with my code?
public void checkAnswer(View view) {
// Get pushed button.
Button answerBtn = (Button) findViewById(view.getId());
String btnText = answerBtn.getText().toString();
TextView title = (TextView) view.findViewById(R.id.title);
ImageButton imageButton = (ImageButton)
view.findViewById(R.id.image);
TextView laman = (TextView) view.findViewById(R.id.laman);
if (btnText.equals(rightAnswer)) {
// Correct!
startService(new Intent(roxasquiz.this, tamamusic.class));
imageButton.setImageResource(R.drawable.check);
title.setText("Magaling!");
laman.setText("Tama ang iyong sagot! ");
rightAnswerCount++;
} else {
// Wrong...
startService(new Intent(roxasquiz.this, malimusic.class));
title.setText("Magsanay pa!");
laman.setText("Mali ang iyong sagot! ");
imageButton.setImageResource(R.drawable.wrong);
}
// Create Dialog.
AlertDialog.Builder builder = new AlertDialog.Builder(this);
LayoutInflater inflater = getLayoutInflater();
View v = inflater.inflate(R.layout.custom_layout, (ViewGroup) view, false);
builder.setPositiveButton("OK", new
DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if (quizCount == QUIZ_COUNT) {
// Show Result.
Intent intent = new Intent(getApplicationContext(), roxasresult.class);
intent.putExtra("RIGHT_ANSWER_COUNT", rightAnswerCount);
startActivity(intent);
} else {
quizCount++;
showNextQuiz();
}
}
});
builder.setView(v);
builder.setCancelable(false);
builder.show();
}
Here is the code that is written before the codes above.
public class roxasquiz extends AppCompatActivity {
private TextView timer;
private TextView countLabel;
private TextView questionLabel;
private Button answerBtn1;
private Button answerBtn2;
private String rightAnswer;
private int rightAnswerCount = 0;
private int quizCount = 1;
static final private int QUIZ_COUNT = 3;
ArrayList<ArrayList<String>> quizArray = new ArrayList<>();
String quizData[][] = {
// {"Question", "Right Answer", "Choice1", "Choice2", "Choice3"}
{"Sa loob ng 10 taon naging speaker of the House si Manuel Roxas. ",
"MALI", "TAMA", },
{"Nagtapos ng abogasya si Manuel Roxas sa University of Santo
Tomas.", "MALI", "TAMA",},
{"Sa lalawigan ng Tarlac ipinanganak si Manuel Roxas. ", "MALI",
"TAMA", },
};
#Override
protected void onCreate(Bundle savedInstanceState) {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.rizaltruefalse);
stopService(new Intent(roxasquiz.this, BackgroundSoundService.class));
countLabel = (TextView)findViewById(R.id.countLabel);
questionLabel = (TextView)findViewById(R.id.questionLabel);
answerBtn1 = (Button)findViewById(R.id.answerBtn1);
answerBtn2 = (Button)findViewById(R.id.answerBtn2);
timer = (TextView)findViewById(R.id.timerlabel);
timer = (TextView)findViewById(R.id.timerlabel);
startService(new Intent(roxasquiz.this, timer.class));
new CountDownTimer(61000, 1000) {
public void onTick(long millisUntilFinished) {
timer.setText("Oras:" + millisUntilFinished / 1000);
}
public void onFinish() {
timer.setText("TAPOS NA!");
timeUp();
}
private void timeUp() {
stopService(new Intent(roxasquiz.this, tamamusic.class));
stopService(new Intent(roxasquiz.this, malimusic.class));
AlertDialog.Builder builder = new AlertDialog.Builder(
roxasquiz.this);
builder.setTitle("Tapos na ang oras!")
.setCancelable(false)
.setNeutralButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
Intent intent = new
Intent(getApplicationContext(), roxasresult.class);
intent.putExtra("RIGHT_ANSWER_COUNT",
rightAnswerCount);
startActivity(intent);
}
});
AlertDialog alert = builder.create();
alert.show();
}
}.start();
// Create quizArray from quizData.
for (int i = 0; i < quizData.length; i++) {
// Prepare array.
ArrayList<String> tmpArray = new ArrayList<>();
tmpArray.add(quizData[i][0]); // Country
tmpArray.add(quizData[i][1]); // Right Answer
tmpArray.add(quizData[i][2]); // Choice1
// Add tmpArray to quizArray.
quizArray.add(tmpArray);
}
showNextQuiz();
}
public void showNextQuiz() {
// Update quizCountLabel.
countLabel.setText("Tanong " + quizCount);
// Generate random number between 0 and 14 (quizArray's size - 1).
Random random = new Random();
int randomNum = random.nextInt(quizArray.size());
// Pick one quiz set.
ArrayList<String> quiz = quizArray.get(randomNum);
// Set question and right answer.
// Array format: {"Country", "Right Answer", "Choice1", "Choice2",
"Choice3"}
questionLabel.setText(quiz.get(0));
rightAnswer = quiz.get(1);
// Remove "Country" from quiz and Shuffle choices.
quiz.remove(0);
answerBtn1.setText("TAMA");
answerBtn2.setText("MALI");
quizArray.remove(randomNum);
}
This is my code to make it a default alertbox and it works fine.
Button answerBtn = (Button) findViewById(view.getId());
String btnText = answerBtn.getText().toString();
String alertTitle;
String laman;
if (btnText.equals(rightAnswer)) {
// Correct!
startService(new Intent(roxasquiz.this, tamamusic.class));
alertTitle = "Magaling!";
laman = "Tama ang iyong sagot";
rightAnswerCount++;
} else {
// Wrong...
alertTitle = "Magsanay pa!";
laman = "Mali ang iyong sagot";
}
// Create Dialog.
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(alertTitle);
builder.setMessage(laman);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if (quizCount == QUIZ_COUNT) {
// Show Result.
Intent intent = new Intent(getApplicationContext(), roxasresult.class);
intent.putExtra("RIGHT_ANSWER_COUNT", rightAnswerCount);
startActivity(intent);
} else {
quizCount++;
showNextQuiz();
}
}
});
builder.setCancelable(false);
builder.show();
}
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
LayoutInflater inflater = this.getLayoutInflater();
View dialogView = inflater.inflate(R.layout.alert_label_editor, null);
dialogBuilder.setView(dialogView);
AlertDialog alertDialog = dialogBuilder.create();
alertDialog.show();

Get selected list item in alert dialog with split string

I have string array in strings.xml with the country phone numbers and the country name separated by a comma.
Now I want to show this list in a dialog and show the country phone number of the selected country in an edittext.
The list is shown, I can click an item and a number w/o the country name is shown in the edittext but unfortunately it's always the same value. It looks like I don't get the clicked item but iterate though the complete list and get something back.
Here's the code of the alert dialog:
private void selectCountry() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.choose_country);
final String[] names = getResources().getStringArray(R.array.Countries);
builder.setItems(names, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
String CountryZipCode = "";
for (int i = 0; i < names.length; i++) {
String[] g = names[i].split(",");
CountryZipCode = g[0];
}
countrycode.setText("+" + CountryZipCode);
}
});
AlertDialog alert = builder.create();
alert.show();
}
And here's a snippet of the array list from strings.xml:
<string-array name="Countries" >
<item>93,Afghanistan</item>
<item>355,Albania</item>
<item>213,Algeria</item>
<item>376,Andorra</item>
<item>244,Angola</item>
</string-array>
Thanks a lot in advance!
is it always the last one?
because if i am reading your code correctly thats what you are doing..
shouldn't you be saying:
builder.setItems(names, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
String CountryZipCode = "";
//for (int i = 0; i < names.length; i++) {
String[] g = names[item].split(",");
CountryZipCode = g[0];
//}
countrycode.setText("+" + CountryZipCode);
}
});

listview does not get updated android

I am very new to Android and am trying to create an app for travel help. It has a couple of components including -> enabling the user to customize a checklist. Apart from the default list, items can be added and deleted.
For adding,
I'm using a dynamic layout through the class file with no XML. It works perfectly :)
For deleting an item from the list,
I created an adpater, a listview and am trying to delete the selected item. With the help of a couple of "toasts", I am able to derive that, an item is being deleted from the list, but the view is not getting updated.
I have checked and tried numerous solutions, but none of them seem to be working. I am attching my java file, in which the display and customization of the list takes place.
The code seems a little long, but its fairly easy to understand. Any help would be greatly appreciated! :)
public class Dynamic extends ListActivity{
public String[] A = new String[100];
public String[] B = new String[100];
public int j=0, m=0, b=0, tot1=0, tot2=0;
public int a[]=new int[100];
CheckBox c, cc;
ArrayList<String> list2 = new ArrayList<String>();
ArrayList<String> list4 = new ArrayList<String>();
ArrayAdapter<String> adapter;
ArrayAdapter<String> adapter2;
private SparseBooleanArray sba;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ScrollView sv = new ScrollView(this);
final LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
sv.addView(ll);
final ListView list3=new ListView(this);
list3.setId(android.R.id.list);
list3.setChoiceMode(list3.CHOICE_MODE_MULTIPLE);
ll.addView(list3);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, list2);
Bundle extras = getIntent().getExtras();
if (extras != null) {
A = extras.getStringArray("var");
int i = extras.getInt("var2");
B = extras.getStringArray("var3");
int k = extras.getInt("var4");
for (j=0;j<i;j++)
{
cc = new CheckBox(this);
cc.setText(A[j]);
ll.addView(cc);
list2.add(A[j]);
adapter.notifyDataSetChanged();
}
for (m=0;m<k;m++)
{
cc = new CheckBox(this);
cc.setText(B[m]);
ll.addView(cc);
list2.add(B[m]);
adapter.notifyDataSetChanged();
}
}
Button b = new Button(this);
b.setText("Delete Item");
ll.addView(b);
b.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
AlertDialog.Builder alertDialog = new AlertDialog.Builder(Dynamic.this);
alertDialog.setTitle("Confirm Delete...");
alertDialog.setMessage("Are you sure you want to delete the selected item from the list?");
alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog,int which)
{
sba=new SparseBooleanArray();
sba.clear();
sba=list3.getCheckedItemPositions();
ListView lv = getListView();
Toast.makeText(getApplicationContext(), "checked " + sba, Toast.LENGTH_SHORT).show();
int itemCount = getListView().getCount();
Toast.makeText(getApplicationContext(), "calc done " + itemCount, Toast.LENGTH_SHORT).show();
for(int i=itemCount-1; i >= 0; i--){
Toast.makeText(getApplicationContext(), "in the loop " + i, Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), " " + sba.get(i), Toast.LENGTH_SHORT).show();
list2.add((list2.get(i)));
Toast.makeText(getApplicationContext(), " " + list2.get(i), Toast.LENGTH_SHORT).show();
adapter.remove(list2.get(i));
list3.invalidate();
adapter.notifyDataSetChanged();
list3.setAdapter(adapter);
Toast.makeText(getApplicationContext(), " " + list2, Toast.LENGTH_SHORT).show();
}
sba.clear();
}
});
alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which){
Toast.makeText(getApplicationContext(), "The item has NOT been deleted!", Toast.LENGTH_SHORT).show();
dialog.cancel();
}
});
alertDialog.show();
setListAdapter(adapter);
}
});
this.setContentView(sv);
}
}
in order to update your listView try this in your adampter
notifyDataSetChanged();
But You should run it on the UI thread. Create an handler within the UI thread and then post Runable to it
like this
private class Asyn_SaveData extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
//Do something here that will run in backGround
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
//and this function is called automatically by doInBackground
// after it finish its work
//in your example refresh your ListView
notifyDataSetChanged();
}
}
and to use the AsyncTask
new Asyn_SaveData().execute(null,null,null);
Just remembre AsyncTask must be subClassed
or
myListView.invalidateViews();

cannot access a value from a different class

In my main class i've a button to call a class which shows a dialog box with an edittext. My problem is this - Main activity is not getting edittext value at the first run, if i run it for a second time, i get the old edittext value.
It seems the main activity class executes the full block of code and returns a previous value which is stored in the class, i've tried many methods including shared preference.
MainActivity.java
public class MainActivity extends Activity {
EditText comment_et,input_et;
Spinner spinner;
Button addbutton,reportbut;
String input_string,date,time,comment,item;
TextView date_tv,time_tv;
String temp[];
Datas datatemp;
String savedinput;
ArrayList<String> list = new ArrayList<String>();
ArrayAdapter<String> adapter;
DatabaseHandler db = new DatabaseHandler(this);
#Override
protected void onCreate(Bundle savedInstanceState)
{
SharedPreferences prefs = getSharedPreferences("myprefs", 0);
savedinput= prefs.getString("KEY_SAVEDINPUT","");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner = (Spinner)findViewById(R.id.spin1);
input_et = (EditText)findViewById(R.id.input_et);
addbutton = (Button)findViewById(R.id.addbutton);
reportbut = (Button)findViewById(R.id.report);
comment_et = (EditText)findViewById(R.id.comment_et);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list);
date_tv = (TextView)findViewById(R.id.date_tv);
time_tv = (TextView)findViewById(R.id.time_tv);
final Calendar c = Calendar.getInstance();
int mYear = c.get(Calendar.YEAR);
int mMonth = c.get(Calendar.MONTH);
int mDay = c.get(Calendar.DAY_OF_MONTH);
int mHour = c.get(Calendar.HOUR_OF_DAY);
int mMinute = c.get(Calendar.MINUTE);
date = ""+mDay+"/"+mMonth+1+"/"+mYear;
time = ""+mHour+":"+mMinute;
date_tv.setText(date);
time_tv.setText(time);
int max_id = db.getDatasCount();
for(int i = 1; i<max_id+1 ;i++)
{
datatemp = db.getItemOnly(i);
String s = datatemp._item.toString();
list.add(" "+ s);
}
addbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialogManager alert = new AlertDialogManager();
alert.showAlertDialog(MainActivity.this, "Enter Item",
"Please enter the spinner item",
true);
System.out.println("main : " +savedinput);
}
});
reportbut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), ListviewActivity.class);
startActivity(i);
}
});
spinner.setAdapter(adapter);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
item = parent.getItemAtPosition(position).toString();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
Button submit = (Button)findViewById(R.id.save);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
comment = comment_et.getText().toString();
System.out.println("comment:"+comment);
/**
* CRUD Operations
* */
// Inserting Contacts
Log.d("Insert: ", "Inserting ..");
db.addData(new Datas(item, comment, date, time));
Toast.makeText(getApplicationContext(), "Data Submitted Successfully",
Toast.LENGTH_LONG).show();
// Reading all contacts
Log.d("Reading: ", "Reading all contacts..");
List<Datas> datas = db.getAllDatas();
for (Datas d : datas) {
String log = "Id: "+d.getID()+" ,Item: " + d.getItem() + " ,Comment: " + d.getComment() + " ,Date: " + d.getDate() + ",Comment: " + d.getTime();
// Writing Contacts to log
Log.d("Item: ", log);
}
}
});
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
AlertDialogManager.java
public class AlertDialogManager {
/**
* Function to display simple Alert Dialog
* #param context - application context
* #param title - alert dialog title
* #param message - alert message
* #param status - success/failure (used to set icon)
* - pass null if you don't want icon
* */
String savedinput;
public void showAlertDialog(final Context context, String title, String message,
Boolean status)
{
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
// Setting Dialog Title
alertDialog.setTitle(title);
// Setting Dialog Message
alertDialog.setMessage(message);
//setting input
final EditText input = new EditText(context);
alertDialog.setView(input);
// saving input to a string
savedinput = input.getText().toString();
System.out.println(savedinput);
if(status != null)
// Setting alert dialog icon
alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
savedinput = input.getText().toString();
SharedPreferences prefs = context.getSharedPreferences("myprefs", 0);
SharedPreferences.Editor editor =prefs.edit();
editor.putString("KEY_SAVEDINPUT", savedinput);
editor.commit();
System.out.println("from class "+savedinput);
}
});
// Showing Alert Message
alertDialog.show();
}
String getItem()
{
return savedinput;
}
}
and here is my logcat, just for further clarification
02-01 13:48:43.372: I/System.out(897): main : firstexecute
02-01 13:48:46.942: W/KeyCharacterMap(897): No keyboard for id 0
02-01 13:48:46.942: W/KeyCharacterMap(897): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
02-01 13:48:49.532: I/System.out(897): from class secondexecute
You have several issues here.
You shouldn't read savedValue in onCreate, you should do it only when you actually use it. See #ρяσѕρєяK answer.
alert.showAlertDialog is non blocking. So after dialog is shown line System.out.println("main : " + savedInput); is executed. It doesn't wait for your input. So you should call some other action beside saving to shared preferences on dialog's ok buttonn. This action should invoke logic that should happen after user entered some text in the dialog.
Update
public void showAlertDialog(final Context context, String title, String message,
Boolean status, final Spinner spinner)
{
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
// Setting Dialog Title
alertDialog.setTitle(title);
// Setting Dialog Message
alertDialog.setMessage(message);
//setting input
final EditText input = new EditText(context);
alertDialog.setView(input);
// saving input to a string
savedinput = input.getText().toString();
System.out.println(savedinput);
if(status != null)
// Setting alert dialog icon
alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
savedinput = input.getText().toString();
// do whatever you want with spinner and savedInput here.
}
});
// Showing Alert Message
alertDialog.show();
}
onClick to show dialog:
alert.showAlertDialog(MainActivity.this, "Enter Item",
"Please enter the spinner item",
true, (Spinner) findViewById(R.id.spin1));
Update 2
Apparently you need to add new item to your spinner adapter. For this you can create list of all items and pass this list along with adapter to dialog. When user enters string and press OK button onClick method adds this string to the list and call notifyDataSetChanged to update UI:
Add this in MainActivity:
List<String> spinnerItems;
In onCreate:
spinnerItems = new ArrayList<String>();
adapter = enw ArrayAdapter<String>(this, 0, spinnerItems);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
Pass spinnerItems and adapter to showAlertDialog:
alert.showAlertDialog(MainActivity.this, "Enter Item",
"Please enter the spinner item",
true, spinnerItems, adapter);
And finally add text to list and notify adapter:
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
savedinput = input.getText().toString();
spinnerItems.add(savedInput);
adapter.notifyDataSetChanged();
}
});
you will need get latest value on Button click instead of onCreate to get latest value from SharedPreferences as :
addbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialogManager alert = new AlertDialogManager();
alert.showAlertDialog(MainActivity.this, "Enter Item",
"Please enter the spinner item",
true);
savedinput= prefs.getString("KEY_SAVEDINPUT",""); //<<< get value here
System.out.println("main : " +savedinput);
}
});
or you will try to get value from onResume of Activity
This
savedinput = input.getText().toString();
is evaluated when it is run. Not when you call getItem(). The value you'll get is what it was, in this case, before the alert was displayed.
same logic goes for
savedinput= prefs.getString("KEY_SAVEDINPUT","");

Compare text in EditText with defined String?

i'm new with Android and i'm writing a simple alarm clock application.when i type the string into the EditText like this "10:00,Monday" this string will compare syntax with the defined string if true it'll turn on the AlarmClock. But i don't know how to compare. May you give me an idea? Thanks so much. My app's interface and code below
1.My app's interface https://dl.dropbox.com/u/40382482/Screenshot%20from%202012-10-25%2023%3A51%3A14.png
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/* Calendar cal = Calendar.getInstance();
SimpleDateFormat date = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat time = new SimpleDateFormat("hh:mm:ss");
final TextView labelDate = (TextView) findViewById(R.id.lblDate);
final TextView lableTime = (TextView) findViewById(R.id.lblTime);
labelDate.setText(date.format(cal.getTime()));
lableTime.setText(time.format(cal.getTime()));*/
final ArrayList<String> setAlarm = new ArrayList<String>();
//nhap noi dung vao edit text
final EditText alarmEnter = (EditText) findViewById(R.id.setting);
final Button button = (Button) findViewById(R.id.Okay);
OnClickListener add = new OnClickListener()
{
public void onClick(View v)
{
if(alarmEnter.getText().toString().equals(""))
{
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Info Missing");
builder.setMessage("Please Enter All Information");
builder.setPositiveButton("Continue", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface diablog, int which)
{
}
}
); builder.show();
}
else {
//compare string in EditText and defined string?
}
}
};
button.setOnClickListener(add);
}
To compare one string with another, use:
if(strText.equals("myString")){ // strText is the string from the edit text, myString is the string
// you are comparing it to
// do something
}else{
// do something else
}
This will return a boolean.
if (myEditText.getText().toString().equals(myString)) { ... }

Categories

Resources