I have a problem with my code, I need to read EditText from a user and than put that text into another layout and do some calculations. My problem is that I don't understand how to read/write data in Android. Below is a snippet of the read/write code.
Thanks for the help!
EDIT: Should be noted that all of this is inside of my MainActivity class
public EditText editName;
public EditText editAMT;
public Button save;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editName = (EditText) findViewById(R.id.editName);
editAMT = (EditText) findViewById(R.id.editAMT);
save = (Button) findViewById(R.id.save);
File fName = new File(name);
File fAMT = new File(AMT);
//WRITING TO THE FILE
try{
FileOutputStream test = openFileOutput(name, Context.MODE_PRIVATE);
FileOutputStream test2 = openFileOutput(AMT, Context.MODE_PRIVATE);
test.write(editName.getText().toString().getBytes());
test2.write(editAMT.getText().toString().getBytes());
test.close();
test2.close();
} catch(Exception e){
e.printStackTrace();
}
//READING FROM THE FILE
try{
BufferedReader inputReader = new BufferedReader(new InputStreamReader(openFileInput(name)));
String inputString;
StringBuffer stringBuffer = new StringBuffer();
while ((inputString = inputReader.readLine()) != null){
stringBuffer.append(inputString + "\n");
}
} catch (IOException e){
e.printStackTrace();
}
}
EDIT: Here is my action plan.
1) Get information from EditText called (eAMT). 2) Get information from EditText called (eName). 3) Put the information of eAMT into a file called eName.txt 4) In another activity, search for the file called eName. 5) Once search is completed, pull the contents of that file and display onto another activity (Main activity).
Instead of writing to a file, use Android's SharedPreferences:
SharedPreferences preferences = getSharedPreferences("com.example.myapp", MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("UniqueEditNameKey", editName.getText().toString);
From another activity, you can do the following to retrieve the value:
SharedPreferences preferences = getSharedPreferences("com.example.myapp", MODE_PRIVATE);
String name = preferences.getString("UniqueEditNameKey", ""); // second argument is default value if key does not exist
Related
There's a problem i'm fighting with for two days. Using FileWriter I try to save data into txt file. File is saved by an application but it's always empty.
b1.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
try {
boolean usunieto = true;
boolean stworzono = false;
String t_magazyn = e_magazyn.getText().toString();
String nazwa = e_nazwa.getText().toString();
if(!t_magazyn.trim().equals("")){
#SuppressLint("SdCardPath") File plik = new File("/sdcard/"+nazwa+".txt");
// jeśli plik nie istnieje, stwórz go
if(plik.exists()){
usunieto = plik.delete();
Toast.makeText(getApplicationContext(),"Plik został usunięty!",Toast
.LENGTH_SHORT).show();
}
if(usunieto){
stworzono = plik.createNewFile();
Toast.makeText(getApplicationContext(),"Plik utworzony!",Toast
.LENGTH_SHORT).show();
}
if(!usunieto||!stworzono){
Toast.makeText(getApplicationContext(),"Apka dalej cie olewa xD",Toast
.LENGTH_SHORT).show();
}
//THIS PART DOESN'T WORK AS INTENDED
FileWriter wpis = new FileWriter(plik.getName(),true);
BufferedWriter bufor = new BufferedWriter(wpis);
bufor.write(e_magazyn.getText().toString());
i_e_magazyn.setText(e_magazyn.getText().toString());
bufor.close();
}
}
catch(IOException e) {
e.printStackTrace();
}
}
});
e_magazyn,e_nazwa are EditText fields and i_e_magazyn is TextView field
In b2 button which isn't visible here this line of code works.
i_e_magazyn.setText(e_magazyn.getText().toString());
I tried a lot of actions to update data into file but it looks like after creating a new FileWriter variables are made empty
How do i make it work?
You just need to write this line
FileWriter wpis = new FileWriter(plik,true);
Instead of
FileWriter wpis = new FileWriter(plik.getName(),true);
I'm trying to make a pretty simple app to help my girlfriend feel safer.
Im really bad at this, and a little help would go a long way. I've been trying to work with intents, and I really feel as if I'm super close to the solution at hand, I just need a little help.
So, the opening page is supposed to wait until you have data in your shared Preferences and then it will act on it.
The second page is supposed to take some data from EditTexts and store it in your intent. For some reason though, my data is not being stored, and when I pull something from the intent it is "".
CLASS 1:
public void ActivateAlarm(View view){
Bundle myBundle = getIntent().getExtras();
if(myBundle == null){
Log.i("The bundle is empty!", "Smashing success!");
}
else{
SharedPreferences sharedPreferences = this.getSharedPreferences("com.example.jackson.distressalarm", Context.MODE_PRIVATE);
String NumberToCall = sharedPreferences.getString("CallNumber", "");
String TextOne = sharedPreferences.getString("1Text", "");
String TextTwo = sharedPreferences.getString("2Text", "");
String TextThree = sharedPreferences.getString("3Text", "");
Button myButton = (Button) findViewById(R.id.button);
myButton.setText(TextOne);
Log.i("MY NUMBER TO CALL", NumberToCall);
/*Take in the data from the settings. Check it for consistency.
1)Are the numbers empty?
2)Is the number 911 or a 7 digit number?
3)Do they have a passcode?
4)Is the number real? No philisophical BS
*/
}
}
CLASS 2:
public void GoToAlarm(View view){
EditText NumberToCall = (EditText) findViewById(R.id.callNumber);
EditText text1 = (EditText) findViewById(R.id.textNumOne);
EditText text2 = (EditText) findViewById(R.id.textNumTwo);
EditText text3 = (EditText) findViewById(R.id.textNumThree);
Intent intent = new Intent(this, AlarmActive.class);
intent.putExtra("callNumber", NumberToCall.getText().toString());
intent.putExtra("1Text", text1.getText().toString());
intent.putExtra("2Text", text2.getText().toString());
intent.putExtra("3Text", text3.getText().toString());
startActivity(intent);
}
I think the problem is coming from a bit of a mix-up between Intents and SharedPreferences.
An Intent is a way to pass data from one activity to another. You're passing data correctly in Class 2, but you're not retrieving it in Class 1. Here's how you can do that:
String NumberToCall = intent.getStringExtra("CallNumber");
String TextOne = intent.getStringExtra("1Text");
String TextTwo = intent.getStringExtra("2Text");
String TextThree = intent.getStringExtra("3Text");
SharedPreferences are a way to save user data. If you want to save data in addition to passing it between activities, you'll need to add it to SharedPreferences with the following code:
SharedPreferences preferences = this.getSharedPreferences("com.example.jackson.distressalarm", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("callNumber", NumberToCall.getText().toString());
editor.putString("1Text", text1.getText().toString());
editor.putString("2Text", text2.getText().toString());
editor.putString("3Text", text3.getText().toString());
editor.apply();
You can retrieve the values with the code you were using in Class 1.
I have ran into a problem. So I am trying to get data from my SQLite database based on the primary key and then I will display the row of data in separate textviews on another activity. Now, I have this working using Intents, but the problem is that I do not want to use "startactivity(intent)" for example as I do not want to go to the activity, I just want to send the data.
So, in context, I have 3 activities. the first activity the user fills in the information and click "verify" button(which saves to the db). this brings them to the second activity which will have an "Information" button on it and when this button is clicked on the next activity this is where I want to display the data I have retrieved from the database.
I have read and tried multiple posts, but does anyone know what the best option is for me to use? I am currently trying to use a combination of SQLite and SharedPreferences.
Code for activity 1 to get and save the data:
Button Progress1 = (Button) findViewById(R.id.progressBar);
Progress1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
res = myDb.getProgressBar1(); //gets the data from the database
if (res.moveToFirst()) {
String LTget = res.getString(res.getColumnIndex("LINETYPE"));
String PT = res.getString(res.getColumnIndex("PACKAGETYPE"));
String QTY = res.getString(res.getColumnIndex("QUANTITY"));
String DUR = res.getString(res.getColumnIndex("DURATION"));
String ST = res.getString(res.getColumnIndex("STARTTIME"));
String ET = res.getString(res.getColumnIndex("ENDTIME"));
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(LTkey, LTget);
editor.putString(PTkey, PT);
editor.putString(qtykey,QTY);
editor.putString(durkey, DUR);
editor.putString(STkey, ST);
editor.putString(ETkey, ET);
editor.commit();
Intent intent = new Intent(Dashboard.this, Actforfragmentname.class); //takes me to the second activity
startActivity(intent);
Code to retrieve data: (unsure about getting from sharedpref so tried one line)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.verify_line);
myDb = new DatabaseHelper(this);
sqLiteDatabase = myDb.getReadableDatabase();
TextView LTTextView = (TextView) findViewById(R.id.textViewspinner1);
TextView PTTextView = (TextView) findViewById(R.id.textViewspinner2);
TextView QTYTextView = (TextView) findViewById(R.id.textViewQuantity);
TextView DURTextView = (TextView) findViewById(R.id.textViewDuration);
TextView STTextView = (TextView) findViewById(R.id.textViewStartTime);
TextView ETTextView = (TextView) findViewById(R.id.textViewendtime);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String LT =(sharedPreferences.getString(LTkey, LTget));
LTTextView.setText(LT);
PTTextView.setText(PT);
QTYTextView.setText(QTY);
DURTextView.setText(DUR);
STTextView.setText(ST);
ETTextView.setText(ET);
}
Can anyone help me out??
Thanks
You should use either Shared Preferences or SQLite database, the first one if you have a small amount of datas. The second one if it is bigger.
So You should push informations in database on button click in Activity 1, and retrieve them in Activity 3.
I got it working by using the method that I was trying out and that was using both SQLite and Shared Preferences together. I had to change the line of code that I was getting the sharedpreferences so to retrieve the data I know have:
SharedPreferences sharedPreferences = getSharedPreferences(MyPREFERENCES, MODE_PRIVATE);
String LT = sharedPreferences.getString(LTkey, null);
String PT = sharedPreferences.getString(PTkey, null);
String QTY = sharedPreferences.getString(qtykey, null);
String DUR = sharedPreferences.getString(durkey, null);
String ST = sharedPreferences.getString(STkey, null);
String ET = sharedPreferences.getString(ETkey, null);
I am using shared preferences but my code is not working. I don't know what's wrong with it. Am I implementing something wrong?
My main java activity(relevant bit of code) is:
public class MainActivity extends AppCompatActivity {
private String s;
public static final String subjectKey = "SubjectID";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final SharedPreferences sharedPreferences = getSharedPreferences(subjectKey, Context.MODE_PRIVATE);
TextView calc_monday = (TextView) findViewById(R.id.monday_calc);
calc_monday.setOnClickListener(
new Button.OnClickListener(){
public void onClick(View v){
CustomDialogClass cdd = new CustomDialogClass(MainActivity.this);
cdd.show();
TextView text1 = (TextView) cdd.findViewById(R.id.Subject_ID);
String text = sharedPreferences.getString(subjectKey, " ");
if(text != " ")
{
text1.setText(text); /* Edit the value here*/
}
TextView text2 = (TextView) cdd.findViewById(R.id.Room_ID);
text2.setText("6 (SEECS)");
TextView text3 = (TextView) cdd.findViewById(R.id.Time_ID);
text3.setText("09:00am - 09:50am");
}
}
);
calc_monday.setOnLongClickListener(
new Button.OnLongClickListener() {
public boolean onLongClick(View v) {
SettingDialogClass SDC = new SettingDialogClass(MainActivity.this);
SDC.show();
EditText texii = (EditText) SDC.findViewById(R.id.set_Subject_ID);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(subjectKey, texii.getText().toString());
editor.apply();
return true;
}
}
);
Basically I want that when I longClick a textbox (calc_monday), a dialog box should appear which appears. Now I should be able to write something on the EditText field which appears on this dialog box. Whatever I write should be stored and then displayed when I SINGLE CLICK on the same textbox (calc_monday)
Please see the 2 methods: onClick and onLongClick to understand.
The code is not working, i.e the text I write on EditText field on onLongCLick dialog box is not being displayed when I single click on the textbox.
What's wrong with the code
When you long press calc_monday, it just show your custom dialog with empty value for EditText. To save your text when input in EditText, create a button in your custom dialog, and call onClickListener action for this button, then save value to SharePreferences.
calc_monday.setOnLongClickListener(
new Button.OnLongClickListener() {
public boolean onLongClick(View v) {
SettingDialogClass SDC = new SettingDialogClass(MainActivity.this);
EditText texii = (EditText) SDC.findViewById(R.id.set_Subject_ID);
Button btnSave = (Button)SDC.findViewById(R.id.your_custom_button);
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(subjectKey, texii.getText().toString());
editor.apply();
SDC.dismiss();
}
});
SDC.show();
return true;
}
}
);
I think it's should be :
String text = sharedPreferences.getString("Name", " ");
Try these methods for saving and loading Strings with preferences:
//save prefs
public void savePrefs(String key, String value){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
//get prefs
public String loadPrefs(String key, String value){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String data = sharedPreferences.getString(key, value);
return data;
}
You can call the load method like this:
subjectKey = loadPrefs("YouCanNameThisAnything", subjectKey);
And you can call the save method like this:
savePrefs("YouCanNameThisAnything", subjectKey);
More details on how to use shared preferences is also available in the documentation here:
http://developer.android.com/reference/android/content/SharedPreferences.html
//create and initialize the intance of shared preference
SharedPreferences sharedPreferences = getSharedPreferences("Session", MODE_PRIVATE);
//save a string
SharedPreferences.Editor edit = sharedPreferences.edit();
edit.putString(subjectKey , texii.getText().toString());
edit.commit();
//retrieve the string
String subject = sharedPreferences.getString(subjectKey, "");
So my question might have been asked many times but i couldnt find an answer anywhere on the internet to it .
. What i want to do is store a textview using sharedprefeences .
In my first class (xp) i,m sending the textview to another class (feedback)
Now the feedback is reciving the textview with no single problem , but never saves it. How can i store that textview in the (feedback) class even after closing the app ??
Here's the class which is intenting the textview
public class Xp extends Activity {
Button accept;
TextView textV;
TextView xbnum;
public static final String PREFS_NAME = "MyPrefsFile";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.xp);
accept = (Button) findViewById(R.id.accept);
textV = (TextView) findViewById(R.id.textV);
xbnum = (TextView) findViewById(R.id.xpnum);
Bundle extras = getIntent().getExtras();
if (extras != null) {
String value1 = extras.getString("intent_xp");
final String value = extras.getString("intent_extra");
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor edit = settings.edit();
edit.putString(PREFS_NAME, value);
edit.putString(PREFS_NAME,value1);
textV.setText(value);
xbnum.setText(value1);
edit.commit();
accept.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(Xp.this, feedback.class);
i.putExtra("intent_extra", textV.getText().toString());
startActivity(i);
finish();
}
});
}
}
}
And here is the class which will recive the intent and save the textview (As supposed )
public class feedback extends Activity {
TextView test1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.feedback);
test1 = (TextView) findViewById(R.id.test1);
Bundle extras = getIntent().getExtras();
if (extras != null) {
String value = extras.getString("intent_extra");
SharedPreferences settings = getSharedPreferences("intent_pref", 0);
SharedPreferences.Editor edit = settings.edit();
edit.putString("intent_pref",value);
test1.setText(value);
edit.apply();
}
}
}
The class is reciving the text , and everything is okay . Only when i close the app and open it , everything is cleared out ..
May be I'm wrong but it seems that you missunderstood how shared preferences works.
If you want to store several values in a preferences file an access it in others classes you have to create one instance of a SharedPreferences.
In your case it means create in both "feedback" and "Xp" a SharedPreferences instance like this :
SharedPreferences settings = getSharedPreferences("MyPrefsFile", SharedPreferences.MODE_PRIVATE);
and then use this instance to store your datas with an editor.
Be careful if you can't store several value for the same key.
You can also store your value in several files as you are actually doing. But if you want to set your textview with the value of your preferences file you have to get it with the getString("key_of_your_value") method on your shared preferences instance.