I can read in my log what i wrote in a txt file in my sdcard but i can't open the file. I need onClick open with a txt viewer or something else the file.. I can display in the log the values right now in this way:
public void onClick(View v)
{
File file = new File("/sdcard/ReportData.txt");
StringBuffer contents = new StringBuffer();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String text = null;
// repeat until all lines is read
while ((text = reader.readLine()) != null) {
contents.append(text)
.append(System.getProperty(
"line.separator"));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
Log.e("TEXT", contents.toString());
}
But i can't open the file.. how can i do it?
Try this..
public void onClick(View v)
{
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
File file = new File("/sdcard/ReportData.txt");
intent.setDataAndType(Uri.fromFile(file), "text/*");
startActivity(intent);
}
Please try following code. Following code displays text file in an textedit.
//Find the view by its id
TextView tv = (TextView)findViewById(R.id.fileContent);
public void onClick(View v)
{
File file = new File("/sdcard/ReportData.txt");
StringBuffer contents = new StringBuffer();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String text = null;
// repeat until all lines is read
while ((text = reader.readLine()) != null) {
contents.append(text)
.append(System.getProperty(
"line.separator"));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
Log.e("TEXT", contents.toString());
String text = contents.toString();
//Set the text
tv.setText(text);
}
Hope this helps you!!
For more info you can go through android-read-text-file-from-sd-card
Related
public void getData(View view) {
try {
FileInputStream fileInput = openFileInput("user_data.txt");
InputStreamReader reader = new InputStreamReader(fileInput);
BufferedReader buffer = new BufferedReader(reader);
StringBuffer strBuffer = new StringBuffer();
String lines;
while ((lines = buffer.readLine()) != null) {
strBuffer.append(lines); //Вывод имени
}
textView3.setText(strBuffer.toString());
} catch (FileNotFoundException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} }
public void saveData (View view) {
String user_name = editSave.getText().toString();
try {
FileOutputStream fileOutput = openFileOutput("user_data.txt", MODE_PRIVATE);
fileOutput.write((user_name).getBytes());
fileOutput.close();
textView3.setText(user_name);
Toast.makeText(setting.this, " ", Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Hello. I'm just learning. I need user_name to be called from any activity so I can insert it into the code that passes the text, right now I can't do it.
I will now try to explain what I want to get: textView.setText("random text" + user_name + "text random")
I would be very grateful if you could edit my code.
in my android app im trying to set 2 text views names from 2 different files but for some reason the first text view is being set as the 2nd files information "ingredient 2 " and the 2nd text view isnt being displayed at all? am i doing something wrong with the way im setting and opening my files?
public class GroceriesActivity extends AppCompatActivity {
public TextView groceryname1, groceryname2, groceryname3, groceryname4;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_groceries);
groceryname1 = (TextView) findViewById(R.id.grocery1);
groceryname2 = (TextView) findViewById(R.id.grocery2);
groceryname3 = (TextView) findViewById(R.id.grocery3);
groceryname4 = (TextView) findViewById(R.id.grocery4);
String message;
String message2;
FileInputStream fis1 = null;
FileInputStream fis2 = null;
FileInputStream fis3 = null;
FileInputStream fis4 = null;
try {
fis1 = openFileInput("Ingredient1");
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
InputStreamReader isr = new InputStreamReader(fis1);
BufferedReader br = new BufferedReader(isr);
StringBuffer sb = new StringBuffer();
try {
while ((message = br.readLine()) != null) {
sb.append(message);
}
} catch (IOException e1) {
e1.printStackTrace();
}
groceryname1.setText(sb.toString());
try {
fis1.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
fis2 = openFileInput("Ingredient2");
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
InputStreamReader isr2 = new InputStreamReader(fis2);
BufferedReader br2 = new BufferedReader(isr2);
StringBuffer sb2 = new StringBuffer();
try {
while ((message2 = br2.readLine()) != null) {
sb2.append(message2);
}
} catch (IOException e1) {
e1.printStackTrace();
}
groceryname2.setText(sb2.toString());
try {
fis2.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
so as tldr im trying to set textview1 as ingredient1 and textview2 as ingredient2 but right now textview1 is being set as ingredient2 and textview2 is not being changed
EDIT: after fixing that error im now having the textview1 and textview2 being set as the first ingredient
try changing
sb.append(message2);
to
sb2.append(message2);
Whenever I try to get a text document from Dropbox containing a version string, it says that it equals null even though it is supposed to equal 0.6.48. I've tried many different ways of getting the file, but its always returning null. Code:
new Thread() {
public void run() {
try {
URL textUrl = new URL(UPDATE_API); // UPDATE_API = "https://dl.dropboxusercontent.com/s/zjlxzypgqsxvtr0/version.txt?dl=1"
BufferedReader bufferReader = new BufferedReader(new InputStreamReader(textUrl.openStream()));
String StringBuffer;
String stringText = "";
while ((StringBuffer = bufferReader.readLine()) != null) {
stringText += StringBuffer;
}
bufferReader.close();
Soundboard.REMOTE_VERSION = stringText;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
What am I missing? I'm building for API 23. I have put <uses-permission android:name="android.permission.INTERNET"/> in my Android manifest.
Your code worked for me with few changes:
String UPDATE_API = "https://dl.dropboxusercontent.com/s/zjlxzypgqsxvtr0/version.txt?dl=1";
private BufferedReader bufferReader = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread() {
public void run() {
try {
URL textUrl = new URL(UPDATE_API);
bufferReader = new BufferedReader(new InputStreamReader(textUrl.openStream()));
String StringBuffer = "";
StringBuilder stringText = new StringBuilder();
while ((StringBuffer = bufferReader.readLine()) != null) {
stringText.append(StringBuffer);
}
Log.d("--->", stringText.toString());
Soundboard.REMOTE_VERSION = stringText;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
bufferReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}.start();
}
Try to close the BufferedReader in try..finally.
Use StringBuilder rather than String for concatenation
I am trying to write and read to a text file name students but I am having all kinds of hassles I am very new to android programming so I am trying this out for the first time. I have looked at code here and there to try and figure out what I am doing wrong but I cant find one specific thing to help, this question has probably been asked a couple of times, so I am sorry for asking it again. Please see my different .xml and .java files below. The actual question is to be able to write data to a textfile and from the main screen click on a textfield which will take you to the edit screen, where you get to edit that specific field and save it to a text file (this however has not been done yet as I am still struggling to figure out why my writing and reading to the textfile is not working, I hope my poor attempt at coding will shed some light on the matter.
Please don't crucify me for my bad coding I am super new to android
/////////////////////////////add screen.java///////////////////////////////
public class AddNew extends Activity {
private static final String newLine = System.getProperty("line.separator");
TextView txtText;
EditText Modules;
EditText Types;
#Override
protected void onCreate(Bundle SavedInstanceState){
super.onCreate(SavedInstanceState);
setContentView(R.layout.add);
txtText = (TextView)findViewById(R.id.textView1);
Modules = (EditText)findViewById(R.id.etMod);
Types = (EditText)findViewById(R.id.etType);
Button backMan = (Button)findViewById(R.id.btnBackMain);
backMan.setOnClickListener(new OnClickListener(){
public void onClick(View v){
//This is where your code will go
startActivity(new Intent(AddNew.this, MainActivity.class));
}
}); //end back Button
//get the day, month & year from the Date picker
DatePicker myDPicker = (DatePicker)findViewById(R.id.dpDate);
Integer Year = myDPicker.getYear();
Integer Month = myDPicker.getMonth();
Integer Day = myDPicker.getDayOfMonth();
StringBuilder sb = new StringBuilder();
sb.append(Year.toString()).append("-").append(Month.toString()).append
("-").append(Day.toString());
final String dobStr=sb.toString();
txtText.setText("TEST");
Button Save = (Button)findViewById(R.id.btnSaveAdded);
Save.setOnClickListener(new OnClickListener(){
public void onClick(View v){
//This is where your code will go
try {
writeToFile(Modules.getText().toString(),
Types.getText().toString(),dobStr);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void writeToFile(String Mod, String AsType, String dobDate) throws
IOException {
// TODO Auto-generated method stub
//String textTofile;
StringBuilder sbText = new StringBuilder();
sbText.append(Mod + "," + dobStr + "," + AsType);
//textTofile=sbText.toString();
String fileName = "student";
PrintWriter printWriter = null;
File file = new File(fileName);
try {
if (!file.exists()) file.createNewFile();
printWriter = new PrintWriter(new FileOutputStream(fileName,
true));
printWriter.write(newLine ); //+textTofile);
} catch (IOException ioex) {
ioex.printStackTrace();
} finally {
if (printWriter != null) {
printWriter.flush();
printWriter.close();
}
}
}
}); //end back Button
}
}
`public class MainActivity extends Activity {
TextView fDisplay;
TextView fTest;
int numItems=0; //use it later to keep track of the number of items.
String inText; //use this variable for the information read in from the textfile.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button but1=(Button)findViewById(R.id.btnAdd);
but1.setOnClickListener(new OnClickListener(){
public void onClick(View v){
//This is where your code will go
startActivity(new Intent(MainActivity.this, AddNew.class));
}
}); //end but1
Button but2 = (Button)findViewById(R.id.btnEditCur);
but2.setOnClickListener(new OnClickListener(){
public void onClick(View v){
//This is where your code will go
startActivity(new Intent(MainActivity.this, EditCur.class));
}
}); //end of button 2
fDisplay = (TextView)findViewById(R.id.tvAssign1);
try {
readFromFile();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void readFromFile() throws IOException {
// TODO Auto-generated method stub
// String ret="";
BufferedReader br;
FileReader fr = null;
try {
fr = new FileReader("student");
br = new BufferedReader(fr);
String line = br.readLine();
while (null != line) {
fDisplay.append(line);
fDisplay.append("\n");
line = br.readLine();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (null != fr) {
try {
fr.close();
} catch (IOException e) {
// ignore
}
}
}
}
}
`
For writting on a file I have used this
String filename;
String content;
filename = "PATH_AND_FILE";
content = "CONTENT ON THE FILE"
BufferedWriter out = new BufferedWriter(new FileWriter(filename));
out.write(myString.toString());
out.flush();
out.close();
And for reading I have this function:
public static String readFileAsString() {
String result = "";
String filename;
filename = "PATH_AND_FILE";
File file = new File(filename);
if ( file.exists() ) {
FileInputStream fis = null;
try { fis = new FileInputStream(file);
char current;
while (fis.available() > 0) {
current = (char) fis.read();
result = result + String.valueOf(current);
}
} catch (Exception e) {
// System.out.println("DEBUG Exception String :"+ e.toString());
} finally {
if (fis != null)
{ try {
fis.close();
} catch (IOException ignored) {
}}
else {// System.out.println("DEBUG Exception String NULL");
}
}
return result;
}
else
{
return "DEFAULT CONTENT";
}
}
In Android, the file' directory is different then that on a PC, like :the files are stored in a directory related to your App, the accessing permissions are different.
This link might be helpful:
How To Read/Write String From A File In Android
Two simple functions (Java) to read and write:
private static void writeToFile(String path, String text) {
PrintWriter writer;
try {
writer = new PrintWriter(path, "UTF-8");
writer.print(text);
writer.close();
} catch (FileNotFoundException | UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static String getFileContent(String filename){
String everything = "";
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(filename));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
StringBuilder sb = new StringBuilder();
String line = null;
try {
line = br.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
try {
line = br.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
everything = sb.toString();
} finally {
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return everything;
}
I am working on an app where I need to save/read my files from Internal storage.
But it read all my data in the same TextView.
Can someone show me show,how to show the data in 2 textviews, or to show me how put the one data under the other data.
Here is my code for saving data:
private void SaveMode() {
String FILENAME ;
String Strin1= textview1.getText().toString();
String String2= textview2.getText().toString();
EditText filename1 = (EditText) findViewById(R.id.filename);
FILENAME = filename1.getText().toString();
if (FILENAME.contentEquals("")){
FILENAME = "UNTITLED";
}
String1 = textview1.getText().toString();
String2= textview2.getText().toString();
FileOutputStream fos = null;
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
fos.write("Strin1.getBytes());
fos.write(String2.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
And here is my code for read my data:
private void getFilenames() {
String[] filenames = getApplicationContext().fileList();
List<String> list = new ArrayList<String>();
for(int i = 0; i<filenames.length; i++){
//Log.d("Filename", filenames[i]);
list.add(filenames[i]);
}
ArrayAdapter<String> filenameAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, list);
spinner.setAdapter(filenameAdapter);
}
public void SpinnerClick(View v) {
String selectFile = String.valueOf(spinner.getSelectedItem());
openFile(selectFile);
}
private void openFile(String selectFile) {
showData = (TextView) findViewById(R.id.show_data);
TextView showData1 = (TextView) findViewById(R.id.show_data1);
String value = "";
FileInputStream fis;
try {
fis = openFileInput(selectFile);
byte[] input = new byte[fis.available()];
while(fis.read(input) != -1){
value += new String(input);
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
showData.setText(value);
}
EDIT
I tried to edit my read code like this, but with no luck
private void openFile(String selectFile) {
TextView showData = (TextView) findViewById(R.id.show_data);
TextView showData2 = (TextView) findViewById(R.id.show_data2);
String value = "";
String[] strArray = value.split(";");
try {
FileInputStream fis = openFileInput(selectFile);
byte[] input = new byte[fis.available()];
while(fis.read(input) != -1){
value += new String(input);
}
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
showData.setText(value);
showData.setText(strArray[0]);
showData2.setText(strArray[1]);
}
Edit 2
Got it to work with Shobhit Puri codes
First while saving your data you might insert a delimiter in between those two string. Make sure that delimiter is not the one expected in your textViews.
While saving:
String string3 = ";";
try {
fos.write("Strin1.getBytes());
fos.write("String3.getBytes());
fos.write(String2.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
Then when you are trying to read it into value string, then split is using .split function. Eg:
String[] strArray = value.split(";");
strArray[0] will give first textview's sting and strArray[1] will give the second.
Update
private void openFile(String selectFile) {
TextView showData = (TextView) findViewById(R.id.show_data);
TextView showData2 = (TextView) findViewById(R.id.show_data2);
String value = "";
try {
FileInputStream fis = openFileInput(selectFile);
byte[] input = new byte[fis.available()];
while(fis.read(input) != -1){
value += new String(input);
}
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String[] strArray = value.split(";");
showData.setText(strArray[0]);
showData2.setText(strArray[1]);
}
try
{
FileInputStream fis = new FileInputStream(myInternalFile);
DataInputStream in = new DataInputStream(fis);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
myData = myData + strLine;
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
myInputText.setText(myData);