cannot access a value from a different class - android

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","");

Related

Unable to add Window, Token is not valid error when clicked on a Spinner

I have an android application when clicked on an option from a side bar it goes to a fragment, and then into another fragment which has clickable radio buttons. When clicked on these it will create a popup window with some text fields in it.
Basically this is how the flow goes,
Activity --> Fragment 1 --> Fragment 2 --> PopupWindow
And i have a spinner on this PopupWindow, but when i click on it to select a value it throws the following exception. I don't understand why this happen.
Process: com.informaticsint.claimassistant, PID: 5045
android.view.WindowManager$BadTokenException: Unable to add window -- token android.view.ViewRootImpl$W#945936c is not valid; is your activity running?
at android.view.ViewRootImpl.setView(ViewRootImpl.java:849)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:337)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
at android.widget.PopupWindow.invokePopup(PopupWindow.java:1329)
at android.widget.PopupWindow.showAsDropDown(PopupWindow.java:1155)
at android.widget.ListPopupWindow.show(ListPopupWindow.java:791)
at android.widget.Spinner$DropdownPopup.show(Spinner.java:1366)
at android.widget.Spinner.performClick(Spinner.java:828)
at android.view.View$PerformClick.run(View.java:22526)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7224)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
This is the Spinner code that cause the problem. Which is in the below mentioned AssignmentDetailsActivity class, showDamagedItemEntryPopup() method
statusSpinner = (Spinner)popupView.findViewById(R.id.popup_status_spinner);
ArrayAdapter<String> statusSpinnerArrayAdapter = new ArrayAdapter<String>(AssignmentDetailsActivity.this, android.R.layout.simple_spinner_item, statusSpinnerArray);
statusSpinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
statusSpinner.setAdapter(statusSpinnerArrayAdapter);
This is my method that creates the popup which is in my AssignmentDetailsActivity class
public void showDamagedItemEntryPopup(RadioButton radioButton, View view){
LayoutInflater layoutInflater = (LayoutInflater)getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View popupView = layoutInflater.inflate(R.layout.component_selection_popup, null);
final PopupWindow popupWindow = new PopupWindow(
popupView,
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
// Set popup Animation style
popupWindow.setAnimationStyle(R.style.popupAnimation);
Button buttonClose = (Button)popupView.findViewById(R.id.close_add_component_btn);
// Close button damaged item popop window
buttonClose.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v) {
popupWindow.dismiss();
}
});
originalAmount = (EditText)popupView.findViewById(R.id.popup_add_component_original_amount);
customerContribution = (EditText)popupView.findViewById(R.id.popup_percentage);
quantity = (EditText)popupView.findViewById(R.id.popup_quantity);
finalAmount = (EditText)popupView.findViewById(R.id.popup_add_component_final_amount);
remarks = (EditText)popupView.findViewById(R.id.popup_add_component_remarks);
// Item Spinner
itemSpinnerArray = new ArrayList<String>();
itemSpinnerArray.add("Select Item");
// Status Spinner
ArrayList<String> statusSpinnerArray = new ArrayList<String>();
statusSpinnerArray.add("FDR");
statusSpinnerArray.add("DR");
statusSpinnerArray.add("SP");
damageComponenetAutoCompleteTextview = (AutoCompleteTextView) popupView.findViewById(R.id.popup_damage_component_item);
damageComponenetAutoCompleteTextview.requestFocus();
ArrayAdapter<String> itemSpinnerArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, itemSpinnerArray);
damageComponenetAutoCompleteTextview.setThreshold(1);
damageComponenetAutoCompleteTextview.setAdapter(itemSpinnerArrayAdapter);
damageComponenetAutoCompleteTextview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
itemSpinnerValue = (String) parent.getItemAtPosition(position);
Log.d("SK-->", "----------------------------------------------------------");
Log.d("SK-->","itemSpinnerValue: " + itemSpinnerValue);
}
});
statusSpinner = (Spinner)popupView.findViewById(R.id.popup_status_spinner);
ArrayAdapter<String> statusSpinnerArrayAdapter = new ArrayAdapter<String>(AssignmentDetailsActivity.this, android.R.layout.simple_spinner_item, statusSpinnerArray);
statusSpinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
statusSpinner.setAdapter(statusSpinnerArrayAdapter);
//Creating a text Watcher
TextWatcher textWatcher = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void afterTextChanged(Editable editable) {
//here, after we introduced something in the EditText we get the string from it
//String answerString = originalAmount.getText().toString();
if (originalAmount.getText().toString().trim().equals("") || customerContribution.getText().toString().trim().equals("")
|| quantity.getText().toString().trim().equals("")) {
// Error , one or more editText are empty
}
else
{
calculateFinalAmount();
}
//and now we make a Toast
//modify "yourActivity.this" with your activity name .this
//Toast.makeText(yourActivity.this,"The string from EditText is: "+answerString,0).show();
}
};
// Adding Text Watcher to our text boxes
originalAmount.addTextChangedListener(textWatcher);
customerContribution.addTextChangedListener(textWatcher);
quantity.addTextChangedListener(textWatcher);
// Show the popup
popupWindow.showAtLocation(view, Gravity.CENTER, 0, 0);
}
public void onSaveItem(View view) {
statusSpinnerValue = (String) statusSpinner.getItemAtPosition(statusSpinner.getSelectedItemPosition());
statusSpinnerValue = "ABC";
itemSpinnerValue = "TEST ITEM";
originalAmount.setText("50");
customerContribution.setText("25");
quantity.setText("1");
if(itemSpinnerValue.matches("Select Item") ||itemSpinnerValue.matches("") || statusSpinnerValue.matches("") || originalAmount.getText().toString().matches("") || customerContribution.getText().toString().matches("") ||
quantity.getText().toString().matches("")){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("ERROR!");
builder.setMessage("Please Fill the Required Fields.")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//do things
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
}
else{
Log.e("TEST", "Check Passed");
Date date = new Date();
if(mDbHandler.itemAlreadyExist(reportID,"item_name", itemSpinnerValue, "DamageComponent") == false){
mDbHandler.addDamageComponent(reportID, itemSpinnerValue, statusSpinnerValue, originalAmount.getText().toString(), Double.parseDouble(customerContribution.getText().toString()),
Integer.parseInt(quantity.getText().toString()), finalAmount.getText().toString(), remarks.getText().toString());
mDbHandler.updateReport(reportID, date.toString(), "time_last_modified");
Toast.makeText(this,"Component Successfully Added",Toast.LENGTH_SHORT).show();
}
else{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("ERROR!");
builder.setMessage("Item Already Exist.")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//do things
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
}
mDbHandler.close();
}
}
Spent 2 days for exactly the same problem :(
The only workaround I find is to use spinner in dialog mode
android:spinnerMode="dialog"
Glad to help you again, Have a look at this question's answers. You are showing popup too early so that you need to delay the run like this
view.post(new Runnable() {
public void run() {
popupWindow.showAtLocation(view, Gravity.CENTER, 0, 0);
}
});
UPDATE :
OR try
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
#Override
public void run() {
popupWindow.showAtLocation(view, Gravity.CENTER, 0, 0);
}
}, 1000); //Delay one second

How to add a pop up/Dialog box and pass information back to the class in Android

I am trying to create a pop-up dialog to allow the user of my android app to add a new field to a list on their main page.
I've done a bit of research and found the Dialog/alertDialog option, but i haven't been able to get it working correctly.
Here is my MainActivity class:
public class MainActivity extends Activity {
private ListView listView;
public static ArrayList<String> ArrayofName = new ArrayList<String>();
//final Dialog dialog = new Dialog(this); //!!! ERROR HERE !!! //
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DatabaseHandler db = new DatabaseHandler(this);
Button AddNewStudent = (Button) findViewById(R.id.AddNew);
/**
* CRUD Operations
* */
// Inserting Contacts
Log.d("Insert: ", "Inserting ..");
//db.addStudentProfile(new StudentProfile("Shannon", "White"));
//db.addStudentProfile(new StudentProfile(1,"Shannon", "White", "WhitehousePS", "30", "21" ));
/*AddNewStudent.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// Using an alertDialog to get the user to enter in a new Student
dialog.setContentView(R.layout.add_new_student);
dialog.setTitle("Add a new student");
final EditText firstName=(EditText)dialog.findViewById(R.id.firstName);
final EditText surname=(EditText)dialog.findViewById(R.id.surname);
final EditText school=(EditText)dialog.findViewById(R.id.school);
final EditText age=(EditText)dialog.findViewById(R.id.age);
Button save=(Button)dialog.findViewById(R.id.save);
Button btnCancel=(Button)dialog.findViewById(R.id.cancel);
dialog.show();
}
});*/
// Reading all contacts
Log.d("Reading: ", "Reading all contacts..");
List<StudentProfile> contacts = db.getAllStudents();
for (StudentProfile studProf : contacts) {
String log = "Id: "+studProf.getID()+" , First name: " + studProf.getFirstName() + ", Surname: " + studProf.getSurname() + ", School: " + studProf.getSchool() +
", Reading Level: "+ studProf.getReadingLevel() + ", Age: " + studProf.getAge();
// Writing Contacts to log
Log.d("Name: ", log);
}
db.getAllStudents();
listView = (ListView) findViewById(R.id.listView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, ArrayofName);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Toast.makeText(getApplicationContext(),
((TextView) v).getText(), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Get the layout inflater
LayoutInflater inflater = getActivity().getLayoutInflater();
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
builder.setView(inflater.inflate(R.layout.dialog_signin, null))
// Add action buttons
.setPositiveButton(R.string.signin, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// sign in the user ...
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
LoginDialogFragment.this.getDialog().cancel();
}
});
return builder.create();
}
}
It's linked to a very simple xml page that just has editible text fields.
My application won't even open with this code - i have tracked the issue down to this line:
final Dialog dialog = new Dialog(this);
at the top of my program.
IS this the best way to go about making a pop up dialog?
Also, what is the easiest way to pass the information back to the class to be stored in a database?
Any help would be much appreciated, thanks! :)
You can create some private variables at the top of your class, and get the text from the editText and put it into those variables in the dialog's button click handler method (where you have the 'sign in the user' comment.)
Sometimes it's also easyer to crate a dialog themed activity.

EditText getText() returns empty string

I have an activity with a button, when the user clicks on the button, an AlertDialog appear with 2 EditText where you put email and password to login.
When I try to get the text from the EditText i always get only empty strings.
The layout login_alert is the layout of the AlertDialog.
Here the code:
View view = getLayoutInflater().inflate(R.layout.login_alert, null, false);
String email = ((EditText) view.findViewById(R.id.emailEditText)).getText().toString();
String password = ((EditText) view.findViewById(R.id.passwordEditText)).getText().toString();
System.out.println("DEBUG: "+email+", "+password); // Empty strings
EDIT:
Activity code:
public class MainActivity extends FragmentActivity {
public static final String mAPP_ID = "...";
public static final String USER_DB_URL = "...";
AssetsExtracter mTask;
private MainFragment mainFragment;
private List<User> usersList = new ArrayList<User>();
private User currentUser = null;
private Button labLoginButton;
private EditText emailET;
private EditText passwordET;
private ProgressDialog dialog;
private View alertView; /* THIS IS THE SOLUTION */
boolean userIsLogged = false;
static {
IMetaioSDKAndroid.loadNativeLibs();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_main);
/*View view = getLayoutInflater().inflate(R.layout.login_alert, null, false); BEFORE*/
alertView = getLayoutInflater().inflate(R.layout.login_alert, null, false);
emailET = (EditText) view.findViewById(R.id.emailEditText);
passwordET = (EditText) view.findViewById(R.id.passwordEditText);
labLoginButton = (Button) findViewById(R.id.loginLabButton);
updateLoginButton();
dialog = new ProgressDialog(this);
dialog.setMessage("Signin in...");
if (savedInstanceState == null) {
// Add the fragment on initial activity setup
mainFragment = new MainFragment();
getSupportFragmentManager().beginTransaction()
.add(android.R.id.content, mainFragment).commit();
} else {
// Or set the fragment from restored state info
mainFragment = (MainFragment) getSupportFragmentManager()
.findFragmentById(android.R.id.content);
}
mTask = new AssetsExtracter();
mTask.execute(0);
}
/* THIS METHOD IS CALLED BY THE LOGIN BUTTON IN THE MAIN ACTIVITY LAYOUT */
public void onLabLoginButtonClick(View v) {
if (userIsLogged) {
currentUser = null;
userIsLogged = false;
updateLoginButton();
Toast.makeText(this, "Disconnected from Lab", Toast.LENGTH_SHORT)
.show();
} else {
/*View messageView = getLayoutInflater().inflate(
R.layout.login_alert, null, false); BEFORE */
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setIcon(R.drawable.icon_launcher);
builder.setTitle(R.string.login_string);
builder.setView(alertView); /* USING THE GLOBAL VARIABLE */
builder.setPositiveButton("Sign me", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface d, int which) {
dialog.show();
// Download user and return a List of User
DownloadFilesAsyncTask task = new DownloadFilesAsyncTask(USER_DB_URL) {
#Override
protected void onPostExecute(final List<User> result) {
usersList = result;
loginCheckRoutine(); //HERE I MANAGE THE LOGIN AND GETTING EMPTY STRING
}
};
task.execute();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
builder.create();
builder.show();
}
}
public void updateLoginButton() {
if (userIsLogged) {
labLoginButton.setText(R.string.logout_string);
} else {
labLoginButton.setText(R.string.login_string);
}
}
public void loginCheckRoutine() {
String email = emailET.getText().toString();
String password = passwordET.getText().toString();
System.out.println("DEBUG: " + email + ", " + password); // EMPTY
// controllo nella lista se c'è l'utente coi dati inseriti
for (int i = 0; i < usersList.size(); i++) {
if (usersList.get(i).getEmail().equals(email)
&& password.equals("admin")) {
currentUser = usersList.get(i);
userIsLogged = true;
updateLoginButton();
dialog.dismiss();
break;
}
}
if (!userIsLogged) {
userIsLogged = false;
updateLoginButton();
dialog.dismiss();
Toast.makeText(MainActivity.this, "Login Failed",
Toast.LENGTH_SHORT).show();
}
}
}
PROBLEM SOLVED, SOLUTION:
In the onCreate() I inflate the alert_dialog layout in a View variable. I made that View variable global (before onCreate()) and then in onLabLoginButtonClick() I don't inflate the view again, but I use that global instantiated in the onCreate(). hope its clear. thank you all!
You getText just after initialization. Untill you have text in xml you won't get the text. In onclick of alertdialog button get the text.
Declare
EdiText ed1,ed2; // before onCreate if in activity and onCraeteView in fragment
as a instance variable
View view = getLayoutInflater().inflate(R.layout.login_alert, null, false);
ed1= (EditText) view.findViewById(R.id.emailEditText))
ed2 = (EditText) view.findViewById(R.id.emailEditText);
then on Alert dialog Button click
String email = ed1.getText().toString();
String password= ed2.getText().toString()
you must get the text when you click on login button of alert dialog box
the above mentioned code you get text when you show alert dialog it always return always empty string you should follow the following procedure
first you make a custom alert box layout having two edit text and one button
user write text to edittext for login and give password and then click login button
when you call login button click listener you can get text of edittext easyly
You are trying to get the text immediately after you inflated the view. Try doing it when the user clicks the done button instead.
Before onCreate add:
EditText email;
EditText pass;
Add this in your onCreate
etEmail (EditText) view.findViewById(R.id.emailEditText);
etPass (EditText) view.findViewById(R.id.emailEditText);
Then add this to when your button is clicked
String email = etEmail.getText().toString();
String pass = etEmail.getText().toString();
Just ensure that the editText.getText.toString() method is inside the OnClick() method, eg:
TextView submit = enquiryFragment.findViewById(R.id.query_submit_button);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
query_type = query_type_editText.getText().toString();
query_text = query_editText.getText().toString();
if (query_text.length()!=0 && query_type.length()!=0) {
postQuery(query_type, query_text, store_id);
// Log.e("query_type ",query_type );
}else{
Toast.makeText(getContext(), "Enter something !", Toast.LENGTH_SHORT).show();
}
}
});
Alternatively add a TextChangedListener to you textview to change the change the string every time the textboxtext changes.
A textwatcher is also possible
you should get the text when you click on save or done button.
If you get this text on click of alert dialog button, you may end up taking it multiple times.

Retaining items in a List View

I'm new to android development having some problems. I created a list view that is based on the user input. User has to enter a category in a dialog box and then it's added into the list. Works like a charm. The question is how do I retain those categories once the user exits from an app and starts it again ? When the user starts the app, the list is blank. Do I have to create a preference screen or something to save what the user types ? Here is my code:
public class MainActivity extends Activity {
final Context context = this;
ArrayAdapter<String> arrayAdapter;
ArrayList<String> listItems = new ArrayList<String>();
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lv = (ListView)findViewById(R.id.listView1);
arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, listItems);
lv.setAdapter(arrayAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case R.id.menu_add_cat:
LayoutInflater li = LayoutInflater.from(context);
View promptAdd = li.inflate(R.layout.prompt_add, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
//set prompts.xml to alertDialogBuilder
alertDialogBuilder.setView(promptAdd);
final EditText etAddCat = (EditText)promptAdd.findViewById(R.id.etDialogInput);
//set a dialog message
alertDialogBuilder.setPositiveButton("Done", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
/*
* add a cat here
*/
String input = etAddCat.getText().toString();
if(null != input && input.length() > 0){
listItems.add(input);
arrayAdapter.notifyDataSetChanged();
}else{
Toast.makeText(getApplicationContext(), "Please enter a new category", Toast.LENGTH_LONG).show();
}
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
break;
}
//return super.onOptionsItemSelected(item);
return true;
}
}// end of MainActivity
You can save it in SQLite DB, use CursorAdapter for your list view.
If the amount of data you want to save is relatively small you can use SharedPreferences to save the String data in your onClick method.
#Override
public void onClick(DialogInterface dialog, int which) {
String input = etAddCat.getText().toString();
if(null != input && input.length() > 0){
listItems.add(input);
// Add all string data to List<String> listItem
listItem.add(input);
arrayAdapter.notifyDataSetChanged();
}else{
Toast.makeText(getApplicationContext(), "Please enter a new category", Toast.LENGTH_LONG).show();
}
}
When the user leaves your activity, use the onStop() callback method to save your List<Strings> and store it through SharedPreferences.
#Override
private void onStop() {
super.onStop();
SharedPreferences.Editor editor = mSharedPreferences.edit();
editor.putString(getResources().getString(R.string.list_of_strings), new HashSet<String>(listItem));
editor.commit;
}
Using the onStart() callback, initialize your List and SharedPreferences. When the user navigates to your activity, your list will be reinitialized when it was saved via onStop().
Finally, iterate through your list, add your items to your ArrayList', create yourArrayAdapter` and set it to your list.
#Override
private onStart(){
super.onStart();
SharedPreferences mSharedPreferences;
mSharedPreferences = this.getApplicationContext().getSharedPreferences("MyPreferences", 0);
List<String> listItems = new ArrayList<String>(mSharedPreferences.getStringSet("ListOfStrings", null));
ListIterator li = listItem.listIterator(0);
while (li.hasNext()) {
newStatusList.add((String)li.next());
}
arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, listItems);
lv.setAdapter(arrayAdapter);
}

Using smsmanagaer is not working in alertbox

smsmanager is not working,its not showing any error also,it function is not working at all,dialog dismiss only working.
Mainactivity.java
public class MainActivity extends Activity implements FetchDataListener,OnClickListener
{
private static final int ACTIVITY_CREATE=0;
private ProgressDialog dialog;
ListView lv;
private List items;
private Button btnGetSelected;
//private ProjectsDbAdapter mDbHelper;
//private SimpleCursorAdapter dataAdapter;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_item);
//mDbHelper = new ProjectsDbAdapter(this);
//mDbHelper.open();
//fillData();
//registerForContextMenu(getListView());
lv =(ListView)findViewById(R.id.list);
btnGetSelected = (Button) findViewById(R.id.btnget);
btnGetSelected.setOnClickListener(this);
initView();
}
private void initView()
{
// show progress dialog
dialog = ProgressDialog.show(this, "", "Loading...");
String url = "http://dry-brushlands-3645.herokuapp.com/posts.json";
FetchDataTask task = new FetchDataTask(this);
task.execute(url);
//mDbHelper.open();
//Cursor projectsCursor = mDbHelper.fetchAllProjects();
//startManagingCursor(projectsCursor);
// Create an array to specify the fields we want to display in the list (only TITLE)
//String[] from = new String[]{ProjectsDbAdapter.KEY_TITLE};
// and an array of the fields we want to bind those fields to (in this case just text1)
//int[] to = new int[]{R.id.text1};
/* Now create a simple cursor adapter and set it to display
SimpleCursorAdapter projects =
new SimpleCursorAdapter(this, R.layout.activity_row, projectsCursor, from, to);
setListAdapter(projects);
*/
// create the adapter using the cursor pointing to the desired data
//as well as the layout information
/*dataAdapter = new SimpleCursorAdapter(
this, R.layout.activity_row,
projectsCursor,
from,
to,
0);
setListAdapter(dataAdapter);
*/
}
#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);
super.onCreateOptionsMenu(menu);
MenuInflater mi = getMenuInflater();
mi.inflate(R.menu.activity_main, menu);
return true;
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
createProject();
return super.onMenuItemSelected(featureId, item);
}
private void createProject() {
Intent i = new Intent(this, ProjectEditActivity.class);
startActivityForResult(i, ACTIVITY_CREATE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
initView();
}
#Override
public void onFetchComplete(List<Application> data)
{
this.items = data;
// dismiss the progress dialog
if ( dialog != null )
dialog.dismiss();
// create new adapter
ApplicationAdapter adapter = new ApplicationAdapter(this, data);
// set the adapter to list
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
CheckBox chk = (CheckBox) view.findViewById(R.id.checkbox);
Application bean = items.get(position);
if (bean.isSelected()) {
bean.setSelected(false);
chk.setChecked(false);
} else {
bean.setSelected(true);
chk.setChecked(true);
}
}
});
}
// Toast is here...
private void showToast(String msg) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
#Override
public void onFetchFailure(String msg)
{
// dismiss the progress dialog
if ( dialog != null )
dialog.dismiss();
// show failure message
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}
#Override
public void onClick(View v) {
StringBuffer sb = new StringBuffer();
// Retrive Data from list
for (Application bean : items) {
if (bean.isSelected()) {
sb.append(Html.fromHtml(bean.getContent()));
sb.append(",");
}
}
showAlertView(sb.toString().trim());
}
#SuppressWarnings("deprecation")
private void showAlertView(String str) {
AlertDialog alert = new AlertDialog.Builder(this).create();
if (TextUtils.isEmpty(str)) {
alert.setTitle("Not Selected");
alert.setMessage("No One is Seleceted!!!");
} else {
// Remove , end of the name
String strContactList = str.substring(0, str.length() - 1);
alert.setTitle("Selected");
alert.setMessage(strContactList);
}
alert.setButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//sendSMS();
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage("phoneNo", null, "sms message", null, null);
dialog.dismiss();
}
});
In my code i am using sms manager for sending sms which are the thing getting from my listview,it has to send sms,but after clicking the ok button,nothing is work, dialog dismiss only working,not sms manager is not working.
smsManager.sendTextMessage("phoneNo", null, "sms message", null, null);
"phoneNo" in this place specify the number for which you want to send sms
ok what is that selected data does that contain the phone numbers or the some text data that needs to be sent as a message. see "phoneNo" is string what you are passing. In your phone in place of number if you type phoneNo how will it send to which number will it send. that 1st parameter is the phone number to which you want to send sms. if you are selecting the phone number from the list get that to a variable and put that variable in place of "phoneNo"
if you want to enter the number when the alert is shown then here is the code
private void showAlertView(String str) {
final EditText input = new EditText(YOURACTIVITYNAME.this);
AlertDialog alert = new AlertDialog.Builder(YOURACTIVITYNAME.this)
if (TextUtils.isEmpty(str)) {
alert.setTitle("Not Selected");
alert.setMessage("No One is Seleceted!!!");
} else {
// Remove , end of the name
String strContactList = str.substring(0, str.length() - 1);
alert.setTitle("Selected");
alert.setMessage(strContactList);
}
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
String value;
#Override
public void onClick(DialogInterface dialog, int which) {
//sendSMS();
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(input.getText().toString(), null, "sms message", null, null);
dialog.dismiss();
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Do nothing.
}
}).show();

Categories

Resources