I found some interesting codes online. And I copy paste it into my AIDE or Android IDE. It hasn't detected any error so far but it just only saves in one file name in all files I saved. And the older file saved will be replaced by a newer one.
public class MainActivity extends Activity {
public EditText editText;
public TextView textView;
public Button save, load;
public String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/MyFiles";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
editText = (EditText) findViewById(R.id.edit);
textView = (TextView) findViewById(R.id.text);
save = (Button) findViewById(R.id.save);
File dir = new File(path);
dir.mkdirs();
}
public void buttonSave (View view)
{
File file = new File (path + "/saved.txt");
String [] saveText = String.valueOf(editText.getText()).split(System.getProperty("line.separator"));
editText.setText("");
Toast.makeText(getApplicationContext(), "Saved", Toast.LENGTH_LONG).show();
Save (file, saveText);
}
}
public static void Save(File file, String[] data)
{
FileOutputStream fos = null;
try
{
fos = new FileOutputStream(file);
}
catch (FileNotFoundException e) {e.printStackTrace();}
try
{
try
{
for (int i = 0; i<data.length; i++)
{
fos.write(data[i].getBytes());
if (i < data.length-1)
{
fos.write("\n".getBytes());
}
}
}
catch (IOException e) {e.printStackTrace();}
}
finally
{
try
{
fos.close();
}
catch (IOException e) {e.printStackTrace();}
}
}
I am planning to make an edittext and name it as yourfilename and that will be its name after I saved it to prevent overwriting files. But the problem is I don't know where to add codes and for so many codes there. I am having doubt of which codes to be used.
By the way, I am very new to this so I do not know much about it.
Thank you.
Check if this helps you.
public void buttonSave(View view) {
String fileName = editText.getText().toString();
File file = new File(path + "/" + fileName + ".txt");
String[] saveText = String.valueOf(editText.getText()).split(System.getProperty("line.separator"));
editText.setText("");
Toast.makeText(getApplicationContext(), "Saved", Toast.LENGTH_LONG).show();
Save(file, saveText);
}
Related
Hello I tried to make an app for displaying quote in Android Studio.
But I got stuck when reading.
I created an "ArrayList" with my custom class Quotes.
I seems to work ok when writing the ArrayList to the file, but when reading from it the size of ArrayList is 0.
public class SaveQuote extends AppCompatActivity {
EditText editTextQuote;
EditText editTextAuthor;
Button btnSave;
ArrayList<Quote> arrQuo = new ArrayList<>();
public static ArrayList<Quote> arrayListQuotesSave;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_save_quote);
init();
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String quote = editTextQuote.getText().toString();
String author =editTextAuthor.getText().toString();
addQuote(quote,author);
}
});
}
private void init(){
editTextQuote = findViewById(R.id.editTextQuote);
editTextAuthor = findViewById(R.id.editTextAuthor);
btnSave = findViewById(R.id.buttonSave);
arrayListQuotesSave = new ArrayList<>();
}
private void addQuote(String quote, String author){
Quote q = new Quote(quote, author);
arrQuo.add(q);
String path = this.getFilesDir().toString();
try {
FileOutputStream fos = openFileOutput("Quotes.txt",MODE_APPEND);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(arrQuo);// when I write size = 1
oos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileInputStream fis = openFileInput("Quotes.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
arrQuo =(ArrayList<Quote>) ois.readObject();
ois.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
I tried to passe a context and call the method openFileOutput on the context
so like this:
enter code here
FileOutputStream fs = context.openFileOutput("Quotes.txt", Context.MODE_PRIVATE);
enter code here
public class SaveQuote extends AppCompatActivity {
EditText editTextQuote;
EditText editTextAuthor;
Button btnSave;
ArrayList<Quote> arrQuo = new ArrayList<>();
public static ArrayList<Quote> arrayListQuotesSave;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_save_quote);
init();
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String quote = editTextQuote.getText().toString();
String author =editTextAuthor.getText().toString();
if(quote.isEmpty() || author.isEmpty()){
Toast.makeText(SaveQuote.this,"Fill all fields",Toast.LENGTH_SHORT).show();
}else {
writeToFile(SaveQuote.this, quote, author);
Toast.makeText(SaveQuote.this,"The quote was saved",Toast.LENGTH_SHORT).show();
}
}
});
}
private void init(){
editTextQuote = findViewById(R.id.editTextQuote);
editTextAuthor = findViewById(R.id.editTextAuthor);
btnSave = findViewById(R.id.buttonSave);
arrayListQuotesSave = new ArrayList<>();
}
private void writeToFile(Context context,String quote,String author) {
Quote q = new Quote(quote,author);
MainActivity.arrayListQuotesMain.add(q);
Integer size = MainActivity.arrayListQuotesMain.size();
Log.v("Added","arrayListQuotesMain size is = "+size.toString());
try {
FileOutputStream fs = context.openFileOutput("Quotes.txt", Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fs);
oos.writeObject(MainActivity.arrayListQuotesMain);
oos.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
editTextQuote.setText("");
editTextAuthor.setText("");
}
}
this is my code I and I want to save this bitmap on my internal storage. The public boolean saveImageToInternalStorage is a code from google but I don't know how to use it. when I touch button2 follow the button1 action.
public class MainActivity extends Activity implements OnClickListener {
Button btn, btn1;
SurfaceView sv;
Bitmap bitmap;
Canvas canvas;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn=(Button)findViewById(R.id.button1);
btn1=(Button)findViewById(R.id.button2);
sv=(SurfaceView)findViewById(R.id.surfaceView1);
btn.setOnClickListener(this);
btn1.setOnClickListener(this);
bitmap=BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
}
#Override
public void onClick(View v) {
canvas=sv.getHolder().lockCanvas();
if(canvas==null) return;
canvas.drawBitmap(bitmap, 100, 100, null);
sv.getHolder().unlockCanvasAndPost(canvas);
}
public boolean saveImageToInternalStorage(Bitmap image) {
try {
// Use the compress method on the Bitmap object to write image to
// the OutputStream
FileOutputStream fos = openFileOutput("desiredFilename.png", Context.MODE_PRIVATE);
// Writing the bitmap to the output stream
image.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
return true;
} catch (Exception e) {
Log.e("saveToInternalStorage()", e.getMessage());
return false;
}
}
}
To Save your bitmap in sdcard use the following code
Store Image
private void storeImage(Bitmap image) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
Log.d(TAG,
"Error creating media file, check storage permissions: ");// e.getMessage());
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
image.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
}
To Get the Path for Image Storage
/** Create a File for saving an image or video */
private File getOutputMediaFile(){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStorageDirectory()
+ "/Android/data/"
+ getApplicationContext().getPackageName()
+ "/Files");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date());
File mediaFile;
String mImageName="MI_"+ timeStamp +".jpg";
mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);
return mediaFile;
}
EDIT
From Your comments i have edited the onclick view in this the button1 and button2 functions will be executed separately.
public onClick(View v){
switch(v.getId()){
case R.id.button1:
//Your button 1 function
break;
case R.id. button2:
//Your button 2 function
break;
}
}
private static void SaveImage(Bitmap finalBitmap) {
String root = Environment.getExternalStorageDirectory().getAbsolutePath();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
String fname = "Image-"+ o +".jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Modify onClick() as follows:
#Override
public void onClick(View v) {
if(v == btn) {
canvas=sv.getHolder().lockCanvas();
if(canvas!=null) {
canvas.drawBitmap(bitmap, 100, 100, null);
sv.getHolder().unlockCanvasAndPost(canvas);
}
} else if(v == btn1) {
saveBitmapToInternalStorage(bitmap);
}
}
There are several ways to enforce that btn must be pressed before btn1 so that the bitmap is painted before you attempt to save it.
I suggest that you initially disable btn1, and that you enable it when btn is clicked, like this:
if(v == btn) {
...
btn1.setEnabled(true);
}
To save file into directory
public static Uri saveImageToInternalStorage(Context mContext, Bitmap bitmap){
String mTimeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date());
String mImageName = "snap_"+mTimeStamp+".jpg";
ContextWrapper wrapper = new ContextWrapper(mContext);
File file = wrapper.getDir("Images",MODE_PRIVATE);
file = new File(file, "snap_"+ mImageName+".jpg");
try{
OutputStream stream = null;
stream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG,100,stream);
stream.flush();
stream.close();
}catch (IOException e)
{
e.printStackTrace();
}
Uri mImageUri = Uri.parse(file.getAbsolutePath());
return mImageUri;
}
required permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
You might be able to use the following for decoding, compressing and saving an image:
#Override
public void onClick(View view) {
onItemSelected1();
InputStream image_stream = null;
try {
image_stream = getContentResolver().openInputStream(myUri);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Bitmap image= BitmapFactory.decodeStream(image_stream );
// path to sd card
File path=Environment.getExternalStorageDirectory();
//create a file
File dir=new File(path+"/ComDec/");
dir.mkdirs();
Date date=new Date();
File file=new File(dir,date+".jpg");
OutputStream out=null;
try{
out=new FileOutputStream(file);
image.compress(format,size,out);
out.flush();
out.close();
MediaStore.Images.Media.insertImage(getContentResolver(), image," yourTitle "," yourDescription");
image=null;
}
catch (IOException e)
{
e.printStackTrace();
}
Toast.makeText(SecondActivity.this,"Image Save Successfully",Toast.LENGTH_LONG).show();
}
});
I want to play a decoded string to audio file.
The string is received from another activity, but mediaPlayer shows null. How can I get and set the path in media.create()?
public class AAudio extends AppCompatActivity {
Button play_audio;
MediaPlayer mediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_aaudio);
String recieve_file = getIntent().getStringExtra("audio_file");
play_audio = findViewById(R.id.textShow);
byte[] decoded = Base64.decode(recieve_file, 0);
String fileName = String.valueOf(decoded);
Log.e("~~~~~~~~ Decoded: ", Arrays.toString(decoded));
try {
String root = Environment.getExternalStorageDirectory().getPath();
File myDir = new File(root, "/kaushlya/mp3");
String path = String.valueOf(myDir);
myDir.mkdirs();
String audioName = "Advicory.mp3";
File file = new File(myDir, audioName);
FileOutputStream os = null;
try {
os = new FileOutputStream(file, true);
os.write(decoded);
os.close();
**mediaPlayer = MediaPlayer.create(this, Uri.parse(Uri.parse(root)+path+fileName));
mediaPlayer.setLooping(true);**
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
catch (Exception e) {
e.printStackTrace();
}
play_audio.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaPlayer.start();
}
});
}
}
I have created a file chooser within the ListActivity, which lists and allows you to select a file within the TravelLogs directory within the internal storage of my device.
The Objective:
I am looking to display text from the .txt file I chose from my file chooser within a TextView, from within dispText within the activity_list.xml file.
Any suggestions or resources? I have been through every tutorial on the topic and must be misunderstanding.
Updated to the most current code as of Nov27 #1226pm pst
public class ListActivity extends AppCompatActivity {
TextView dispText;
Button buttonOpenDialog;
TextView textFolder;
String KEY_TEXTPSS = "TEXTPSS";
static final int CUSTOM_DIALOG_ID = 0;
ListView dialog_ListView;
File root;
File curFolder;
private List<String> fileList = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
buttonOpenDialog = (Button) findViewById(R.id.opendialog);
buttonOpenDialog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showDialog(CUSTOM_DIALOG_ID);
}
});
root = new File(Environment.getExternalStorageDirectory(), "TravelLogs");
curFolder = root;
dispText = (TextView) findViewById(R.id.text_file_data);
}
public String getTextFileData(String fileName) {
StringBuilder text = new StringBuilder();
Log.d("jason", "fileName: " + fileName );
try {
FileInputStream fIS = new FileInputStream(fileName);
InputStreamReader isr = new InputStreamReader(fIS, "UTF-8");
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
text.append(line + '\n');
}
br.close();
} catch (IOException e) {
text.append("IOException: " + e.getMessage() + "\n");
Log.e("Error!", "Error occured while reading text file from Internal Storage!");
}
return text.toString();
}
#Override
protected Dialog onCreateDialog(int id) {
Dialog dialog = null;
switch (id) {
case CUSTOM_DIALOG_ID:
dialog = new Dialog(ListActivity.this);
dialog.setContentView(R.layout.dialoglayout);
dialog.setTitle("Select Log");
dialog.setCancelable(true);
dialog.setCanceledOnTouchOutside(true);
textFolder = (TextView) dialog.findViewById(R.id.folder);
dialog_ListView = (ListView) dialog.findViewById(R.id.dialoglist);
dialog_ListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d("jason", "fileName: " + fileName );
File selected = new File(fileList.get(position));
if(selected.isDirectory()) {
ListDir(selected);
} else {
Toast.makeText(ListActivity.this, selected.toString() + " selected",
Toast.LENGTH_LONG).show();
dismissDialog(CUSTOM_DIALOG_ID);
String text = getTextFileData(selected.getAbsolutePath());
Toast.makeText(ListActivity.this, text.toString() + " line",
Toast.LENGTH_LONG).show();
}
}
});
break;
}
return dialog;
}
#Override
protected void onPrepareDialog(int id, Dialog dialog) {
super.onPrepareDialog(id, dialog);
switch (id) {
case CUSTOM_DIALOG_ID:
ListDir(curFolder);
break;
}
}
void ListDir(File f) {
curFolder = f;
textFolder.setText(f.getPath());
File[] files = f.listFiles();
fileList.clear();
for(File file : files) {
fileList.add(file.getPath());
}
ArrayAdapter<String> directoryList = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, fileList);
dialog_ListView.setAdapter(directoryList);
}
#Override
public void onBackPressed()
{
super.onBackPressed();
startActivity(new Intent(ListActivity.this, MainActivity.class));
finish();
}
#Override
public boolean onSupportNavigateUp(){
startActivity(new Intent(ListActivity.this, MainActivity.class));
finish();
return true;
}
}
FileInputStream fIS = getApplicationContext().openFileInput(fileName);
Change to
FileInputStream fIS = new FileInputStream(fileName);
Further i consider this post solved.
For further detail questions make another post to solve them.
I am making an app where I have my school balance set and can press dedicated buttons to take away certain amounts depending on what I purchase. I am having trouble with the balance. I have a way of updating it to what I want, however after I terminate the application I want it to stay the same in a TextView. I so far was able to make it save it to a file, or at least I hope I was, with the help of a video.
How could I on opening the app read the text file and set the TextView equal to what is in the file?
submitBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String submitAmount = amountEnter.getText().toString();
balance.setText(submitAmount);
String myBalance = balance.getText().toString();
try {
FileOutputStream fou = openFileOutput("balance.txt",
MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fou);
try {
osw.write(myBalance);
osw.flush();
osw.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
});
You can save it in SharedPrefs
change it to
submitBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String submitAmount = amountEnter.getText().toString();
balance.setText(submitAmount);
PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).
edit().putString("balance", submitAmount).commit();
}
});
and you can get it by
String balance=PreferenceManager.getDefaultSharedPreferences(getApplicationContext())
.getString("balance","nothing_there");
Seeing your code, i assume that you know how to read/write a file in android. If not, then see it from here . https://stackoverflow.com/questions/12421814/how-can-i-read-a-text-file-in-android/ You can try the following code. THe readfile method is from the upper link. You just have to read the particular line/string from the file at onCreate method of the activity. Get the reference of your desired TextView and then set the text to TextView like below. I hope it helps you
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
String texts = readfile();
TextView textView = findViewById(R.id.text_view);
textView.setText(text);
}
private String readfile() {
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard, "file.txt");
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
br.close();
} catch (IOException e) {
//You'll need to add proper error handling here
}
return text.toString();
}