This code receives information from an acquaintance you want to register in editText, and then clicks finButton to save the information you receive as a file called friendlist.txt.
However, the Toast message is outputted from the try-catch statement that is currently performed when finButton is pressed.
Also, the checkpermission does not work, which is wrapped in a try~catch statement, but does not have output on the logcat.
And manifest.
uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"
uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
is written.
Please let me know the solution.
And this content is written with a translator, so the sentence can be strange.
when you press finButton, the logcat is shown below.
The code corresponding to the 116th line is this.
FileOutputStream outstream = openFileOutput("friendList.txt", Activity.MODE_WORLD_WRITEABLE);
logcat
public class EnteringInformationOfFriendActivity extends AppCompatActivity {
Button finButton;
EditText phoneNumberEditText, nameEditText, emailEditText, groupEditText, memoEditText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_entering_information_of_friend);
phoneNumberEditText = (EditText) findViewById(R.id.phoneNumberEditText);
nameEditText = (EditText) findViewById(R.id.nameEditText);
emailEditText = (EditText) findViewById(R.id.emailEditText);
groupEditText = (EditText) findViewById(R.id.groupEditText);
memoEditText = (EditText) findViewById(R.id.memoEditText);
try{
checkPermission();
}
catch (Exception e){
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String exceptionAsStrting = sw.toString();
Log.e("CSP", exceptionAsStrting);
e.printStackTrace();
}
finButton = (Button) findViewById(R.id.finButton);
finButton.setOnClickListener(v -> {
try{
String phoneTxt = phoneNumberEditText.getText().toString().trim();
String nameTxt = nameEditText.getText().toString().trim();
String emailTxt = emailEditText.getText().toString().trim();
String groupTxt = groupEditText.getText().toString().trim();
String memoTxt = memoEditText.getText().toString().trim();
String friendInfoTxt = phoneTxt + "-" + nameTxt + "-" + emailTxt + "-" + groupTxt + "-" + memoTxt;
FileOutputStream outstream = openFileOutput("friendList.txt", Activity.MODE_WORLD_WRITEABLE);
outstream.write(friendInfoTxt.getBytes());
outstream.close();
Intent intent = new Intent(v.getContext(), FriendListActivity.class);
startActivity(intent);
} catch (Exception e){
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String exceptionAsStrting = sw.toString();
Log.e("Filesave", exceptionAsStrting);
e.printStackTrace();
Toast.makeText(this.getApplicationContext(), "Save failed.", Toast.LENGTH_SHORT).show();
}
});
}
public void checkPermission(){
if(checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
}
}
}
Try with Context.MODE_APPEND or Context.MODE_PRIVATE instead of Activity.MODE_WORLD_WRITEABLE
Related
I have created a simple Layout to get information from users, and i have java programmed it to get the data and store them in an .JSON format. I took it as a string and saved them into .JSON format. But while returning return jsonObject i get an error.
Here is the code:
public class MainActivity extends AppCompatActivity {
EditText firstname, lastname, username, mail_id, mobile_no, pass;
Button submit;
JSONObject jsonObject = new JSONObject();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String FILE_NAME = "Sample.json";
firstname = (EditText) findViewById(R.id.firstname);
lastname = (EditText) findViewById(R.id.lastname);
username = (EditText) findViewById(R.id.username);
mail_id = (EditText) findViewById(R.id.mail);
mobile_no = (EditText) findViewById(R.id.phone);
pass = (EditText) findViewById(R.id.password);
submit = findViewById(R.id.submit);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
jsonformat();
String userString = jsonObject.toString();
File file = new File(MainActivity.this.getFilesDir(), FILE_NAME);
FileWriter fileWriter;
try {
fileWriter = new FileWriter(file);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write(userString);
bufferedWriter.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}
File file1 = new File(MainActivity.this.getFilesDir(), FILE_NAME);
FileReader fileReader = null;
try {
fileReader = new FileReader(file1);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuilder stringBuilder = new StringBuilder();
String line = null;
try {
line = bufferedReader.readLine();
while (line != null) {
stringBuilder.append(line).append("\n");
line = bufferedReader.readLine();
bufferedReader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
// This responce will have Json Format String
String responce = stringBuilder.toString();
}
});
}
public JSONObject jsonformat()
{
try {
jsonObject.put("fname", firstname); // seems that it's wrong.
jsonObject.put("lname", lastname); // seems that it's wrong.
jsonObject.put("uname", username); // seems that it's wrong.
jsonObject.put("mail", mail_id); // seems that it's wrong.
jsonObject.put("Phone Number", mobile_no); // seems that it's wrong.
jsonObject.put("Password", pass); // seems that it's wrong.
//return jsonObject; // The error -- You can't return jsonObject in here. onCreate method is void method.
} catch (JSONException e) {
e.printStackTrace();
}
return jsonObject;
}
}
Build error:
/home/sim/AndroidStudioProjects/Activity/app/src/main/java/com/example/activity /MainActivity.java:55: error: incompatible types: unexpected return value
return jsonObject;
^
The .JSON file is created as per the program in the directory. But doesn't contain any value in it. just some "id" has been printed.
Dunno where did i make mistake or missed logic. Comment my mistakes.
I think your code contains some wrong logic.
first, you cannot return onCreate method. you should make seperate method to return object. I think that your code don't need return.
Second, you did put "Layout Element instance" to JSONObject.
I cannot understand why you did it.
Anyway, I changed your MainActivity code as following.
So you can made your change in new MainActivity code.
public class MainActivity extends AppCompatActivity {
EditText firstname, lastname, username, mail_id, mobile_no, pass;
Button submit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String FILE_NAME = "Sample.json";
firstname = (EditText) findViewById(R.id.firstname);
lastname = (EditText) findViewById(R.id.lastname);
username = (EditText) findViewById(R.id.username);
mail_id = (EditText) findViewById(R.id.mail);
mobile_no = (EditText) findViewById(R.id.phone);
pass = (EditText) findViewById(R.id.password);
submit = findViewById(R.id.submit);
submit.setOnClickListener(v -> {
JSONObject jsonObject = jsonformat();
String userString = jsonObject.toString();
File file = new File(getFilesDir(), FILE_NAME);
FileWriter fileWriter;
try {
fileWriter = new FileWriter(file);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write(userString);
bufferedWriter.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}
File file1 = new File(this.getFilesDir(), FILE_NAME);
FileReader fileReader = null;
try {
fileReader = new FileReader(file1);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuilder stringBuilder = new StringBuilder();
String line = null;
try {
line = bufferedReader.readLine();
while (line != null) {
stringBuilder.append(line).append("\n");
line = bufferedReader.readLine();
bufferedReader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
// This responce will have Json Format String
String responce = stringBuilder.toString();
});
}
public JSONObject jsonformat() {
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("fname", firstname.getText().toString());
jsonObject.put("lname", lastname.getText().toString());
jsonObject.put("uname", username.getText().toString());
jsonObject.put("mail", mail_id.getText().toString());
jsonObject.put("Phone Number", mobile_no.getText().toString());
jsonObject.put("Password", pass.getText().toString());
} catch (JSONException e) {
e.printStackTrace();
}
return jsonObject;
}
}
Hello I have wrote this code to read my csv and when I click a button I get an output. The thing is the only line that gets printed is the final row of the csv. How can I modify my code so with each and every click I get next line?
``InputStream inputStream;
String[] ids;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView = findViewById(R.id.textView);
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
inputStream = getResources().openRawResource(R.raw.dating);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try{
String csvLine;
while((csvLine = reader.readLine())!=null){
ids = csvLine.split(",");
try{
textView.setText(ids[3]+ids[4]);
}catch (Exception e){
Log.e("Unknown exception", e.toString());
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
Move the:
inputStream = getResources().openRawResource(R.raw.dating);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
out off the OnClickListener.
That's all.
my App saves the text of a multi-line EditView to a text file, but the problem is that if I restart my app, only the last line gets restored. (Perhaps it's also possible that the FileOutputStream only saves the last line, I am not sure ¯_(ツ)_/¯)
Here is my code:
private static final String TAG = "EditDataActivity";
public static String Textfile = "test.txt";
private Button btnSave,btnDelete;
private EditText editable_item;
EditText Zutaten, Zubereitung;
DatabaseHelper mDatabaseHelper;
private String selectedName;
private int selectedID;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_data_layout);
btnSave = (Button) findViewById(R.id.btnSave);
btnDelete = (Button) findViewById(R.id.btnDelete);
editable_item = (EditText) findViewById(R.id.editable_item);
mDatabaseHelper = new DatabaseHelper(this);
Zutaten = (EditText)findViewById(R.id.editText4);
Zubereitung = (EditText)findViewById(R.id.editText2);
Zutaten.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
try{
EditText test = (EditText)findViewById(R.id.editable_item);
String testText = test.getText().toString();
String Textfile2 = testText + ".txt";
EditText field = (EditText)findViewById(R.id.editText4);
String text = field.getText().toString();
FileOutputStream fos = openFileOutput(Textfile2, Context.MODE_PRIVATE);
fos.write(text.getBytes());
fos.close();
}catch (IOException e){
System.out.println("Error");
}
}
});
Intent receivedIntent = getIntent();
selectedID = receivedIntent.getIntExtra("id",-1); //NOTE: -1 is just the default value
selectedName = receivedIntent.getStringExtra("name");
editable_item.setText(selectedName);
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try{
EditText test = (EditText)findViewById(R.id.editable_item);
String testText = test.getText().toString();
String Textfile2 = testText + ".txt";
EditText field = (EditText)findViewById(R.id.editText4);
String text = field.getText().toString();
FileOutputStream fos = openFileOutput(Textfile2, Context.MODE_PRIVATE);
fos.write(text.getBytes());
fos.close();
}catch (IOException e){
System.out.println("Error");
}
Toast.makeText(getApplicationContext(), "Rezept erfolgreich gespeichert!", Toast.LENGTH_SHORT).show();
Intent back = new Intent(EditDataActivity.this, MainActivity.class);
startActivity(back);
String item = editable_item.getText().toString();
if (!item.equals("")) {
mDatabaseHelper.updateName(item, selectedID, selectedName);
} else {
toastMessage("Du musst das Rezept benennen!");
}
}
});
btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try{
EditText test = (EditText)findViewById(R.id.editable_item);
String testText = test.getText().toString();
String Textfile2 = testText + ".txt";
EditText field = (EditText)findViewById(R.id.editText4);
String text = field.getText().toString();
FileOutputStream fos = openFileOutput(Textfile2, Context.MODE_APPEND);
fos.write("".getBytes());
fos.close();
System.out.println("did it");
}catch (IOException e){
System.out.println("Error");
}
Intent back = new Intent(EditDataActivity.this, MainActivity.class);
startActivity(back);
mDatabaseHelper.deleteName(selectedID,selectedName);
editable_item.setText("");
toastMessage("Rezept erfolgreich gelöscht!");
}
});
}
private void toastMessage(String message){
Toast.makeText(this,message, Toast.LENGTH_SHORT).show();
}
public void loadsavedfile(){
try {
EditText test1 = (EditText) findViewById(R.id.editable_item);
String test1Text = test1.getText().toString();
String Textfile2 = test1Text + ".txt";
if (!Textfile2.isEmpty()) {
FileInputStream fis = openFileInput(Textfile2);
BufferedReader reader = new BufferedReader(new InputStreamReader(new DataInputStream(fis)));
String test;
EditText Test = (EditText) findViewById(R.id.editText4);
while ((test = reader.readLine()) != null) {
Test.setText(test);
}
}else{
}
}catch(IOException e){
}
Hope fully you can help me :)
Thanks!
Just do
while ((test = reader.readLine()) != null) {
Test.setText(Test.getText()+"\n" + test);
}
When you had setText(test) only it was replacing the text from the edit text every time the loop ran but you have to append the new text to the last line. A better way to do this would be to create the String first and then set it to EditText as it is better for performance.
StringBuilder str = new StringBuilder();
while((test = reader.readLine()) != null)
str.append('\n' + test);
Test.setText(str.toString());
Hope this solves your problem.
I am trying to read in some data from a text file I created on my SDcard. However, when I am done reading it in, the stringbuilder is still blank. I don't know if it isn't reading the file. I looked on the android device monitor and the fie exists with data in it. It is on my sdcard inside a "Notes" directory. Here is the code.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
welcomeText = (TextView) findViewById(R.id.welcomeText);
userName = (EditText) findViewById(R.id.userName);
submitButton = (Button) findViewById(R.id.submitButton);
password = (EditText) findViewById(R.id.passInput);
viewAll = (Button) findViewById(R.id.viewAll);
submitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
generateNoteOnSD("info", userName.getText().toString() + "," +password.getText().toString() );
}
});
viewAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
File sdCard = Environment.getExternalStorageDirectory();
File file = new File(sdCard, "info");
String line;
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
br.close();
}
catch (IOException e) {
}
welcomeText.setText("Welcome, " + text);
}
});
}
public void generateNoteOnSD(String sFileName, String sBody){
try
{
File root = new File(Environment.getExternalStorageDirectory(), "Notes");
if (!root.exists()) {
root.mkdirs();
}
File gpxfile = new File(root, sFileName);
FileWriter writer = new FileWriter(gpxfile);
writer.append(sBody);
writer.flush();
writer.close();
Toast.makeText(this, "Saved", Toast.LENGTH_SHORT).show();
}
catch(IOException e)
{
e.printStackTrace();
}
}
Try to change like below
viewAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String fileName = "/Notes/info";
File myFile = new File(baseDir + File.separator + fileName);
try {
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
String text = "";
String aDataRow = "";
while ((aDataRow = myReader.readLine()) != null) {
text += aDataRow + "\n";
}
}
catch (IOException e) {
}
welcomeText.setText("Welcome, " + text);
}
});
I have a read and write operation at a android app. On onCreate, a file will be read and display it to an editext and can be editted. When the save is pressed, the data will be written to the same file that will be read on onCreate. But I got an error. No such file in directory. I don't get it. I'm creating the file when the save button is pressed. Any ideas?
Java code:
EditText Name;
EditText Age;
EditText Height;
EditText Weight;
EditText MedHistory;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_medicalhistory);
Name = (EditText) findViewById(R.id.medhistName);
Age = (EditText) findViewById(R.id.medhistAge);
Height = (EditText) findViewById(R.id.medhistHeight);
Weight = (EditText) findViewById(R.id.medhistWeight);
MedHistory = (EditText) findViewById(R.id.MedHist);
int i = 0;
String MedHistData[] = new String[5];
try {
File myFile = new File("/data/data/Project.Package.Structure/files/MedicalHistory.txt");
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(new InputStreamReader(fIn));
String aDataRow = "";
while ((aDataRow = myReader.readLine()) != null)
{
MedHistData[i] = aDataRow;
i++;
}
i = 0;
Name.setText(MedHistData[0]);
Age.setText(MedHistData[1]);
Height.setText(MedHistData[2]);
Weight.setText(MedHistData[3]);
MedHistory.setText(MedHistData[4]);
myReader.close();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
Button Save = (Button) findViewById(R.id.SaveBtn);
Save.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try {
File myFile = new File("/data/data/Project.Package.Structure/files/MedicalHistory.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(Name.getText() + "\n");
myOutWriter.append(Age.getText() + "\n");
myOutWriter.append(Height.getText() + "\n");
myOutWriter.append(Weight.getText() + "\n");
myOutWriter.append(MedHistory.getText());
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),
"Medical History Saved'",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
});
}
You should use openFileInput() method to open file for reading and openFileOutput() for writing. These functions return a FileInputStream and FileOutputStream respectively.
My guess: you don't have write access to the file.
You only can access specific folders for writing in android.
Have a look at
http://developer.android.com/guide/topics/data/data-storage.html#filesInternal
They have a simple example on how to write a text file.