android programming: need help creating files inside my app - java

I am creating an android app and am trying to create a program that involves creating a folder file inside my app and being able to save it to any directory.
I would want it to be created inside my app and it should allow for as many files as the user wants to be created. How do I do that?
Here is my code:
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class Create extends Activity {
EditText textmsg;
static final int READ_BLOCK_SIZE = 100;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create);
textmsg=(EditText)findViewById(R.id.editText1);
}
// write text to file
public void WriteBtn(View v) {
// add-write text into file
try {
FileOutputStream fileout=openFileOutput("mytextfile.txt", MODE_PRIVATE);
OutputStreamWriter outputWriter=new OutputStreamWriter(fileout);
outputWriter.write(textmsg.getText().toString());
outputWriter.close();
//display file saved message
Toast.makeText(getBaseContext(), "File saved successfully!",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
// Read text from file
public void ReadBtn(View v) {
//reading text from file
try {
FileInputStream fileIn=openFileInput("mytextfile.txt");
InputStreamReader InputRead= new InputStreamReader(fileIn);
char[] inputBuffer= new char[READ_BLOCK_SIZE];
String s="";
int charRead;
while ((charRead=InputRead.read(inputBuffer))>0) {
// char to string conversion
String readstring=String.copyValueOf(inputBuffer,0,charRead);
s +=readstring;
}
InputRead.close();
Toast.makeText(getBaseContext(), s,Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
}

Write:
// write text to file
public void WriteBtn(View v) {
// add-write text into file
try {
FileOutputStream fileout=openFileOutput("mytextfile.txt", MODE_PRIVATE);
fileout.write((textmsg.getText()).getByte())
fileout.close();
//display file saved message
Toast.makeText(getBaseContext(), "File saved successfully!",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
Read:
// Read text from file
public void ReadBtn(View v) {
//reading text from file
try {
FileInputStream fileIn = openFileInput("mytextfile.txt");
byte[] reader = new byte[fileIn.available()];
if(fileIn.read(reader) != -1){
String contentFile = new String[reader];
Toast.makeText(getBaseContext(), contentFile,Toast.LENGTH_SHORT).show();
}
fileIn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
It will help you.

Related

button not working in android basic apo I am trying to create

I am having an issue with my first app. When I click on "Submit" it is meant to create a textfile with the values that the user has entered however it is not creating it. I am not sure what the issue is.
I would also like to know if there is a better way of storing the data entered by the user to make is useable eventually in a excel spread sheet. Or just use plain text file to make it easy?
package com.example.mybodyrecord;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
String myBodyRecord = "My_Body_Record.txt";
Date date = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm");
File file; // declare here and initialize inside onCreate.
Button button;
EditText weightInput;
EditText ketoneBloodInput;
EditText ketoneUrineInput;
EditText bloodPressureInput;
EditText bloodSugarInput;
String weight;
String ketoneBlood;
String ketoneUrine;
String bloodPressure;
String bloodSugar;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Setting where to get the data from, ie what fields
weightInput = findViewById(R.id.weight);
ketoneBloodInput = findViewById(R.id.ketoneblood);
ketoneUrineInput = findViewById(R.id.ketoneurine);
bloodPressureInput = findViewById(R.id.bp);
bloodSugarInput = findViewById(R.id.bslvl);
button = findViewById(R.id.submit);
//activity has a context now you can use getApplicationContext or this
file = new File(this.getFilesDir(),myBodyRecord);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FileOutputStream fos = null;
//Taking input from the fields
weight = weightInput.getText().toString() +"kg";
ketoneBlood = ketoneBloodInput.getText().toString() +"mmol/L";
ketoneUrine = ketoneUrineInput.getText().toString();
bloodPressure = bloodPressureInput.getText().toString() +"mmHg";
bloodSugar = bloodSugarInput.getText().toString() +"mmol/L";
//Save to the file, with the date and time
if (file.exists()) {
try {
fos = openFileOutput(myBodyRecord, getApplicationContext().MODE_APPEND);
fos.write("\n\r".getBytes());
fos.write(formatter.format(date).getBytes());
fos.write(weight.getBytes());
fos.write(ketoneBlood.getBytes());
fos.write(ketoneUrine.getBytes());
fos.write(bloodPressure.getBytes());
fos.write(bloodSugar.getBytes());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
else {
try {
fos = openFileOutput(myBodyRecord, getApplicationContext().MODE_PRIVATE);
fos.write("\n\r".getBytes());
fos.write(formatter.format(date).getBytes());
fos.write(weight.getBytes());
fos.write(ketoneBlood.getBytes());
fos.write(ketoneUrine.getBytes());
fos.write(bloodPressure.getBytes());
fos.write(bloodSugar.getBytes());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
});
}
}
Collins
The question how to read/write to text files in android is already answered in this thread:
How can I read a text file in Android?
However, tis is not what you want in android.
First, you should be familiar with the concept of application and service.
Then, to solve your problem:
- For a smaller amount of data (eg. settings) you might use SharedPreferences.
- For more data (eg. records) the recommended approach is a ContentProvider with SQLite database.

Android Studio: Unable to extract raw String text from PDF file using PDFBox

I am using the PDFBox library for the first time to create an app in which I need to be able to extract raw String text from a PDF file. Whenever I run the application, it just crashes. All the methods appear to be correct however the app is still crashing.
NOTE: Android Studio shows an error in the methods unless they are within "try-catch" statements.
package com.example.e_reader;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.tom_roush.pdfbox.contentstream.operator.text.ShowText;
import com.tom_roush.pdfbox.pdmodel.PDDocument;
import com.tom_roush.pdfbox.text.PDFTextStripper;
import com.tom_roush.pdfbox.util.PDFBoxResourceLoader;
import java.io.File;
import java.io.IOException;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button importButton = findViewById(R.id.importButton);
final TextView pdfView = findViewById(R.id.pdfView);
File file = new File("C:/Users/hd009/AndroidStudioProjects/EReader/app/src/main/java/assets");
PDDocument sample = null;
try {
sample = PDDocument.load(file);
} catch (IOException e) {
e.printStackTrace();
}
PDFTextStripper stripper = null;
try {
stripper = new PDFTextStripper();
} catch (IOException e) {
e.printStackTrace();
}
String text = null;
try {
text = stripper.getText(sample);
} catch (IOException e) {
e.printStackTrace();
}
pdfView.setText(text);
}
}

java.lang.IOException:pipe broken

I am developing a bluetooth file transfer application. In this application, I want to connect two android devices via bluetooth and transfer files. However, I am able to show all nearest device, Paired devices and able to connect with them but when I transfer images, bluetoothSocket.write() throws pipe broken exception. I have searched for solutions and refer all answers from stackoverflow and after that what I understood is that when the receiver bluetooth server socket is closed, this exception is raised but I can't get how to solve this problem. Below is my code for connecting to device and transferring images. Thanks in advance
package com.example.jayesh.bluetoothusagedemo.ConnectAsyncTask;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Parcelable;
import android.util.Log;
import android.widget.Toast;
import com.example.jayesh.bluetoothusagedemo.R;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.SocketTimeoutException;
import java.util.UUID;
/**
* Created by Jayesh on 26-01-2017.
*/
public class ConnectDevice extends AsyncTask<BluetoothDevice, Void, String> {
BluetoothSocket bluetoothSocket;
Context context;
String uuid;
OutputStream outputStream;
byte[] bytes;
public ConnectDevice(Context context,String uuid)
{
this.context = context;
this.uuid = uuid;
}
#Override
protected String doInBackground(BluetoothDevice... bluetoothDevices) {
try {
bluetoothSocket = bluetoothDevices[0].createRfcommSocketToServiceRecord(UUID.fromString(uuid));
if (bluetoothSocket != null) {
bluetoothSocket.connect();
}
} catch (SocketTimeoutException e) {
//e.printStackTrace();
Log.d("socket=======","socket timeout");
} catch (IOException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}
if(bluetoothSocket.isConnected()){
convertImageToByteArray();
try {
//Log.d("bytessize========", String.valueOf(bytes.length));
for(Byte b:bytes){
if(bluetoothSocket.isConnected()){
outputStream.write(b);
//Thread.sleep(500);
}
else{
Log.d("closed=============","true");
break;
}
//outputStream.flush();
}
//outputStream.write(bytes);
outputStream.flush();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
} //catch (InterruptedException e) {
//e.printStackTrace();
//}
}
return "completed...";
}
#Override
protected void onPostExecute(String s) {
//super.onPostExecute(s);
Toast.makeText(context, s, Toast.LENGTH_SHORT).show();
}
void convertImageToByteArray(){
try {
outputStream = bluetoothSocket.getOutputStream();
Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(),R.drawable.pic1);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG,100,stream);
bytes = stream.toByteArray();
Log.d("bytessize========", String.valueOf(bytes.length));
} catch (IOException e) {
e.printStackTrace();
}
}
}

Trying to check if textfile with same name has already been created

I am trying to create a basic app where I input text to the app, this text names a text file, then the app adds extra text to the file. If a text file with the same name already exists, I want to output "file exists". At the moment from what I can see, the check to see if a file with the same name already exists is not working. Can anybody see why? From what I see it should work. Here is the code:
package com.example.user.filetest;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.File;
public class MainActivity extends AppCompatActivity {
FileUtility myFile = new FileUtility();
private File root;
private File file;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final EditText enter = ((EditText) findViewById(R.id.editText));
final TextView show = ((TextView) findViewById(R.id.textView));
Button b = ((Button) findViewById(R.id.button));
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String s = enter.getText().toString();
file = new File(root, "//" + s);
if (file.exists()) {
show.setText("File Exists");
}
else {
myFile.createFile(getApplicationContext(), s);
myFile.writeLine("test");
show.setText(myFile.readAll());
}
}
}
);
}
package com.example.user.filetest;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import android.content.Context;
import android.os.Environment;
import android.util.Log;
import android.content.*;
public class FileUtility {
private File root;
private File file;
public FileUtility() {
root = Environment.getExternalStorageDirectory();
}
public void createFile(Context context, String fileName) {
try {
if (root.canWrite()) {
file = new File(root, "//" + fileName);
if (!file.exists()) {
file.createNewFile();
}
}
else
{
file = new File(context.getFilesDir(), "//" + fileName); // File(root, "//" + fileName);
if (!file.exists()) {
file.createNewFile();
}
}
} catch (IOException e) {
Log.e("Error", "fail to create a new file");
}
}
public String readAll() {
StringBuilder returnString = new StringBuilder();
try {
BufferedReader in;
FileReader datawriter = new FileReader(file);
in = new BufferedReader(datawriter);
if (file.exists()) {
String str = null;
while((str=in.readLine())!=null)
{
returnString.append(str + "\n");
}
}
in.close();
} catch (IOException e) {
Log.e("Error", "fail to write file");
}
return returnString.toString();
}
public void writeLine(String message) {
try {
BufferedWriter out;
FileWriter datawriter = new FileWriter(file,true);
out = new BufferedWriter(datawriter);
if (file.exists()) {
out.write(message + "\n");
out.flush();
}
out.close();
} catch (IOException e) {
Log.e("Error", "fail to write file");
}
}
}
You have an issue in the way you declare and initialize File root in both classes.
In MainActivity :
The File root attribute is not initialized
Change your code to
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
root = Environment.getExternalStorageDirectory(); // Initialilze the root file here
// ...
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String s = enter.getText().toString();
file = new File(root, "//" + s);
if (file.exists()) {
show.setText("File Exists");
}
else {
myFile.createFile(root, getApplicationContext(), s); // pass the root file as parameter
myFile.writeLine("test");
show.setText(myFile.readAll());
}
}
}
);
}
In FileUtility :
As you are also using the root in FileUtility to create the new file you can pass it as parameter and then remove the class attribute .
class FileUtility{
private File file;
public FileUtility() {
}
public void createFile(File root, Context context, String fileName){
// Use the root initialized into the main activity
//...
And the you

Writing more than one String to a file without deleting the first one ANDROID favorites for browser

I am making a simple browser for school and I am trying to make the favorites. This code here adds a favorite to a file(so I can keep it after the app is closed) and displays it in the TextView. My problem is that it can only save one. If i add the second one, the first one is replaced. I thought i could add them in an array or arrayList(or anything that works, i am open to suggestions), but i can't succeed. Thanks for the help.
package com.example.browser3;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Favorite extends Activity {
EditText etName;
EditText etAdress;
Button bAdd;
TextView tvDisplay;
protected void onResume() {
readFile("favorite.txt", tvDisplay);
super.onResume();
}
public void writeFile(String fileName, EditText v, EditText x){
try {
OutputStreamWriter out=new OutputStreamWriter(openFileOutput(fileName,0));
out.write(v.getText().toString()+ x.getText().toString());
out.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void readFile(String fileName, TextView w){
try {
InputStream in=openFileInput(fileName);
if(in!=null){
InputStreamReader reader= new InputStreamReader(in);
BufferedReader buffreader= new BufferedReader(reader);
StringBuilder builder= new StringBuilder();
String str;
while((str=buffreader.readLine())!=null){
builder.append(str+ "\n");
}
in.close();
w.setText(builder.toString());
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.favorite);
etName = (EditText) findViewById(R.id.etName);
etAdress = (EditText) findViewById(R.id.etAdress);
bAdd = (Button) findViewById(R.id.bAdd);
tvDisplay = (TextView) findViewById(R.id.tvDisplay);
bAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
writeFile("favorite.txt",etName, etAdress);
readFile("favorite.txt", tvDisplay);
}
});
}
}
to write at first position i.e. prepend then u need to use this
private void writeToFile(Context context,String data){
try{
String path=context.getFilesDir().getAbsolutePath();
File file = new File(path + File.separator + fileName);
RandomAccessFile rf = new RandomAccessFile(file,"rws");
file.getParentFile().mkdirs();
Log.d("creating file path",path);
byte[] text = new byte[(int) file.length()];
rf.readFully(text);
rf.seek(0);
rf.writeBytes(data);
rf.write(text);
Log.d("write","writing file...");
rf.close();
}catch(Exception e){e.printStackTrace(); Log.d("caught", "data wititng fail");}
}
and if u want to append use this
private void writeToFile(Context context,String data){
try{
String path=context.getFilesDir().getAbsolutePath();
File file = new File(path + File.separator + fileName);
RandomAccessFile rf = new RandomAccessFile(file,"rws");
file.getParentFile().mkdirs();
Log.d("creating file path",path);
byte[] text = new byte[(int) file.length()];
rf.readFully(text);
rf.seek(0);
rf.write(text);
rf.writeBytes(data);
Log.d("write","writing file...");
rf.close();
}catch(Exception e){e.printStackTrace(); Log.d("caught", "data wititng fail");}
}
or u can open file in MODE_APPEND mode.. to open file in append mode change to this OutputStreamWriter out=new OutputStreamWriter(openFileOutput(fileName,true));

Categories