Hi I am creating a task reminder app. It works but I would like to create some sort of Toast validation. For example a user doesn't fill in the title and I'd like an toast saying "title needs to be filled in!" e.t.c
But I'm not sure how to do this.
I am using an EditText widget by the way.
This is one method:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDbHelper = new RemindersDbAdapter(this);
setContentView(R.layout.reminder_edit);
mCalendar = Calendar.getInstance();
mTitleText = (EditText) findViewById(R.id.title);
mBodyText = (EditText) findViewById(R.id.body);
mDateButton = (Button) findViewById(R.id.reminder_date);
mTimeButton = (Button) findViewById(R.id.reminder_time);
mConfirmButton = (Button) findViewById(R.id.confirm);
mRowId = savedInstanceState != null ? savedInstanceState.getLong(RemindersDbAdapter.KEY_ROWID)
: null;
registerButtonListenersAndSetDefaultText();
}
and another:
private void saveState() {
String title = mTitleText.getText().toString();
String body = mBodyText.getText().toString();
SimpleDateFormat dateTimeFormat = new SimpleDateFormat(DATE_TIME_FORMAT);
String reminderDateTime = dateTimeFormat.format(mCalendar.getTime());
if (mRowId == null) {
long id = mDbHelper.createReminder(title, body, reminderDateTime);
if (id > 0) {
mRowId = id;
}
} else {
mDbHelper.updateReminder(mRowId, title, body, reminderDateTime);
}
new ReminderManager(this).setReminder(mRowId, mCalendar);
}
Thanks.
You should check inside your submit button's click listener whether all the necessary fields are filled in properly, and if not, just show up the toast:
Toast.makeText(getApplicationContext(), "Title needs to be filled in!",
Toast.LENGTH_SHORT).show();
Related
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.
I am trying to receive an integer in url.
This how i pass value from one activity to another:
private void displayCategoriesInformation(CategoriesModel categoriesModel) {
//get references to your views
TextView tvCategoryId = (TextView) findViewById(R.id.tvCategoryId);
final int categoryId = categoriesModel.getId();
//set values from your categoriesModel java object to textView
tvCategoryId.setText("Id : " + categoriesModel.getId());
okButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Categories.this, SubCategories.class);
intent.putExtra("parameter_name", categoryId);
startActivity(intent);
}
});
}
in SubCategory.class i receive it like this
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.row_subcategory);
Intent intent = getIntent();
int recivedId = intent.getIntExtra("parameter_name", 2);
TextView tvRecivedId = (TextView) findViewById(R.id.tvRecivedId);
tvRecivedId.setText("recivedId" + recivedId);
dialog = new ProgressDialog(this);
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.setMessage("Loading, please wait.....");
spinnerFood = (Spinner) findViewById(R.id.spinFood);
okButton = (Button) findViewById(R.id.bOk);
// spinner item select listener
spinnerFood.setOnItemSelectedListener(this);
new JSONTask().execute("http://146.185.178.83/resttest/subCategories");
}
now the value is stored in the variable recivedId which is 1 or 2 or 3 or 4
what i want to do is execute this JSONTask url like this
new JSONTask().execute("http://146.185.178.83/resttest/categories/recivedId/subCategories");
so the end url would look like this http://146.185.178.83/resttest/categories/1/subcategories/
how can i achieve this
String url = "http://146.185.178.83/resttest/categories/" + recivedId +"/subcategories/";
new JSONTask().execute(url);
I'm doing a register and login and I want it to add more things into the database. Such as first name, Last name, email, username, and password. Here's my code for my register.java:
public class Register extends Activity {
private Button bRR;
EditText etFN, etLN, etEmail, etUN, etPW, etRPW;
Spinner SMonth, SDay, SYaer;
TextView TVterms;
ArrayAdapter<CharSequence> adapter;
ProgressDialog PD;
String url = "http://10.0.0.12/accounts_java.php";
String fname , lname , uname , email , pass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
initTypeface();
//Button's go here
bRR = (Button)findViewById(R.id.bRR);
bRR = (Button)findViewById(R.id.bRR);
bRR.setTypeface(Typeface.createFromAsset(getAssets(), "fonts/SinkinSans-300Light.otf"));
//EditText's go here
etFN = (EditText)findViewById(R.id.etFN);
etLN = (EditText)findViewById(R.id.etLN);
etEmail = (EditText)findViewById(R.id.etEmail);
etUN = (EditText)findViewById(R.id.etUN);
etPW = (EditText)findViewById(R.id.etPW);
etRPW = (EditText)findViewById(R.id.etRPW);
//Spinner's go here
SMonth = (Spinner)findViewById(R.id.SMonth);
SDay = (Spinner)findViewById(R.id.SDay);
SYaer = (Spinner)findViewById(R.id.SYear);
SMonth = (Spinner)findViewById(R.id.SMonth);
adapter = ArrayAdapter.createFromResource(this, R.array.Month, R.layout.support_simple_spinner_dropdown_item);
adapter.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item);
SMonth.setAdapter(adapter);
SDay = (Spinner)findViewById(R.id.SDay);
adapter = ArrayAdapter.createFromResource(this, R.array.Day, R.layout.support_simple_spinner_dropdown_item);
adapter.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item);
SDay.setAdapter(adapter);
SYaer = (Spinner)findViewById(R.id.SYear);
adapter = ArrayAdapter.createFromResource(this, R.array.Year, R.layout.support_simple_spinner_dropdown_item);
adapter.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item);
SYaer.setAdapter(adapter);
//TextView's go here
TVterms = (TextView)findViewById(R.id.TVterms);
//oonClick's go here
//pd'// STOPSHIP: 12/18/2015
PD = new ProgressDialog(this);
PD.setMessage("Creating your account...");
PD.setCancelable(false);
}
public void onSignUpClick(View v)
{
if (v.getId() == R.id.bRR);
{
EditText fname = (EditText)findViewById(R.id.etFN);
EditText lname = (EditText)findViewById(R.id.etLN);
EditText uname = (EditText)findViewById(R.id.etUN);
EditText email = (EditText)findViewById(R.id.etEmail);
EditText pass1 = (EditText)findViewById(R.id.etPW);
EditText pass2 = (EditText)findViewById(R.id.etRPW);
String fnamestr = fname.getText().toString();
String lnamestr = lname.getText().toString();
String unamestr = uname.getText().toString();
String emailstr = email.getText().toString();
String pass1str = pass1.getText().toString();
String pass2str = pass2.getText().toString();
if (!pass1str.equals(pass2str))
{
//popup msg
Toast pass = Toast.makeText(Register.this, "Password do not match!", Toast.LENGTH_SHORT);
pass.show();
}
}
}
private void initTypeface() {
Typeface myTypeface = Typeface.createFromAsset(getAssets(), "fonts/SinkinSans-300Light.otf");
TextView tittleText=(TextView) findViewById(R.id.textView5);
tittleText.setTypeface(myTypeface);
myTypeface = Typeface.createFromAsset(getAssets(), "fonts/SinkinSans-300Light.otf");
tittleText = (TextView) findViewById(R.id.textView7);
tittleText.setTypeface(myTypeface);
myTypeface = Typeface.createFromAsset(getAssets(), "fonts/SinkinSans-300Light.otf");
tittleText = (TextView) findViewById(R.id.textView8);
tittleText.setTypeface(myTypeface);
myTypeface = Typeface.createFromAsset(getAssets(), "fonts/SinkinSans-300Light.otf");
tittleText = (TextView) findViewById(R.id.textView9);
tittleText.setTypeface(myTypeface);
myTypeface = Typeface.createFromAsset(getAssets(), "fonts/SinkinSans-300Light.otf");
tittleText = (TextView) findViewById(R.id.textView10);
tittleText.setTypeface(myTypeface);
myTypeface = Typeface.createFromAsset(getAssets(), "fonts/SinkinSans-300Light.otf");
tittleText = (TextView) findViewById(R.id.textView11);
tittleText.setTypeface(myTypeface);
myTypeface = Typeface.createFromAsset(getAssets(), "fonts/SinkinSans-300Light.otf");
tittleText = (TextView) findViewById(R.id.textView12);
tittleText.setTypeface(myTypeface);
myTypeface = Typeface.createFromAsset(getAssets(), "fonts/SinkinSans-300Light.otf");
tittleText = (TextView) findViewById(R.id.textView13);
tittleText.setTypeface(myTypeface);
myTypeface = Typeface.createFromAsset(getAssets(), "fonts/SinkinSans-300Light.otf");
tittleText = (TextView) findViewById(R.id.TVterms);
tittleText.setTypeface(myTypeface);
}
public void insert(View view){
PD.show();
fname = etFN.getText().toString();
lname = etLN.getText().toString();
uname = etUN.getText().toString();
email = etEmail.getText().toString();
pass = etPW.getText().toString();
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
PD.dismiss();
etFN.setText("");
etLN.setText("");
etUN.setText("");
etEmail.setText("");
etPW.setText("");
Toast.makeText(getApplicationContext(),
"Your account is created!",
Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
PD.dismiss();
Toast.makeText(getApplicationContext(),
"Error creating your account!",
Toast.LENGTH_SHORT).show();
}
}){
#Override
protected Map<String,String> getParams() {
Map<String,String> params = new HashMap<String,String>();
params.put("fname",fname);
return params;
}
};
MyApplication.getInstance().addToReqQueue(postRequest);
}
}
I want to add 5 more values into MySQL not just one.
#Override
protected Map<String,String> getParams() {
Map<String,String> params = new HashMap<String,String>();
params.put("fname",fname);
params.put("lname",lname );
...
return params;
}
I'm going to leave my old answer below because I still argue that ContentProvider might be a good mechanism for you since it logically isolates the syncing mechanisms for network transmission/etc.
I didn't realize you were using Volley at first, I had forgotten that it even exists since I just teach the manual stuff, and never use the 'convenience methods', etc.
....because if so it is on the Android device isn't MySQL, Android uses SQLite3 as its internal Database.
If you want to insert multiple things into a database, then you need to call insert over and over between a .beginTransaction() and a .endTransaction(), this way the database will 'throw away' any inserts that are done if any single insert fails.
Now you might be wondering how to pass multiple sets of data to the method to do the inserts. For this you have 2 options. You can pass an array of Contentvalues, or you can pass an array (or a collection such as arraylist/etc) of custom POJOs (and my recommendation would be to have that POJO class have a 'getContentValues() method that reuturns a content values object from each POJO.)
But in either case you have to begin your transaction, loop through all the Contentvalues, and then end the transation.
Android JAVADOC for SQLit SQLiteDatabase.insert(String, String, Contentvalues)
I personally NEVER write a DB that I don't immediately wrap by a ContentProvider in Android. Content Provider just gives a nicer separation of concerns/interface for me. (and then it is easy to add syncAdapters, accounts, and all that extra 'sugar' to make the data-store work wonders for you. But of course this depends on your target application, and the ones I write are almost by definition all networked.)
I am trying to retain the data in my Edittext views, using onsaveinstancestate. The user clicks on the "add" button, which is supposed to retain the information in the Edittext views. When the add button is clicked, the user is taken back to activity main. When the module is selected for editing, the edit_module layout is shown but without the information in the edittext views, which I am trying to retain. Any ideas?? I think I may be missing a step, is there more to it than saving the strings in the onsaveinstancestate method, and then assigning those strings to the Edittext views when the activity is called?? New to Android.
NewModule.java
public class NewModule extends Activity{
// The EditText objects
EditText ModuleCode;
EditText ModuleName;
EditText ModuleType;
EditText DayOfWeek;
EditText StartTime;
EditText EndTime;
EditText Location;
EditText AdditionalInfo;
#Override
public void onCreate(Bundle savedInstanceState) {
// Get saved data if there is any
super.onCreate(savedInstanceState);
dbTools = new DBTools(this);
// Designate that add_module.xml is the interface used
setContentView(R.layout.add_module);
// Initialize the EditText objects
ModuleCode= (EditText) findViewById(R.id.modcodeet);
ModuleName = (EditText) findViewById(R.id.modnameet);
ModuleType = (EditText) findViewById(R.id.moduletypeet);
DayOfWeek = (EditText) findViewById(R.id.dowet);
StartTime = (EditText) findViewById(R.id.starttimeet);
EndTime = (EditText) findViewById(R.id.endtimeet);
Location = (EditText) findViewById(R.id.locationet);
AdditionalInfo = (EditText) findViewById(R.id.additionalinfoet);
}
public void addNewModule(View view) {
// Will hold the HashMap of values
HashMap<String, String> queryValuesMap = new HashMap<String, String>();
// Get the values from the EditText boxes
queryValuesMap.put("ModuleCode", ModuleCode.getText().toString());
queryValuesMap.put("ModuleName", ModuleName.getText().toString());
queryValuesMap.put("ModuleType", ModuleType.getText().toString());
queryValuesMap.put("DayOfWeek", DayOfWeek.getText().toString());
queryValuesMap.put("StartTime", StartTime.getText().toString());
queryValuesMap.put("EndTime", EndTime.getText().toString());
queryValuesMap.put("Location", Location.getText().toString());
queryValuesMap.put("AdditionalInfo", AdditionalInfo.getText().toString());
// Call for the HashMap to be added to the database
dbTools.insertModule(queryValuesMap);
// Call for MainActivity to execute
this.callMainActivity(view);
}
public void callMainActivity(View view) {
Intent theIntent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(theIntent);
}
public void onSaveInstanceState(Bundle savedInstanceState){
EditText editText = (EditText) findViewById(R.id.modcodeet);
String code = editText.getText().toString();
savedInstanceState.putString("code", code);
EditText editText2 = (EditText) findViewById(R.id.modnameet);
String name = editText2.getText().toString();
savedInstanceState.putString("name", name);
EditText editText3 = (EditText) findViewById(R.id.moduletypeet);
String type = editText3.getText().toString();
savedInstanceState.putString("type", type);
EditText editText4 = (EditText) findViewById(R.id.dowet);
String dow = editText4.getText().toString();
savedInstanceState.putString("dow", dow);
EditText editText5 = (EditText) findViewById(R.id.starttimeet);
String messagesubject = editText5.getText().toString();
savedInstanceState.putString("start", messagesubject);
EditText editText6 = (EditText) findViewById(R.id.endtimeet);
String end = editText6.getText().toString();
savedInstanceState.putString("end",end);
EditText editText7 = (EditText) findViewById(R.id.locationet);
String location = editText7.getText().toString();
savedInstanceState.putString("location", location);
EditText editText8 = (EditText) findViewById(R.id.additionalinfoet);
String additionalinfo = editText8.getText().toString();
savedInstanceState.putString("additionalinfo", additionalinfo);
super.onSaveInstanceState(savedInstanceState);
}
}
TIA
Edit Module.java
public class EditModule extends Activity{
EditText ModuleCode;
EditText ModuleName;
EditText ModuleType;
EditText DayOfWeek;
EditText StartTime;
EditText EndTime;
EditText Location;
EditText AdditionalInfo;
DBTools dbTools = new DBTools(this);
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_module);
if (savedInstanceState != null)
{
String strValue = savedInstanceState.getString("code");
if (strValue != null);
ModuleCode = (EditText)findViewById(R.id.modcodeet);
ModuleCode.setText(strValue);
strValue = savedInstanceState.getString("name");
if (strValue != null);
ModuleName = (EditText)findViewById(R.id.modnameet);
ModuleName.setText(strValue);
strValue = savedInstanceState.getString("type");
if(strValue != null);
ModuleType = (EditText)findViewById(R.id.moduletypeet);
ModuleType.setText(strValue);
strValue = savedInstanceState.getString("dow");
if(strValue != null);
DayOfWeek = (EditText)findViewById(R.id.dowet);
DayOfWeek.setText(strValue);
strValue = savedInstanceState.getString("start");
if (strValue != null);
StartTime = (EditText)findViewById(R.id.starttimeet);
StartTime.setText(strValue);
strValue = savedInstanceState.getString("end");
if (strValue != null);
EndTime = (EditText)findViewById(R.id.endtimeet);
EndTime.setText(strValue);
strValue = savedInstanceState.getString("location");
if (strValue != null);
Location = (EditText)findViewById(R.id.locationet);
Location.setText(strValue);
strValue = savedInstanceState.getString("additionalinfo");
if (strValue != null);
AdditionalInfo = (EditText)findViewById(R.id.additionalinfoet);
AdditionalInfo.setText(strValue);
}
public void editModule(View view){
HashMap<String, String> queryValuesMap = new HashMap<String, String>();
ModuleName = (EditText) findViewById(R.id.modnameet);
ModuleType = (EditText) findViewById(R.id.moduletypeet);
DayOfWeek = (EditText) findViewById(R.id.dowet);
StartTime = (EditText) findViewById(R.id.starttimeet);
EndTime = (EditText) findViewById(R.id.endtimeet);
Location = (EditText) findViewById(R.id.locationet);
AdditionalInfo = (EditText) findViewById(R.id.additionalinfoet);
this.callMainActivity(view);
}
public void callMainActivity(View view){
Intent objIntent = new Intent(getApplication(), MainActivity.class);
startActivity(objIntent);
}
}
try like this:
//intialization of shared preferences
private SharedPreferences preferences;
//in oncreate() give like this:
preferences = PreferenceManager.getDefaultSharedPreferences(this);
// store the edittext value in shared preferences
Editor edit = preferences.edit();
edit.putString("edittextvalue", edittextvalue);
edit.commit();
//whereever u want to get value and use
String apptext = preferences.getString("edittextvalue","");
use SharedPreferences to save edittext value
I've been trying to fix these two bugs for a while and I feel like it has to do with a fundamental misunderstanding of what happens when I open up a new activity. Basically the program is a task management program. It works fine when I add new tasks without modifying the category, and the database updates fine and the main page of the application updates as I add new tasks to display these new tasks.
However, I recently added functionality for an "add categories" button. The purpose of this button is to open up a new listactivity that allows users to add new categories of tasks. Every time I open this from the task editing activity and then press the back button to get back to the main page, all of the tasks in the database get cleared. Wondering if anyone can tell me what's going on and why the data is getting wiped out.
here's the relevant code snippet from the front page (the list view showing all of the tasks:
private RemindersDbAdapter mDbHelper;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.reminder_list);
mDbHelper = new RemindersDbAdapter(this);
mDbHelper.open();
fillData();
registerForContextMenu(getListView());
}
private void fillData() {
Cursor remindersCursor = mDbHelper.fetchAllReminders();
startManagingCursor(remindersCursor);
// Create an array to specify the fields we want to display in the list (only TITLE)
String[] from = new String[]{RemindersDbAdapter.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 reminders =
new SimpleCursorAdapter(this, R.layout.reminder_row, remindersCursor, from, to);
setListAdapter(reminders);
}
Here's some of the code for my task editing view (the one calling the activity for the category listing):
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDbHelper = new RemindersDbAdapter(this);
//mCatDbHelper = new CategoriesDbAdapter(this);
setContentView(R.layout.reminder_edit);
mCalendar = Calendar.getInstance();
mTitleText = (EditText) findViewById(R.id.title);
//mBodyText = (EditText) findViewById(R.id.body);
mDateButton = (Button) findViewById(R.id.reminder_date);
mTimeButton = (Button) findViewById(R.id.reminder_time);
mLowPriorityButton = (Button) findViewById(R.id.low_priority);
mMedPriorityButton = (Button) findViewById(R.id.med_priority);
mHighPriorityButton = (Button) findViewById(R.id.high_priority);
mManageCategories = (Button) findViewById(R.id.manage_categories);
mSchoolRadio = (RadioButton)findViewById(R.id.radio_schoolwork);
mFamilyRadio = (RadioButton)findViewById(R.id.radio_family);
mOtherRadio = (RadioButton)findViewById(R.id.radio_other);
mContext = this;
priority = "Low";
category = "Other";
mConfirmButton = (Button) findViewById(R.id.confirm);
mRowId = savedInstanceState != null ? savedInstanceState.getLong(RemindersDbAdapter.KEY_ROWID)
: -1L;
registerButtonListenersAndSetDefaultText();
}
private void setRowIdFromIntent() {
if (mRowId == -1L) {
Bundle extras = getIntent().getExtras();
mRowId = extras != null ? extras.getLong(RemindersDbAdapter.KEY_ROWID)
: -1L;
}
}
#Override
protected void onPause() {
super.onPause();
mDbHelper.close();
}
#Override
protected void onResume() {
super.onResume();
mDbHelper.open();
setRowIdFromIntent();
//if(mRowId != -1L)
populateFields();
}
#Override
protected Dialog onCreateDialog(int id) {
switch(id) {
case DATE_PICKER_DIALOG:
return showDatePicker();
case TIME_PICKER_DIALOG:
return showTimePicker();
}
return super.onCreateDialog(id);
}
private void populateFields() {
// Only populate the text boxes and change the calendar date
// if the row is not null from the database.
if (mRowId != -1L) {
Cursor reminder = mDbHelper.fetchReminder(mRowId);
startManagingCursor(reminder);
mTitleText.setText(reminder.getString(
reminder.getColumnIndexOrThrow(RemindersDbAdapter.KEY_TITLE)));
category = reminder.getString(reminder.getColumnIndexOrThrow(RemindersDbAdapter.KEY_CATEGORY));
if(category.equals("School"))
mSchoolRadio.setChecked(true);
else if(category.equals("Family"))
mFamilyRadio.setChecked(true);
else
mOtherRadio.setChecked(true);
// Get the date from the database and format it for our use.
SimpleDateFormat dateTimeFormat = new SimpleDateFormat(DATE_TIME_FORMAT);
Date date = null;
try {
String dateString = reminder.getString(reminder.getColumnIndexOrThrow(RemindersDbAdapter.KEY_DATE_TIME));
date = dateTimeFormat.parse(dateString);
mCalendar.setTime(date);
} catch (ParseException e) {
Log.e("ReminderEditActivity", e.getMessage(), e);
}
} else {
// This is a new task - add defaults from preferences if set.
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String defaultTitleKey = getString(R.string.pref_task_title_key);
String defaultTimeKey = getString(R.string.pref_default_time_from_now_key);
String defaultTitle = prefs.getString(defaultTitleKey, null);
String defaultTime = prefs.getString(defaultTimeKey, null);
if(defaultTitle != null)
mTitleText.setText(defaultTitle);
if(defaultTime != null)
mCalendar.add(Calendar.MINUTE, Integer.parseInt(defaultTime));
}
updateDateButtonText();
updateTimeButtonText();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if(mRowId == -1L)
mRowId = -1L;
outState.putLong(RemindersDbAdapter.KEY_ROWID, mRowId);
}
/*
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
mRowId = savedInstanceState != null ? savedInstanceState.getLong(RemindersDbAdapter.KEY_ROWID)
: -1L;
}
*/
private void saveState() {
String title = mTitleText.getText().toString();
//String body = mBodyText.getText().toString();
SimpleDateFormat dateTimeFormat = new SimpleDateFormat(DATE_TIME_FORMAT);
String reminderDateTime = dateTimeFormat.format(mCalendar.getTime());
if (mRowId == -1L) {
long id = mDbHelper.createReminder(title, priority, category, reminderDateTime);
if (id > 0) {
mRowId = id;
}
} else {
mDbHelper.updateReminder(mRowId, title, priority, category, reminderDateTime);
}
new ReminderManager(this).setReminder(mRowId, mCalendar);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
}
Here's the call (in the same class as the above code) to the new CategoryListActivity activity that's causing the problems:
mManageCategories.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(mContext, CategoryListActivity.class);
startActivity(i);
//populateFields();
}
});
I left out a lot of the less relevant code. Anyway like I said above... the main problem is that as soon as I start this new CategoryListActivity activity, the database and all the tasks get wiped out. weirdly, even if I restart the emulator the tasks don't get wiped as long as I don't start the CategoryListActivity. If anyone has any idea what's going on please help.
Andrew checkout this two links that will explain you everything about database integration.
http://www.devx.com/wireless/Article/40842/1954
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/