I'm learning to write a demo about get input message from the EditText, but after finishing it, i found the message is wrong. I tried to log it. The answer is as below.
Code is here:
public class MainActivity extends Activity {
private EditText edit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edit = (EditText) findViewById(R.id.editText);
}
#Override
protected void onDestroy() {
super.onDestroy();
String input = edit.toString();
Log.i("tag",input);
save(input);
}
public void save(String input){
FileOutputStream out = null;
BufferedWriter writer = null;
try{
out = openFileOutput("data", Context.MODE_PRIVATE);
writer = new BufferedWriter(new OutputStreamWriter(out));
writer.write(input);
}catch (IOException e) {
e.printStackTrace();
}finally {
try {
if(writer != null){
writer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
My log cat shows following response
Replace this line:
String input = edit.toString();
with:
String input = edit.getText().toString();
try
edit.getText().toString(); to get text from EditText
When you try to use toString() method it will give hashcode value of the object.
In your case it is giving hashcode value of EditText object you have created.
If you want to get the string value you have entered in EditText field u have to first get Editable from EditText example below
editText.getText().toString() it will return the value you have entered in EditText
Related
I have an registration layout with its java file to store the user's credential locally to its app directory. But i need to store those credentials somewhere user can't access or make any change.
Is there a way to do. If so kindly help.
My .java file.
public class screen_25 extends Activity {
EditText searchBox;
EditText searchBox1;
EditText searchBox2;
EditText searchBox3;
EditText searchBox4;
EditText searchBox5;
TextView response;
Button save;
Button read;
private String fileName = "SampleFile2.pdf";
private String filePath = "MyFileStorage";
File myExternalFile;
String myData="";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.screen_25);
save=(Button)findViewById(R.id.save_user);
response=(TextView)findViewById(R.id.response);
searchBox=(EditText) findViewById(R.id.searchBox);
searchBox1=(EditText) findViewById(R.id.searchBox1);
searchBox2=(EditText) findViewById(R.id.searchBox2);
searchBox3=(EditText) findViewById(R.id.searchBox3);
searchBox4=(EditText) findViewById(R.id.searchBox4);
searchBox5=(EditText) findViewById(R.id.searchBox5);
save.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
try{
FileOutputStream fos =new FileOutputStream(myExternalFile);
fos.write(searchBox.getText().toString().getBytes());
fos.write(searchBox1.getText().toString().getBytes());
fos.write(searchBox2.getText().toString().getBytes());
fos.write(searchBox3.getText().toString().getBytes());
fos.write(searchBox4.getText().toString().getBytes());
fos.write(searchBox5.getText().toString().getBytes());
fos.close();
}
catch (IOException e )
{
e.printStackTrace();
}
searchBox .setText("");
searchBox1.setText("");
searchBox2.setText("");
searchBox3.setText("");
searchBox4.setText("");
searchBox5.setText("");
Toast.makeText(getApplicationContext(), "Registered", Toast.LENGTH_SHORT).show();
}
});
read = (Button) findViewById(R.id.read);
read.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
FileInputStream fis = new FileInputStream(myExternalFile);
DataInputStream in = new DataInputStream(fis);
BufferedReader br =
new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
myData = myData + strLine;
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
searchBox.setText(myData);
searchBox1.setText(myData);
searchBox2.setText(myData);
searchBox3.setText(myData);
searchBox4.setText(myData);
searchBox5.setText(myData);
response.setText("SampleFile.txt data retrieved from Internal Storage...");
}
});
if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) {
save.setEnabled(false);
}
else {
myExternalFile = new File(getExternalFilesDir(filePath), fileName);
}
}
private static boolean isExternalStorageReadOnly() {
String extStorageState = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState)) {
return true;
}
return false;
}
private static boolean isExternalStorageAvailable() {
String extStorageState = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(extStorageState)) {
return true;
}
return false;
}}
I have created a sample file to save those credentials. i need to store those somewhere safe where user cant access or modify those files.
What you're searching for are SharedPreferences.
Here's a tutorial on how to use it: https://developer.android.com/training/data-storage/shared-preferences
As it was mentioned by #Pascal - you can use shared preferences. I would clarify such topic. I think that using file for such data has some bad sides:
So huge actions with data
Easy to get it - one the other hand when a user will have root access he will be able to see SP (shared prefereces) data too.
So, as I see you would like to save some string data to apps storage. For writing data you need firstly to define global SP variable:
SharedPreferences mSettings;
than inside onCreate() method assign value:
mSettings = getSharedPreferences("app_data", Context.MODE_PRIVATE);
After it you can read/write some data. General types are mentioned here. So data writing you have to set key-value info into app storage:
mSettings = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("key_name", "some string data");
editor.apply();
and to read written data use such code:
String dataString = mSettings.getString("key_name", "default string value");
you can get such variables from any screen of your app. So, you can see that such method is lighter that files writing.
Below page is the one having data i want to save from user.
How do I make this data to be read on next activity having a editText of text view?
And is this Code correct?
AddMoney.class
public class AddMoney extends AppCompatActivity {
Button b1;
EditText et;
enter code here
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_money);
b1 = (Button) findViewById(R.id.b1);
et = (EditText) findViewById(R.id.et);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
saveData();
AlertDialog.Builder b = new AlertDialog.Builder(AddMoney.this);
b.setIcon(R.mipmap.ic_launcher);
int val = Integer.parseInt(et.getText().toString());
b.setTitle("MONEY ADDED");
String msg = "₹" + val + " has been added in your wallet";
b.setMessage(msg);
b.setCancelable(false);
b.setPositiveButton("OK",null);
AlertDialog d = b.create();
d.show();
}
});
}
public void saveData() {
try {
FileOutputStream fileOutputStream = openFileOutput("Expenses.txt", MODE_PRIVATE);
fileOutputStream.write(et.getText().toString().getBytes());
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
As a better approach you can make use of SharedPreference as SripadRaj suggested.
on the first activity,where you save the data:
SharedPreference sp =getSharedPreferences("app_package_name", Context.MODE_PRIVATE);
sp.putString("expense",et.getText().toString());
sp.apply();
On another activity:
SharedPreference sp =getSharedPreferences("app_package_name", Context.MODE_PRIVATE);
String expense = sp.getString("expense","0.0");
What do you think is wrong with this code ?
I am using this class: https://github.com/btouchard/HttpData/blob/master/README.md
Error:
java.lang.IllegalStateException: Could not execute method of the activity
Location of error: Log.i line!
Thanks for the assistance.
I guess it is a basic solution, but I can't find it.
public class Formulaire extends Activity {
EditText msgTextField;
Button sendButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.form);
//make message text field object
msgTextField = (EditText) findViewById(R.id.msgTextField);
//make button object
sendButton = (Button) findViewById(R.id.sendButton);
}
public void send(View v) {
//get message from message box
try {
String MonURL = "http://www.davidmarchioni.fr/glopper/test.txt";
HttpData request = new HttpData(MonURL);
request.header(MonURL);
String html = request.asString();
Thread.sleep(2600);
Log.i("OK >> ", html);
Toast.makeText(getApplicationContext(), html, Toast.LENGTH_SHORT).show();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
well try on catching Exception, what if String html comes null? what maybe the reason
I have google alot, read javadoc, plus search different forums including this reading the issue but not found the correct answer to my question. The code snippet below is working fine but I want to exactly know what function to use exactly for read/write file in android. One can write to internal storage using OutputStream, FileOutputSteam.write(), Other is to use OutputStreamWriter(FileOutputSteam).write(), further BufferedWriter(OutputStreamWriter).write(), and finally PrintWriter.write().
Same goes for the InputStream case whether to use InputStream, FileInputSteam.read(), InputSreamReader(FileInputStream).read(), BufferedReader(InputStreamReader).
I want to know which exactly is the best proper way to do it. Please help me out as totally confused with this.
public class MainActivity extends Activity {
private static final String TAG = MainActivity.class.getName();
private static final String FILENAME = "students.txt";
private EditText stdId;
private Button Insert;
private Button Search;
private Button Update;
private Button Delete;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final String TAG = MainActivity.class.getName(); //output: com.fyp2.testapp.MainActivity
//value used for insert/delete/search
stdId = (EditText) findViewById(R.id.editTxtId);
//insert value in application sandbox file
Insert = (Button) findViewById(R.id.btnInsert);
Insert.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String IdToInsert = stdId.getText().toString().trim();
if(IdToInsert.length() > 0) {
myInsertFunc(IdToInsert);
}
else {
Toast.makeText(getApplicationContext(), "Id cannot be null!", Toast.LENGTH_SHORT).show();
stdId.requestFocus();
}
}
});
//search value from application sandbox file
Search = (Button) findViewById(R.id.btnSearch);
Search.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String IdToSearch = stdId.getText().toString().trim();
if(IdToSearch.length() > 0) {
mySearchFunc(IdToSearch);
}
else {
Toast.makeText(getApplicationContext(), "Id cannot be null!", Toast.LENGTH_SHORT).show();
stdId.requestFocus();
}
}
});
//delete value from application sandbox file
Delete = (Button) findViewById(R.id.btnDelete);
Delete.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String IdToDelete = stdId.getText().toString().trim();
if(IdToDelete.length() > 0) {
myDeleteFunc(IdToDelete);
}
else {
Toast.makeText(getApplicationContext(), "Id cannot be null!", Toast.LENGTH_SHORT).show();
stdId.requestFocus();
}
}
});
}
//function to insert
private void myInsertFunc(String data) {
//If student id already exist don't write it again -> Not handled at the moment
//Other exceptions may not have been handled properly
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput(FILENAME, Context.MODE_APPEND));
BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
bufferedWriter.append(data);
bufferedWriter.newLine();
Toast.makeText(getApplicationContext(), "Student ID: " + data + " Inserted Successfully!", Toast.LENGTH_SHORT).show();
bufferedWriter.close();
outputStreamWriter.close();
}
catch (IOException e) {
Log.e(TAG, "File write failed: " + e.toString());
}
}
//function to search
private void mySearchFunc(String data) {
//Id id not found show toast to user -> Not handled at the moment
try {
InputStream inputStream = openFileInput(FILENAME);
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
while ((receiveString = bufferedReader.readLine()) != null) {
if(receiveString.contains(data))
{
Toast.makeText(getApplicationContext(), "Found Student ID: " + data , Toast.LENGTH_SHORT).show();
break;
}
}
bufferedReader.close();
inputStream.close();
}
}
catch (FileNotFoundException e) {
Log.e(TAG, "File not found: " + e.toString());
} catch (IOException e) {
Log.e(TAG, "Can not read file: " + e.toString());
}
}
private void myDeleteFunc(String data) {
/* I have found a solution to delete a specific line from the file.
* But the problem is that it needs to scan the whole file line by line and copy the file contents that not matches the string to temp file.
* This solution can reduce the effeciency. Consider search 20,000 records in a file.
* Need to work around on it.
*/
}
private void myUpdateFunc(String data) {
/* Same goes to the update process...
* Need to scan all records and copy content in temp file and put the updated data in that file.
* Need to work around on this issue too...
*/
}
#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;
}
}
They all serve a purpose. There is best proper way, because each writer was made for a reason. Usually anything that has buffered is more efficient if you have mulitple read/writes/flush.
Both the Android and Java docs can be helpful and java docs give you more description for these writers. Check out these documentation. Try reading the javase6 ones which are more detailed:
Android_FileWriter
Java_FileWriter
Android_OutputStreamWriter
Java_OutputStreamWriter
Android_BufferedWriter
Java_BufferedWriter
I am very interested on App Development. But i began only two months ago so I have no experience.... I try to make a little translator app for my self. I have an EditText for Input and TextView for Output. the Idea is to read from EditText, search in a Text Document line by line with Line Number like
for Example:
Apple - Apfel
Car - Auto
then find the word and bring the translated word to textView
for Example:
EditText word is: Apple
the word is found Textview is: Apfel
If the word not founded so make TextView error message.
I have an Idea for make an Alert Dialog for Empty EditText
"eingabe" is my text value from EditText
So what i want to do was, that the Method look at EditText and get the text from there. When the Field is empty it comes an error message in form of an AlertDialog. If the field is not empty the Method take the Value and compares it with my Dictionary wich is saved in my Assets folder. thats why o need a InputStream and a Reader! But i have no idea how i write the correct syntax for the Code.
This is my Complete Method
eingabe means EditText
public void sucheErgebnis() throws IOException{
final Context context = DeutschActivity.this;
final String str;
final String eingabe = txtEingabe.getText().toString();
StringBuffer buf = new StringBuffer();
InputStream is = this.getResources().getAssets().open("dictionary.rtf");
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
btnSuch = (Button)findViewById(R.id.btnSuch);
btnSuch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(Objects.equals(eingabe, "")){
new AlertDialog.Builder(context)
.setTitle("Dikkat")
.setMessage("Arama alani bos kalamaz!")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
txtEingabe.setSelection(0);
}
})
.setIcon(android.R.drawable.ic_dialog_alert).show();
}
else{
}
}
});
}
I have written this code which will read through the file (as format mentioned by you) stored in asset folder and return the translated word:
public class MainActivity extends AppCompatActivity {
EditText txtEingabe;
Button btnSuch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtEingabe = (EditText)findViewById(R.id.txtEingabe);
btnSuch = (Button)findViewById(R.id.btnSuch);
try {
sucheErgebnis();
} catch (IOException e) {
e.printStackTrace();
}
}
public void sucheErgebnis() throws IOException {
final Context context = MainActivity.this;
final String str;
StringBuffer buf = new StringBuffer();
btnSuch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String eingabe = txtEingabe.getText().toString().trim();
if(eingabe.equals("")){
new AlertDialog.Builder(context)
.setTitle("Dikkat")
.setMessage("Arama alani bos kalamaz!")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
txtEingabe.setSelection(0);
}
})
.setIcon(android.R.drawable.ic_dialog_alert).show();
}
else{
String translatedWord = FileReaderFromAssets.read(context, eingabe);
if(!translatedWord.equals("")){
txtEingabe.setText(translatedWord);
}
else{
// write your code here if that word not present in the rtf file
}
}
}
});
}
Here is the method which search through the file and return the matched word, "" if match not found:
public class FileReaderFromAssets {
public static String read(Context context, String word){
String translatedWord = "";
BufferedReader reader = null;
try {
String[] line;
reader = new BufferedReader(
new InputStreamReader(context.getAssets().open("dictionary.rtf")));
// do reading, usually loop until end of file reading
String mLine;
while ((mLine = reader.readLine()) != null) {
line = mLine.split("-");
String temp= line[0].trim();
if(temp.equalsIgnoreCase(word.trim())){
translatedWord = line[1].trim();
break;
}
}
return translatedWord;
} catch (Exception e) {
return translatedWord;
}
finally{
try{
reader.close();
}catch(IOException ex){
}
}
}
}