Empty saved text file - java

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);

Related

Line Break in index of ArrayList

I am reading a text line with FileInputStream at one of its index in ArrayList which contains a Line Break and using it to display in TextView. But problem is that \n is being displayed instead of making a line break.
I also checked Whether an Arraylist can contain "\n" and it worked exactly how I wanted
but only when am declaring it within my class like -data.add(1,"xyz\nxyz"). but the same is not working when I read line from text file.
public class MainActivity extends AppCompatActivity {
public static ArrayList<String> data;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
data=new ArrayList<>();
tv1=findViewById(R.id.text1);
tv2=findViewById(R.id.text2);
Reading text file
File fi = new File(Environment.getExternalStorageDirectory(), "Path /test.txt");
if (fi.exists()){
try {
FileInputStream inputStream = new FileInputStream(fi.getPath());
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line = bufferedReader.readLine();
while (line != null) {
data.add(0,line);
line = bufferedReader.readLine();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Displaying elements of ArrayList in TextView
tv1.setText(data.get(0)); // TextView display "\n" instead of line break.
data.add(1,"\n\nhello here is a\nline break"); // This works fine as expected, text is displayed in new line
tv2.setText(data.get(1));

renameTo() not working for renaming images and returns false

I have an image gallery app, I am trying to rename images using renameTo() method but it is not able to change the name of files and returns false. I read many questions on SO for renaming files and all of them suggest for only one method for renaming files - renameTo(). Strangely enough, many questions talk about how it is not a good method for renaming files in various conditions.
Is there any other way of renaming files in android? If I use this way only, how to make it work?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_gallery);
alert = new AlertDialog.Builder(this);
etRenameFile = new EditText(getApplicationContext());
alert.setTitle("Do you want to rename the file?");
alert.setMessage(" ");
alert.setView(etRenameFile);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, int whichButton) {
renameFileAlert();
adapter.notifyDataSetChanged();
}
});
alert.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// what ever you want to do with No option.
}
});
private void renameFileAlert(){
String renameFile = etRenameFile.getText().toString();
Log.v(TAG, renameFile + " another");
String filename= al_images.get(int_position).getAl_imagepath().get(fileIndex);
File oldFilePath = new File(al_images.get(int_position).getAl_imagepath().get(fileIndex));
Log.v(TAG,oldFilePath.toString());
// Log.d("OLDFILEPATH", oldFilePath.toString()); // prints the correct path of the file being selected
x = al_images.get(int_position).getAl_imagepath().get(fileIndex);
File renamedFile = new File(x.replace(filename, renameFile));
Log.v(TAG, renamedFile.toString() + " new name"); //prints new name of the file being entered
// Log.d("NEWFILE", renamedFile.toString());
boolean renamed = oldFilePath.renameTo(renamedFile);
if(renamed){
Log.v(TAG, "rename done");
} else Log.v(TAG, "failed");
notifyMediaStoreScanner(renamedFile);
}
public final void notifyMediaStoreScanner(File file) {
// try {
// MediaStore.Images.Media.insertImage(getBaseContext().getContentResolver(),
// file.getAbsolutePath(), file.getName(), null);
getBaseContext().sendBroadcast(new Intent(
Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
getBaseContext().sendBroadcast(new Intent(
Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
// } catch (FileNotFoundException e) {
// e.printStackTrace();
// }
}
What are you trying to rename it to exactly? renameTo() will only return true if and only if the renaming succeeded; returning false otherwise.

Write and Read Android

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

How to use ArrayList<String> for saving/retrieving in sharedpreferences

I compile the list: titleList.add(0, title), apply it in sharedpreferences: prefs.putString(TITLES, title).apply() and now need to retrieve it.
I have looked at a lot of the solutions here and none seem to fit my problem well.
The program is suppose to take text a user inputs and save it using SharedPreferences, so it can be used in a ListActivity later. This list is currently an ArrayList (I believe I need it in an array list because I am using AutoCompleteEditText for suggestions from the array list, so I need the adapter).
Based on the above logic,prefs is a sharedpreference object full of string objects. I have tried using prefs.getAll().values.toArray(new String[0...100]). I found that in an "Android" book. It works, but only gets the first item. After trying methods, Set<?> and a few others, that was the method that got anything at all.
It is all I need to have the program working PERFECTLY. Can someone please help getting this list to save in sharedpreferences, retrieving it as a complete, split, list (that can be indexed) and passing it to a ListActivity?
ArrayList<String> titleList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_make_lyric);
autoCompleteAdapter = new ArrayAdapter<>(
this,
android.R.layout.simple_list_item_1,
titleList
);
lyricTitle.setAdapter(autoCompleteAdapter);
lyricTitle.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// load in song when selected from auto-complete list
lyricHolder.setText(openSongFile(lyricTitle.getText().toString()));
}
});
saveBtn = (Button) findViewById(R.id.saveBtn);
saveBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
performSave();
}
});
titlePref = getSharedPreferences(titlePrefFile, MODE_PRIVATE);
//titleList = titlePref.getAll().values().toArray();
}
private void performSave() {
String title = lyricTitle.getText().toString();
String song = lyricHolder.getText().toString();
if(!areFieldsNull(title, song)) {
saveSongFile(title, song);
warnSave.show();
}
else
warnEmpty.show();
}
private void saveSongFile(String title, String song) {
BufferedWriter bufferWriter = null;
try {
FileOutputStream fos = openFileOutput(title, Context.MODE_PRIVATE);
bufferWriter = new BufferedWriter(new OutputStreamWriter(fos));
bufferWriter.write(song);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
bufferWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//update song title list adapter
autoCompleteAdapter = new ArrayAdapter<>(
this,
android.R.layout.simple_list_item_1,
titleList
);
lyricTitle.setAdapter(autoCompleteAdapter);
titleList.add(0,title);
prefEditor = titlePref.edit();
prefEditor.putString("titleList", title).apply();
}
Sorry, formatting the code just wont work for me.
Thank you and Happy Holidays!
I think you need to use ObjectSerializer.
Save :
ArrayList<String> strings = new ArrayList<String>();
string.add("Hello!");
//save list into SP
SharedPreferences prefs = getSharedPreferences(SHARED_PREFS_FILE, Context.MODE_PRIVATE);
Editor editor = prefs.edit();
try {
editor.putString("LIST", ObjectSerializer.serialize(strings));
} catch (IOException e) {
e.printStackTrace();
}
editor.commit();
Restore :
// load list from preference
SharedPreferences prefs = getSharedPreferences(SHARED_PREFS_FILE, Context.MODE_PRIVATE);
ArrayList<String> strings = new ArrayList<String>();
try {
strings = (ArrayList<String>) ObjectSerializer.deserialize(prefs.getString("LIST", ObjectSerializer.serialize(new ArrayList<String>())));
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Or use parcelable wrapping to save/retrieve your data
Sergey's answer may be just fine. Also, take a look at JPM's answer and class, on this thread. I used it yesterday.
So, using JPM's class, here's writing myBigArrayList:
// write data file for later use
String ser = SerializeObject.objectToString(myBigArrayList);
if (ser != null && !ser.equalsIgnoreCase("")) {
SerializeObject.WriteSettings(c, ser, "myobject.dat");
} else {
SerializeObject.WriteSettings(c, "", "myobject.dat");
}
And, here's a method I adapted, that returns a complete, intact arraylist:
private ArrayList<yabbaData> getYabbaData() {
String ser = SerializeObject.ReadSettings(getActivity().getApplicationContext(), "myobject.dat");
ArrayList<yabbaData> give = null;
if (ser != null && !ser.equalsIgnoreCase("")) {
Object obj = SerializeObject.stringToObject(ser);
// Then cast it to your object and
if (obj instanceof ArrayList) {
// Do something
give = (ArrayList<yabbaData>) obj;
}
}
return give;
}
In the write, I use c as my application context, where I had passed in getApplicationContext().
In the read, I used getActivity().getApplicationContext() because I was in a fragment. Sub in String for my yabbaData object, in ArrayList, and I think it's ready to use.

How to store the .txt file in SQLite Android

I created application of write and read file. when i click button ,my file is write and also read the file on the same button click.I want as and when my file is write , that file is save it into SQLite.I'm surfing lot of on the net but can't find proper source or ideas how to do this.And that file is compare with input String something like "code" . If this input_String is match with that file which is store in the SQLite database , if match user can't go ahead for the further process.I would appreciate if anybody out there is capable of giving me some advice on this one and I hope other people find this helpful too.Here is my code.Thanks in Advanced.
The Activity class
public class Write extends Activity {
/** Called when the activity is first created. */
EditText myText;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.abc);
myText = (EditText) findViewById(R.id.myText);
Button createButton = (Button) findViewById(R.id.btnCreate);
Button readButton = (Button) findViewById(R.id.btnRead);
createButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
createFile(myText.getText().toString());
myText.setText("");
readFile();
}
});
}
private void createFile(String Text)
{
FileOutputStream fos = null;
try
{
fos = openFileOutput("mynote.txt", MODE_PRIVATE);
fos.write(Text.getBytes());
Toast.makeText(getApplicationContext(), "File created succesfully",
Toast.LENGTH_SHORT).show();
}
catch (FileNotFoundException e)
{
Log.e("CreateFile", e.getLocalizedMessage());
}
catch (IOException e)
{
Log.e("CreateFile", e.getLocalizedMessage());
}
finally
{
if (fos != null)
{
try
{
// drain the stream
fos.flush();
fos.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
And the DataBase_Adapter code
//Table Name
public static final String TABLE_NAME_CODE="code_table";
//Colum,n Names
public static final String KEY_CODE_ID="ID";
public static final String KEY_CODE_NAME="USERNAME";
//Table Create Statement
public static final String DATABASE_CREATE_CODE = "CREATE TABLE "+TABLE_NAME_CODE+" ("+KEY_CODE_ID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+KEY_CODE_NAME+"TEXT)";
//Insert Code in Database code_table
public void saveCode(String strKey_Code)
{
ContentValues newValues = new ContentValues();
// Assign values for each row.
newValues.put(KEY_CODE_NAME , strKey_Code);
// Insert the row into your table
db.insert(TABLE_NAME_CODE, null, newValues);
}
The approach you have taken could be improved a little bit, consider storing in the database only the name of the files, you already have the files saved, right? why store their content again in the database?

Categories

Resources