Android:onSaveInstanceState. How do you save entries into EditVew? - java

I'm trying to save user entries into a form, but for some reason I can not get it to work. When I kill the application and restart the data does not appear.
My aim is that if a user is halfway through completing the form and the application is killed, that when the application relaunches the entries will still remain. Any guidance would be much appreciated.
public class MainActivity extends Activity {
public final static String EXTRA_FROM = "com.example.assignment1.FROM";
public final static String EXTRA_TO = "com.example.assignment1.TO";
public final static String EXTRA_CC = "com.example.assignment1.CC";
public final static String EXTRA_BCC = "com.example.assignment1.BCC";
public final static String EXTRA_SUBJECT = "com.example.assignment1.SUBJECT";
public final static String EXTRA_COMPOSE = "com.example.assignment1.COMPOSE";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
protected void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
EditText emailFrom =(EditText) findViewById(R.id.editEmailFrom);
EditText emailTo =(EditText) findViewById(R.id.editEmailTo);
EditText emailCc =(EditText) findViewById(R.id.editEmailCc);
EditText emailBcc =(EditText) findViewById(R.id.editEmailBcc);
EditText emailSubject =(EditText) findViewById(R.id.editEmailSubject);
EditText emailCompose =(EditText) findViewById(R.id.editEmailCompose);
String from = emailFrom.getText().toString();
String to = emailTo.getText().toString();
String cc = emailCc.getText().toString();
String bcc = emailBcc.getText().toString();
String subject = emailSubject.getText().toString();
String compose = emailCompose.getText().toString();
outState.putString(EXTRA_FROM, from);
outState.putString(EXTRA_TO, to);
outState.putString(EXTRA_CC, cc);
outState.putString(EXTRA_BCC, bcc);
outState.putString(EXTRA_SUBJECT, subject);
outState.putString(EXTRA_COMPOSE, compose);
}
#Override
protected void onRestoreInstanceState(Bundle savedState)
{
EditText emailFrom =(EditText) findViewById(R.id.editEmailFrom);
EditText emailTo =(EditText) findViewById(R.id.editEmailTo);
EditText emailCc =(EditText) findViewById(R.id.editEmailCc);
EditText emailBcc =(EditText) findViewById(R.id.editEmailBcc);
EditText emailSubject =(EditText) findViewById(R.id.editEmailSubject);
EditText emailCompose =(EditText) findViewById(R.id.editEmailCompose);
String from = savedState.getString(EXTRA_FROM);
String to = savedState.getString(EXTRA_TO);
String cc = savedState.getString(EXTRA_CC);
String bcc = savedState.getString(EXTRA_BCC);
String subject = savedState.getString(EXTRA_SUBJECT);
String compose = savedState.getString(EXTRA_COMPOSE);
emailFrom.setText(from);
emailTo.setText(to);
emailCc.setText(cc);
emailBcc.setText(bcc);
emailSubject.setText(subject);
emailCompose.setText(compose);
}
public void emailSend (View sendButton)
{
Intent intent = new Intent(this,DisplayEmailActivity.class);
EditText emailFrom =(EditText) findViewById(R.id.editEmailFrom);
EditText emailTo =(EditText) findViewById(R.id.editEmailTo);
EditText emailCc =(EditText) findViewById(R.id.editEmailCc);
EditText emailBcc =(EditText) findViewById(R.id.editEmailBcc);
EditText emailSubject =(EditText) findViewById(R.id.editEmailSubject);
EditText emailCompose =(EditText) findViewById(R.id.editEmailCompose);
String from = emailFrom.getText().toString();
String to = emailTo.getText().toString();
String cc = emailCc.getText().toString();
String bcc = emailBcc.getText().toString();
String subject = emailSubject.getText().toString();
String compose = emailCompose.getText().toString();
intent.putExtra(EXTRA_FROM,from);
intent.putExtra(EXTRA_TO,to);
intent.putExtra(EXTRA_CC,cc);
intent.putExtra(EXTRA_BCC,bcc);
intent.putExtra(EXTRA_SUBJECT,subject);
intent.putExtra(EXTRA_COMPOSE,compose);
startActivity(intent);
}
}

To save a few items your best shot is to use SharedPreferences.
I've put an example some time ago on this post: SharedPreferences.
Good luck.

When I kill the application and restart the data does not appear.
Of course. If you kill the application (e.g., task killer), your saved instance state goes away. To handle this scenario, you need to persist your data to a file, database, etc.
To test whether or not onSaveInstanceState() works, rotate the screen or do some other type of configuration change.

Related

Calling Class to another activity

I have a second activity that handles all the user input and another activity that handles all the data from the second activity. What I want to do is call a class "SubmitName" from the activity to the second activity so that I dont need to pass the values from second activity to the main activity anymore. Here are the codes..
MainActivity (Where the class "SubmitName" are located and values are passed.)
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
TextView Name;
String lastname;
String licensenumber;
String mviolation;
String maplace;
String maddress;
String phonenumber;
String officername;
String contactnumber;
String datetime;
RecyclerView.LayoutManager layoutManager;
RecyclerAdapter adapter;
ArrayList<Violator> arrayList = new ArrayList<>();
BroadcastReceiver broadcastReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button addBtn = (Button)findViewById(R.id.btnAdd);
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, FragActivity.class);
startActivity(intent);
}
});
recyclerView = (RecyclerView)findViewById(R.id.recyclerView);
Name = (TextView) findViewById(R.id.tvName);
Intent intent = getIntent();
String str = intent.getStringExtra("firstname");
lastname = intent.getStringExtra("lastname");
licensenumber = intent.getStringExtra("licensenumber");
mviolation = intent.getStringExtra("violation");
maplace = intent.getStringExtra("arrestplace");
maddress = intent.getStringExtra("address");
phonenumber = intent.getStringExtra("phonenumber");
contactnumber = intent.getStringExtra("contactnumber");
officername = intent.getStringExtra("officername");
datetime = intent.getStringExtra("datetime");
Name.setText(str);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
adapter = new RecyclerAdapter(arrayList);
recyclerView.setAdapter(adapter);
readFromLocalStorage();
broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
readFromLocalStorage();
}
};
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.nav_bar, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.TrafficAd:
Intent i = new Intent(this, TrafficAdvisory.class);
this.startActivity(i);
break;
}
return super.onOptionsItemSelected(item);
}
public void submitName(View view)
{
String name = Name.getText().toString();
String lname = lastname;
String lnumber = licensenumber;
String violation = mviolation;
String aplace = maplace;
String address = maddress;
String pnumber = phonenumber;
String cnumber = contactnumber;
String oname = officername;
String dtime = datetime;
saveToAppServer(name,lname,lnumber,violation,aplace,address,pnumber,cnumber,oname,dtime);
Name.setText("");
}
public void readFromLocalStorage()
{
arrayList.clear();
DbHelper dbHelper = new DbHelper(this);
SQLiteDatabase database = dbHelper.getReadableDatabase();
Cursor cursor = dbHelper.readFromLocalDatabase(database);
while (cursor.moveToNext())
{
String name = cursor.getString(cursor.getColumnIndex(DBContract.NAME));
String lname = cursor.getString(cursor.getColumnIndex(DBContract.LNAME));
String lnumber = cursor.getString(cursor.getColumnIndex(DBContract.LNUMBER));
String violation = cursor.getString(cursor.getColumnIndex(DBContract.VIOLATION));
String aplace = cursor.getString(cursor.getColumnIndex(DBContract.ARRESTPLACE));
String address = cursor.getString(cursor.getColumnIndex(DBContract.ADDRESS));
String pnumber = cursor.getString(cursor.getColumnIndex(DBContract.PNUMBER));
String cnumber = cursor.getString(cursor.getColumnIndex(DBContract.CNUMBER));
String oname = cursor.getString(cursor.getColumnIndex(DBContract.ONAME));
String dtime = cursor.getString(cursor.getColumnIndex(DBContract.DTIME));
int sync_status = cursor.getInt(cursor.getColumnIndex(DBContract.SYNC_STATUS));
arrayList.add(new Violator(name,lname,lnumber,violation,aplace,address,pnumber,cnumber,oname,dtime,sync_status));
}
adapter.notifyDataSetChanged();
cursor.close();
}
public void saveToAppServer(final String name,final String lname, final String lnumber,final String violation, final String aplace,final String address, final String pnumber, final String cnumber, final String oname, final String dtime)
{
if (checkNetworkConnection())
{
StringRequest stringRequest = new StringRequest(Request.Method.POST,DBContract.SERVER_URL,
new Response.Listener<String>(){
#Override
public void onResponse(String response){
try {
JSONObject jsonObject = new JSONObject(response);
String Response = jsonObject.getString("response");
if(Response.equals("OK"))
{
saveToLocalStorage(name,lname,lnumber,violation,aplace,address,pnumber,cnumber,oname,dtime,DBContract.SYNC_STATUS_OK);
}
else
{
saveToLocalStorage(name,lname,lnumber,violation,aplace,address,pnumber,cnumber,oname,dtime,DBContract.SYNC_STATUS_FAILED);
}
} catch (JSONException e){
e.printStackTrace();
}
}
},new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error){
saveToLocalStorage(name,lname,lnumber,violation,aplace,address,pnumber,cnumber,oname,dtime,DBContract.SYNC_STATUS_FAILED);
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<>();
params.put("name",name);
params.put("lname",lname);
params.put("lnumber",lnumber);
params.put("violation", violation);
params.put("aplace", aplace);
params.put("address",address);
params.put("pnumber",pnumber);
params.put("cnumber",cnumber);
params.put("oname",oname);
params.put("dtime",dtime);
return params;
}
}
;
MySingleton.getInstance(MainActivity.this).addToRequestQue(stringRequest);
}
else
{
saveToLocalStorage(name,lname,lnumber,violation,aplace,address,pnumber,cnumber,oname,dtime,DBContract.SYNC_STATUS_FAILED);
}
}
SecondActivity (Where inputs are handled and data passing to the mainactivity)
public class ViolatorDetail extends AppCompatActivity implements View.OnClickListener{
EditText Name;
Button btnClose;
TextView DTime;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_violator_detail);
DTime = (TextView)findViewById(R.id.tvDTime);
final String currentDT = DateFormat.getDateTimeInstance().format(new Date());
DTime.setText(currentDT);
btnClose = (Button) findViewById(R.id.btnClose);
btnClose.setOnClickListener(this);
Button btnSubmit = (Button)findViewById(R.id.btnSubmit);
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText Name = (EditText)findViewById(R.id.etfName);
EditText LName = (EditText)findViewById(R.id.etlName);
EditText LNumber = (EditText)findViewById(R.id.etlNumber);
EditText Violation = (EditText)findViewById(R.id.etViolation);
EditText Arrestplace = (EditText)findViewById(R.id.etaPlace);
EditText Address = (EditText)findViewById(R.id.etAddress);
EditText PNumber = (EditText)findViewById(R.id.etpNumber);
EditText CNumber = (EditText)findViewById(R.id.etcNumber);
EditText OName = (EditText)findViewById(R.id.etoName);
String DT = DTime.getText().toString();
Intent intent = new Intent(ViolatorDetail.this, MainActivity.class);
intent.putExtra("firstname", Name.getText().toString());
intent.putExtra("lastname", LName.getText().toString());
intent.putExtra("licensenumber", LNumber.getText().toString());
intent.putExtra("violation", Violation.getText().toString());
intent.putExtra("arrestplace", Arrestplace.getText().toString());
intent.putExtra("address", Address.getText().toString());
intent.putExtra("phonenumber", PNumber.getText().toString());
intent.putExtra("contactnumber", CNumber.getText().toString());
intent.putExtra("officername", OName.getText().toString());
intent.putExtra("datetime", DT);
startActivity(intent);
}
});
}
}
What I want to do is call the "SUBMITNAME" class to the second activity so that no data passing will be done anymore.
As other friends mentioned Intent is a correct and good way to transfer data between activities. But if you want to avoid writing so much code to transfer data I suggest to create a pure java class (or java bean) and define all needed fields in that class (note: this class should implement java.io.Serializable interface). Now you could transfer instances of this class between activities.
I don’t think there is a better way of passing data between activities than Intents.
What you probably need is encapsulation of passing of extra. You can achieve this by making a static method in the ViolatorDetail class, which accepts as arguments as values you would like to pass, and returns Intent.
public static Intent newIntent(Context packageContext, String ... args){
Intent intent = new Intent(packageContext, ViolatorDetail.this);
intent.putExtra(EXTRA_STRING_ARGS, args);
return intent;
}
Then in the caller class you make an intent by makeing a static call on that function, and pass values as arguments
Intent intent = ViolatorDetail.newIntent(getActivity(), strings)
startActivity(intent);
However, in your case, you should probably make a more sensible way of passing data than as array of strings.
If you don't want to pass data between Activities with Intent, you can do it by writing certain data in a file and when you need it just read from it... I did it like this and I'm still happy i did it that way, it's simple and relatively quick, you just have to care a little about IOExceptions.

Android new class TextWatcher cannot tran value from mainActivity

I have the problem on android app development, I have a class to TextWatcher.
but the textWatcher cannot use the method of getSelectionStart(), getSelectionEnd(), length(), findViewById(mInputLayout), setText(s) and setSelection(tempSelection).
and the mainActivity cannot tran the value into customTextWatcher.
Could you help me please.
public class customTextWatcher implements TextWatcher {
CharSequence temp;
int editStart;
int editEnd;
String mEditText; //EditText
String mInputLayout; //Input Layout
int tempLength; // Set the EditText length to limit it
//private String activity; // Set the Activity of the class to use this class
String errorText; // When out of boundary with EditText , it will show the errorText
// Constructor for this Class,
// Get the params from main Class
public customTextWatcher(String mEditText, String mInputLayout, int tempLength, String errorText) {
this.mEditText = mEditText;
this.mInputLayout = mInputLayout;
this.tempLength = tempLength;
//this.activity = activity;
this.errorText = errorText;
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
temp = s;
}
#Override
public void afterTextChanged(Editable s) {
// String selectedText = mEditText.getText().substring(editStart, editEnd);
editStart = mEditText.getSelectionStart();
editEnd = mEditText.getSelectionEnd();
if (tempLength.length() > 10) {
TextInputLayout til = (TextInputLayout)findViewById(mInputLayout);
til.setErrorEnabled(true);
til.setError(errorText);
s.delete(editStart - 1, editEnd);
int tempSelection = editStart;
mEditText.setText(s);
mEditText.setSelection(tempSelection);
}
}
}
mEditTextLastName = (EditText) findViewById(R.id.input_lastName);
mEditTextFirstName = (EditText) findViewById(R.id.input_firstName);
mEditTextHomeAddress = (EditText) findViewById(R.id.input_homeAddress);
mEditTextCountry = (EditText) findViewById(R.id.input_country);
mEditTextPhoneCode = (EditText) findViewById(R.id.input_PhoneCode);
mEditTextMobile = (EditText) findViewById(R.id.input_mobile);
mEditTextOtherPhone = (EditText) findViewById(R.id.input_otherPhone);
mEditTextEmail = (EditText) findViewById(R.id.input_email);
mEditTextPassword = (EditText) findViewById(R.id.input_password);
mEditTextReComfirmPassword = (EditText) findViewById(R.id.input_reConfirmPassword);
mEditTextWechat = (EditText) findViewById(R.id.input_wechat);
/**
* mTextInputLayout findById of layout TextInputLayout
*/
mTextInputLayout_LastName = (TextInputLayout) findViewById(R.id.lastNameLayout);
mTextInputLayout_FistName = (TextInputLayout) findViewById(R.id.firstNameLayout);
mTextInputLayout_HomeAddress = (TextInputLayout) findViewById(R.id.homeAddressLayout);
mTextInputLayout_Country = (TextInputLayout) findViewById(R.id.countryLayout);
mTextInputLayout_PhoneCode = (TextInputLayout) findViewById(R.id.phoneCodeLayout);
mTextInputLayout_Mobile = (TextInputLayout) findViewById(R.id.mobileLayout);
mTextInputLayout_OtherPhone = (TextInputLayout) findViewById(R.id.otherPhoneLayout);
mTextInputLayout_Email = (TextInputLayout) findViewById(R.id.emailAddressLayout);
mTextInputLayout_Password = (TextInputLayout) findViewById(R.id.passwordLayout);
mTextInputLayout_ReComfirmPassword = (TextInputLayout) findViewById(R.id.reConfirmPasswordLayout);
mTextInputLayout_Wechat = (TextInputLayout) findViewById(R.id.wechatLayout);
mEditTextLastName.addTextChangedListener(new customTextWatcher(mEditTextLastNam,mTextInputLayout_LastName,20,"error : Can't over 20's character!"));
That is because you moved your TextWatcher into separate class.
If your TextWatcher is inner class within your Activity, you can access that Activity (Context). One solution is to define callback interfaces in your TextWatcher and implement it in Activity. By doing so, you will be able to set your Activity as callback for TextWatcher and access Activity's methods.

Android Volley String Request not sending POST Data to user database

I am writing an android app to interact with a user database on a live server. I'm currently working on a 'register user' activity, which is supposed to simply add a user to the database, based on information they enter in an edit text field.
I am Using Android's Volley Library to accomplish this, using a simple String Request. The request is then added to a request queue. I am able to connect and get a response from the server, but when I attempt to update the database (add a user) nothing happens.
I understand that while using method=POST (which my server does), one must override the getParams() method specifying Key/Value pairs (where KEY is the post data from the php script and the value is the new data.)
Ive tried implementing my request queue as a singleton class, creating a custom header, and even tried modifying volley's method from POST to 'DEPRECATED_GET_OR_POST' with no luck. If someone can tell me what i'm doing wrong or what's missing id greatly appreciate it.
Here's my code:
//url to the registration page (on the server)
private static final String Register_URL = "http://www.wupx.com/arcums/profile/register.php";
//key values (these are the values in the DB)
public static final String Key_Username = "username";
public static final String Key_Realname = "name";
public static final String Key_Password = "password2";
public static final String Key_Email = "email";
//declare the editText field & Button
private EditText editTextUsername;
private EditText editTextName;
private EditText editTextEmail;
private EditText editTextPassword;
private EditText editTextPassword2;
private Button buttonRegister;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
//reference editText fields and buttons
editTextUsername = (EditText) findViewById(R.id.editTextUserName);
editTextName = (EditText) findViewById(R.id.editTextRealName);
editTextEmail = (EditText) findViewById(R.id.editTextEmail);
editTextPassword = (EditText) findViewById(R.id.editTextPassword);
editTextPassword2 = (EditText) findViewById(R.id.editTextPasswordAgain);
buttonRegister = (Button) findViewById(R.id.registerButton);
buttonRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
registerUser();//calls the registerUser method.
}
});
}
//method to add user to the arcums database
private void registerUser() {
//print textview contents to logcat (debugging)
Log.d("log message", "entering register User method");
//values passed in from the user
final String Username = editTextUsername.getText().toString().trim();
final String Name = editTextName.getText().toString().trim();
final String Password = editTextPassword.getText().toString().trim();
final String Password2 = editTextPassword2.getText().toString().trim();
final String Email = editTextEmail.getText().toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.POST, Register_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// put a toast here
Toast.makeText(register.this, R.string.register_response , Toast.LENGTH_SHORT).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// error toast
Toast.makeText(register.this, R.string.register_error, Toast.LENGTH_SHORT).show();
}
}){
//returns a hashmap with key value pairs
#Override
protected Map<String,String> getParams(){
Map<String, String> params = new HashMap<String, String>();
params.put(Key_Username, Username);
params.put(Key_Realname, Name);
params.put(Key_Password, Password2);
params.put(Key_Email, Email);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
and here's a screenshot of my DB values in php myadmin:
DB values
note that not all fields need to be filled out in order to be added to the database- just name, username, email, and password.
the server itself has no GUI so i'm unable to post the PHP code at the moment. I hope someone can help with the information given!

Retrieving data from wrong database

I have two SQLiteDatabases in my application. One retrieves the user's input from the class DataEntryHome. The other retrieves the user's input from the class GarmentEntry. I also have two activities which display the user's inputs in the form of a ListView. These are shown in the activities RecapPage and RecapOrderDetails.
To make things simpler for myself as a new java programmer, I have used separate dbHelper, DataProvider and ListDataAdapter classes for the separate databases.
My issue is that in the RecapOrderDetails class, the ListView is populated with the contents from DataEntryHome rather than from GarmentEntry. The ListView in RecapPage works as it should.
Here is all of the code that I think is relevant:
DataEntryHome:
public class DataEntryHome extends AppCompatActivity implements TextWatcher{
private static Button DataEntryButtonN, SaveDataButton, PreviewButton;
Context context = this;
UserDbHelper userDbHelper;
SQLiteDatabase sqLiteDatabase;
EditText ContactName,ContactSurname,ContactEmail,ContactPhone,ContactAddInfo;
Button saveDetails;
public static ArrayList<String> CUSTOMERS = new ArrayList<String>();
String customers[];
#Override
public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
final EditText surnameArray = (EditText) findViewById(R.id.customerSurnameEntry);
saveDetails = (Button) findViewById(R.id.saveDetailsButton);
saveDetails.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String erm=surnameArray.getText().toString().trim();
if(erm.length() != 0){
CUSTOMERS.add(erm);
surnameArray.setText("");
}
Intent arrayItems = new Intent(DataEntryHome.this, RecapPage.class);
Bundle arrayItemsBundle = new Bundle();
}
});
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.data_entry_home);
ContactName = (EditText) findViewById(R.id.customerFirstNameEntry);
ContactName.addTextChangedListener(this);
ContactSurname = (EditText) findViewById(R.id.customerSurnameEntry);
ContactSurname.addTextChangedListener(this);
ContactEmail = (EditText) findViewById(R.id.customerEmail);
ContactEmail.addTextChangedListener(this);
ContactPhone = (EditText) findViewById(R.id.customerNumber);
ContactPhone.addTextChangedListener(this);
ContactAddInfo = (EditText) findViewById(R.id.addInfo1);
setupSaveDataButton();
}
public void addContact(View view) {
String name = ContactName.getText().toString();
String surname = ContactSurname.getText().toString();
String email = ContactEmail.getText().toString();
String phone = ContactPhone.getText().toString();
String add_info = ContactAddInfo.getText().toString();
userDbHelper = new UserDbHelper(context);
sqLiteDatabase = userDbHelper.getWritableDatabase();
userDbHelper.addInformation(name,surname,email,phone,add_info,sqLiteDatabase);
Toast.makeText(getBaseContext(), "Data saved", Toast.LENGTH_SHORT).show();
userDbHelper.close();
}
RecapPage:
public class RecapPage extends AppCompatActivity{
ListView listView;
SQLiteDatabase sqLiteDatabase;
UserDbHelper userDbHelper;
Cursor cursor;
ListDataAdapter listDataAdapter;
Button goButtonAction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recap_page);
goButtonAction = (Button) findViewById(R.id.goButton);
listView = (ListView) findViewById(R.id.list_view);
listView.setClickable(true);
listDataAdapter = new ListDataAdapter(getApplicationContext(),R.layout.row_layout);
listView.setAdapter(listDataAdapter);
userDbHelper = new UserDbHelper(getApplicationContext());
sqLiteDatabase = userDbHelper.getReadableDatabase();
cursor = userDbHelper.getInformation(sqLiteDatabase);
if(cursor.moveToFirst()) {
do {
String first_name, surname, email, phone, add_info;
first_name = cursor.getString(0);
surname = cursor.getString(1);
email = cursor.getString(2);
phone = cursor.getString(3);
add_info = cursor.getString(4);
DataProvider dataProvider = new DataProvider(first_name,surname,email,phone,add_info);
listDataAdapter.add(dataProvider);
} while (cursor.moveToNext());
}
Intent arrayItems = getIntent();
Bundle arrayItemsBundle = arrayItems.getExtras();
}
GarmentEntry:
public class GarmentEntry extends AppCompatActivity {
Spinner tcshenspinner, backprintoptionsspinner, tcbackhenspinner, cosspinner, ppspinner;
ArrayAdapter<CharSequence> tcshenspinneradapter, backprintoptionsspinneradapter, tcbackhenspinneradapter,
cosspinneradapter, ppspinneradapter;
Button nextButton1;
public static ImageView imagePreview;
public static final String IMAGE_RES_ID_1 = "image_res_id_1";
Context contextOrder = this;
OrderDbHelper userDbHelperOrder;
SQLiteDatabase sqLiteDatabaseOrder;
EditText OrderNoOfShirts, OrderFrontText,OrderShirt1;
Spinner OrderColourOfShirts, OrderPrintPosition, OrderColourOfText, OrderBackPrint, OrderBackColour;
Button saveOrderDetails;
public static ArrayList<String> ORDERINFO = new ArrayList<>();
String orderinfo[];
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.garment_entry);
final EditText shirtArray = (EditText)findViewById(R.id.noofshirts);
saveOrderDetails = (Button)findViewById(R.id.saveOrderDetails);
saveOrderDetails.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String erm=shirtArray.getText().toString().trim();
if (erm.length() != 0){
ORDERINFO.add(erm);
shirtArray.setText("");
}
Intent arrayItemsOrder = new Intent(GarmentEntry.this, RecapOrderDetails.class);
Bundle arrayItemsOrderBundle = new Bundle();
}
});
OrderNoOfShirts = (EditText)findViewById(R.id.noofshirts);
OrderColourOfShirts = (Spinner)findViewById(R.id.cosspinner);
OrderFrontText = (EditText)findViewById(R.id.fronttexthint);
OrderPrintPosition = (Spinner)findViewById(R.id.ppspinner);
OrderColourOfText = (Spinner)findViewById(R.id.tcshenspinner);
OrderBackPrint = (Spinner)findViewById(R.id.backprintoptionsspinner);
OrderBackColour = (Spinner)findViewById(R.id.tcbackhenspinner);
OrderShirt1 = (EditText)findViewById(R.id.nnsshirt1);
}
public void addOrder(View view){
String no_of_shirts = OrderNoOfShirts.getText().toString();
String colour_of_shirts = OrderColourOfShirts.getSelectedItem().toString();
String front_text = OrderFrontText.getText().toString();
String print_position = OrderPrintPosition.getSelectedItem().toString();
String colour_of_text = OrderColourOfText.getSelectedItem().toString();
String back_print = OrderBackPrint.getSelectedItem().toString();
String back_colour = OrderBackColour.getSelectedItem().toString();
String shirt_1 = OrderShirt1.getText().toString();
userDbHelperOrder = new OrderDbHelper(contextOrder);
sqLiteDatabaseOrder = userDbHelperOrder.getWritableDatabase();
userDbHelperOrder.addInformationOrder(no_of_shirts,colour_of_shirts,front_text,print_position,colour_of_text,back_print,
back_colour,shirt_1, null,null,null,null,null,null,null,null,null,null,sqLiteDatabaseOrder);
Toast.makeText(getBaseContext(), "Data saved", Toast.LENGTH_SHORT).show();
userDbHelperOrder.close();
}
RecapOrderDetails:
public class RecapOrderDetails extends AppCompatActivity {
ListView listViewOrder;
SQLiteDatabase sqLiteDatabaseOrder;
UserDbHelper userDbHelperOrder;
Cursor cursorOrder;
ListDataAdapterOrder listDataAdapterOrder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recap_order_details);
listViewOrder = (ListView)findViewById(R.id.list_view_order);
listViewOrder.setClickable(true);
listDataAdapterOrder = new ListDataAdapterOrder(getApplicationContext(),R.layout.order_layout);
listViewOrder.setAdapter(listDataAdapterOrder);
userDbHelperOrder = new UserDbHelper(getApplicationContext());
sqLiteDatabaseOrder = userDbHelperOrder.getReadableDatabase();
cursorOrder = userDbHelperOrder.getInformation(sqLiteDatabaseOrder);
if (cursorOrder.moveToFirst()){
do {
String no_of_shirts, colour_of_shirts, front_text, print_position, text_colour, back_print, back_colour, shirt1;
no_of_shirts = cursorOrder.getString(0);
colour_of_shirts = cursorOrder.getString(1);
front_text = cursorOrder.getString(2);
print_position = cursorOrder.getString(3);
text_colour = cursorOrder.getString(4);
/*back_print = cursorOrder.getString(5);
back_colour = cursorOrder.getString(6);
shirt1 = cursorOrder.getString(7);*/
DataProviderOrder dataProviderOrder = new DataProviderOrder(no_of_shirts,colour_of_shirts,front_text,print_position,
text_colour,null,null,null);
listDataAdapterOrder.add(dataProviderOrder);
}while (cursorOrder.moveToNext());
}
Intent arrayItems = getIntent();
Bundle arrayItemsBundle = arrayItems.getExtras();
}
I THINK the reason why the wrong data is being passed into the second database is because of this:
if (cursorOrder.moveToFirst()){
do {
String no_of_shirts, colour_of_shirts, front_text, print_position, text_colour, back_print, back_colour, shirt1;
no_of_shirts = cursorOrder.getString(0);
colour_of_shirts = cursorOrder.getString(1);
front_text = cursorOrder.getString(2);
print_position = cursorOrder.getString(3);
text_colour = cursorOrder.getString(4);
/*back_print = cursorOrder.getString(5);
back_colour = cursorOrder.getString(6);
shirt1 = cursorOrder.getString(7);*/
DataProviderOrder dataProviderOrder = new DataProviderOrder(no_of_shirts,colour_of_shirts,front_text,print_position,
text_colour,null,null,null);
listDataAdapterOrder.add(dataProviderOrder);
Are the values 0-4 reserved for the first database (for DataEntryHome)?
I also think that this:
userDbHelperOrder = new UserDbHelper(getApplicationContext());
sqLiteDatabaseOrder = userDbHelperOrder.getReadableDatabase();
cursorOrder = userDbHelperOrder.getInformation(sqLiteDatabaseOrder);
has something to do with the matter.
I have figured it out.
On activity RecapOrderDetails, This:
userDbHelperOrder = new UserDbHelper(getApplicationContext());
was this issue.
To resolve it, I had to do the following:
OrderDbHelper = orderDbHelperOrder
in the main method.
And then replace
userDbHelperOrder = new UserDbHelper(getApplicationContext());
with
orderDbHelperOrder = new OrderDbHelper(getApplicationContext());

Saving information in EditText in android

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

Categories