Unable to read/write to file in android - java

I'm trying to get my app to write text into a text file from an EditText and read from it into a TextView. It never updated the TextView earlier and now the app is crashing. Any advise would be very appreciated!
public class MainActivity extends Activity implements OnClickListener {
String file = Environment.getExternalStorageDirectory() + "/CSCI598.txt";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button rea = (Button) findViewById(R.id.reads1);
rea.setOnClickListener(this);
Button ap = (Button) findViewById(R.id.appends1);
ap.setOnClickListener(this);
}
private void toast(String text)
{
Context context = getApplicationContext();
Toast toast = Toast.makeText(context, text, Toast.LENGTH_LONG);
toast.show();
}
#SuppressWarnings("resource")
#Override
public void onClick(View v) {
TextView tv=(TextView)findViewById(R.id.textView1);
EditText et=(EditText)findViewById(R.id.editText1);
switch(v.getId()) {
case R.id.reads1:
try
{
FileInputStream fis = new FileInputStream(file);
BufferedReader bfr = new BufferedReader(new InputStreamReader(fis));
String in;
StringBuffer stringBuffer = new StringBuffer();
while ((in = bfr.readLine()) != null) {
stringBuffer.append(in + "\n");
}
tv.setText(stringBuffer.toString());
toast("File successfully loaded.");
}
catch (Exception ex)
{
toast("Error loading file: " + ex.getLocalizedMessage());
}
break;
case R.id.appends1:
String txt=et.getText().toString();
try
{
FileWriter writer = new FileWriter(file);
writer.write(txt);
writer.flush();
writer.close();
toast("File successfully saved.");
}
catch (Exception ex)
{
toast("Error saving file: " + ex.getLocalizedMessage());
}
break;
}
}
}

Get the sdcard directory using Environment.getExternalStorageDirectory(). Try changing this line in you code:
String file = "sdcard/CSCI598.txt";
With:
String file = Environment.getExternalStorageDirectory() + "/CSCI598.txt";
Also, as #Yahya mentioned make sure you have this permission in your android manifest file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
If this doesn't work. Try reading the file like this:
FileReader fr = new FileReader(file);
BufferedReader inputReader = new BufferedReader(fr);
Then use your while loop as it is right now.
Write the file like this
FileWriter out = new FileWriter(file, true);
out.write(txt + "\n");
out.close();

Provide crash log.
Have you given sdcard read write permission in your manifest xml file.
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
Instead of using hard coded path like String file = "sdcard/CSCI598.txt"; use below
String file = Environment.getExternalStorageDirectory() + "/CSCI598.txt";
As you are using emulator have have you alot sd card space while creating AVD

Related

create an XML file to store the input in my Android app

I work with Android Studio and have two input values ​​and these should be saved in an XML file. How do I create an XML file in my App to save my input? I already tried it with the XmlSerializer but I don't understand where I can find the generated file in my app
public class MainActivity extends AppCompatActivity {
EditText mEditTextG;
EditText mEditTextS;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void send (View v) throws FileNotFoundException {
mEditTextG = findViewById(R.id.editTextGERID);
String gerID = mEditTextG.getText().toString();
mEditTextS = findViewById(R.id.editTextSollAstID);
String sollID = mEditTextS.getText().toString();
//create XML File for Storage
String filename = "device.xml";
XmlSerializer serializer = Xml.newSerializer();
StringWriter writer = new StringWriter();
try {
serializer.setOutput(writer);
serializer.startDocument("UTF-8", true);
serializer.startTag("", "device");
serializer.startTag("", "GERID");
serializer.text(gerID);
serializer.endTag("","GERID");
serializer.startTag("", "SollAstID");
serializer.text(sollID);
serializer.endTag("","SollAstID");
serializer.endTag("","device");
serializer.endDocument();
String result = writer.toString();
FileOutputStream fos = this.openFileOutput(filename, Context.MODE_PRIVATE);
fos.write(result.getBytes(),0,result.length());
fos.close();
Toast.makeText(this,"SollID: "+ sollID ,Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
}
This is how the XML file should look like
The XML file should also be able to be displayed or read in later in the program.
Thanks in advance

FileWrite not creating new file Android Studio, getting 'java.io.FileNotFoundException: file.py: open failed: EROFS (Read-only file system)'

so i've been trying to run a simple python script in java using the runtime method. It worked well outside of android studio, but in Andorid studio I keet getting this error java.io.FileNotFoundException: file.py: open failed: EROFS (Read-only file system)'.
I know that this isn't the most effective way to run a python script through Java, but please help me out. I don't know what permissions to change in order for new script to be written.
Heres my full code:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView resultstv = (TextView)findViewById(R.id.resultsTV);
Button solvebtn = (Button)findViewById(R.id.solvebtn);
final EditText enterWordTv = (EditText)findViewById(R.id.enterWordET);
solvebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
resultstv.setText(anagram(getEnterWordTv(enterWordTv)).toString());
}
});
}
public String getEnterWordTv(EditText inputFU) {
String finWord = inputFU.getText().toString();
return(finWord);
}
static ArrayList<String> anagram(Int num){
ArrayList<String> results = new ArrayList<String>();
try {
String mainPrg = "import sys\nprint(sys.argv[1])";
BufferedWriter out = new BufferedWriter(new FileWriter("AnagremSOlver.py"));
out.write(mainPrg);
out.close();
String number = num;
Process p = Runtime.getRuntime().exec("python3 AnagremSOlver.py " + number);
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String ret;
while ((ret = in.readLine()) != null){
results.add(ret);
}
System.out.println(results);
} catch (Exception e){
System.out.println(e);
}
return(results);
}
}
Other answers from other places have told me to update the permissions in AndroidManifest.xml by adding <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> but having added it, I still get the same problem.

Creating and sending a file

I am trying to create file in internal storage and then send it via email in Android.
However, I still get file not found or similar errors.
Please, help!
String FILENAME = "TestFile.txt";
Sending file by button click
btnSendFile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
File gpxfile = getFile();
Uri path = Uri.fromFile(gpxfile);
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("message/rfc822");
Context context = v.getContext();
String email = "MYEMAILHERE";
i.putExtra(Intent.EXTRA_EMAIL, new String[]{email});
i.putExtra(Intent.EXTRA_SUBJECT, "Subject");
i.putExtra(Intent.EXTRA_TEXT, "Text");
i.putExtra(Intent.EXTRA_STREAM, path);
context.startActivity(Intent.createChooser(i, context.getString("Sending...")));
}
});
}
Creating file in internal storage
private void createTestFile() {
try {
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_APPEND);
fos.write("Your content".getBytes());
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Get file function. Return File if file exists
private File getFile() {
return new File(getFilesDir() + "/" + FILENAME);
}
Maybe you need to make
Context.openFileOutput(FILENAME, Context.MODE_APPEND);
Instead of that one you used? I think someone had similiar problem over here: android what is wrong with openFileOutput?

AutoCompleteTextView is not showing strings loaded from the Internal Storage

I want make a AutoCompleteTextview which will load previously saved suggestion from the internal storage. I successfully loaded the strings from the internal storage to a string array(i used logging to check....).
then as i loaded the string array to an adapter and set the adapter to the AutoCompleteTextview, after that the AutoCompleteTextview is not showing the suggestion-strings which i loaded from the Internal Storage but it is showing the suggestion-string(s) which i loaded to the string array at runtime.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//this is the array where i am trying to save my data into
loadedString=new String[1];
loadedString[0]="the pre-loaded String"
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, loadedString);
atcv = (AutoCompleteTextView) findViewById(R.id.autocomplete);
int objectCounter = 0;
try {
FileInputStream fis = this.openFileInput(FILENAME);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
String temp;
while ((temp = br.readLine()) != null) {
//here i am calculating the lines of my data-file
//as 1 line contains 1 string object
//so that i can initialize the string array
objectCounter++;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//intializing the array
// objectCounter+1 and index =1 because i loaded an object before
loadedString = new String[objectCounter+1];
int index = 1;
try {
FileInputStream fis = this.openFileInput(FILENAME);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
String temp;
while ((temp = br.readLine()) != null) {
loadedString[index] = temp;
index++;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();
atcv.setAdapter(adapter);
atcv.setThreshold(1);
}
this is the method i am using to save the data
public void saver(View view) {
String string;
if(actv.getText()!=null){
advice = advices.getText().toString();}
advice=advice+"\n";
try{
FileOutputStream fos = openFileOutput(FILENAME, context.MODE_APPEND);
fos.write(advice.getBytes());
fos.close();
Toast.makeText(this, "File saved" , Toast.LENGTH_LONG).show();
}
catch (Exception e){
Toast.makeText(this, "File could not be saved", Toast.LENGTH_LONG).show();
}
Please help. Note that i used notifyDataSetChanged() method. I will be really grateful.
Note that i used notifyDataSetChanged() method
In your case, that is useless. The ArrayAdapter will continue to use your old String[1]. It does not know about your new String[].
First, do not do disk I/O on the main application thread, as you are doing here. Use some form of background operation, like an AsyncTask.
Second, do not read the data in twice, as that is twice as slow for the user. For example, you could use a data structure like ArrayList<String>, which can expand its size on the fly.
Then, do not create the ArrayAdapter until after you have loaded the strings.

I can't save audio file after recordings in Android application development

After working on a sound recorder, I discovered that the files are not saving.. But the code is right.. With error that directory is not found.. But I created a script to make a new directory if it's not available.. But it's not working.. I have included the code here.. Someone should just help...
private String getFilename() {
String filepath = Environment.getExternalStorageDirectory().getPath();
File file = new File(filepath, AUDIO_RECORDER_FOLDER);
if (!file.exists()) {
file.mkdirs();
}
return (file.getAbsolutePath() + "/" + System.currentTimeMillis() + AUDIO_RECORDER_FILE_EXT_WAV);
}
private String getTempFilename() {
String filepath = Environment.getExternalStorageDirectory().getPath();
File file = new File(filepath, AUDIO_RECORDER_FOLDER);
if (!file.exists()) {
file.mkdirs();
}
File tempFile = new File(filepath, AUDIO_RECORDER_TEMP_FILE);
if (tempFile.exists())
tempFile.delete();
return (file.getAbsolutePath() + "/" + AUDIO_RECORDER_TEMP_FILE);
}
This was how i did and i works for me
//uses-permission android:name="android.permission.RECORD_AUDIO"
//uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
private MediaRecorder mr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mr = new MediaRecorder();
mr.setAudioSource(MediaRecorder.AudioSource.MIC);
mr.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mr.setOutputFile("/sdcard/_name.3gp");
mr.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
try{
mr.prepare();
mr.start();
}
catch (Exception ex){
}
}
public void stopAndSave(View v){
try{
mr.stop();
mr.release();
}
catch (Exception ex){
}
}
Have you added user permission to use external storage in app
It's done like this in AndroidManifest file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Categories

Resources