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);
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.
I have created a simple Layout to get information from users, and i have java programmed it to get the data and store them in an .JSON format. I took it as a string and saved them into .JSON format. But while returning return jsonObject i get an error.
Here is the code:
public class MainActivity extends AppCompatActivity {
EditText firstname, lastname, username, mail_id, mobile_no, pass;
Button submit;
JSONObject jsonObject = new JSONObject();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String FILE_NAME = "Sample.json";
firstname = (EditText) findViewById(R.id.firstname);
lastname = (EditText) findViewById(R.id.lastname);
username = (EditText) findViewById(R.id.username);
mail_id = (EditText) findViewById(R.id.mail);
mobile_no = (EditText) findViewById(R.id.phone);
pass = (EditText) findViewById(R.id.password);
submit = findViewById(R.id.submit);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
jsonformat();
String userString = jsonObject.toString();
File file = new File(MainActivity.this.getFilesDir(), FILE_NAME);
FileWriter fileWriter;
try {
fileWriter = new FileWriter(file);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write(userString);
bufferedWriter.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}
File file1 = new File(MainActivity.this.getFilesDir(), FILE_NAME);
FileReader fileReader = null;
try {
fileReader = new FileReader(file1);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuilder stringBuilder = new StringBuilder();
String line = null;
try {
line = bufferedReader.readLine();
while (line != null) {
stringBuilder.append(line).append("\n");
line = bufferedReader.readLine();
bufferedReader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
// This responce will have Json Format String
String responce = stringBuilder.toString();
}
});
}
public JSONObject jsonformat()
{
try {
jsonObject.put("fname", firstname); // seems that it's wrong.
jsonObject.put("lname", lastname); // seems that it's wrong.
jsonObject.put("uname", username); // seems that it's wrong.
jsonObject.put("mail", mail_id); // seems that it's wrong.
jsonObject.put("Phone Number", mobile_no); // seems that it's wrong.
jsonObject.put("Password", pass); // seems that it's wrong.
//return jsonObject; // The error -- You can't return jsonObject in here. onCreate method is void method.
} catch (JSONException e) {
e.printStackTrace();
}
return jsonObject;
}
}
Build error:
/home/sim/AndroidStudioProjects/Activity/app/src/main/java/com/example/activity /MainActivity.java:55: error: incompatible types: unexpected return value
return jsonObject;
^
The .JSON file is created as per the program in the directory. But doesn't contain any value in it. just some "id" has been printed.
Dunno where did i make mistake or missed logic. Comment my mistakes.
I think your code contains some wrong logic.
first, you cannot return onCreate method. you should make seperate method to return object. I think that your code don't need return.
Second, you did put "Layout Element instance" to JSONObject.
I cannot understand why you did it.
Anyway, I changed your MainActivity code as following.
So you can made your change in new MainActivity code.
public class MainActivity extends AppCompatActivity {
EditText firstname, lastname, username, mail_id, mobile_no, pass;
Button submit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String FILE_NAME = "Sample.json";
firstname = (EditText) findViewById(R.id.firstname);
lastname = (EditText) findViewById(R.id.lastname);
username = (EditText) findViewById(R.id.username);
mail_id = (EditText) findViewById(R.id.mail);
mobile_no = (EditText) findViewById(R.id.phone);
pass = (EditText) findViewById(R.id.password);
submit = findViewById(R.id.submit);
submit.setOnClickListener(v -> {
JSONObject jsonObject = jsonformat();
String userString = jsonObject.toString();
File file = new File(getFilesDir(), FILE_NAME);
FileWriter fileWriter;
try {
fileWriter = new FileWriter(file);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write(userString);
bufferedWriter.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}
File file1 = new File(this.getFilesDir(), FILE_NAME);
FileReader fileReader = null;
try {
fileReader = new FileReader(file1);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuilder stringBuilder = new StringBuilder();
String line = null;
try {
line = bufferedReader.readLine();
while (line != null) {
stringBuilder.append(line).append("\n");
line = bufferedReader.readLine();
bufferedReader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
// This responce will have Json Format String
String responce = stringBuilder.toString();
});
}
public JSONObject jsonformat() {
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("fname", firstname.getText().toString());
jsonObject.put("lname", lastname.getText().toString());
jsonObject.put("uname", username.getText().toString());
jsonObject.put("mail", mail_id.getText().toString());
jsonObject.put("Phone Number", mobile_no.getText().toString());
jsonObject.put("Password", pass.getText().toString());
} catch (JSONException e) {
e.printStackTrace();
}
return jsonObject;
}
}
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);
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
I am using http://www.siegmann.nl/epublib to read epub file. My code is mentioned below.
try {
book = epubReader.readEpub(new FileInputStream("/sdcard/EpubTesting.epub"));
Resource res;
Spine contents = book.getSpine();
List<SpineReference> spinelist = contents.getSpineReferences();
StringBuilder string = new StringBuilder();
String line = null;
int count = spinelist.size();
for (int i=0;i<count;i++){
res = contents.getResource(i);
try {
InputStream is = res.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
try {
while ((line = reader.readLine()) != null) {
linez = (string.append(line+"\n")).toString();
}
} catch (IOException e) {e.printStackTrace();}
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println(linez);
s1.loadDataWithBaseURL("/sdcard/",linez, "text/html", "UTF-8",null);
}catch (FileNotFoundException e) {
Toast.makeText(mContext, "File not found.", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(mContext, "IO Exception.", Toast.LENGTH_SHORT).show();
}
Also tried
s1.loadDataWithBaseURL("",linez, "text/html", "UTF-8",null);
s1.loadDataWithBaseURL("file://mnt/sdcard/",linez, "text/html", "UTF-8",null);
But result is sifar. Please tell me what I have to do to show the contained images in file. I have gone through FAQ says Make a subclass of android.webkit.WebView that overloads the loadUrl(String) method in such a way that it loads the image from the Book instead of the internet. But till I don't where they extract the file how can I locate the path. Please tell me. I am very confused. Thanks in advance.
public class EpubBookContentActivity extends Activity{
private static final String TAG = "EpubBookContentActivity";
WebView webview;
Book book;
int position = 0;
String line;
int i = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content);
webview = (WebView) findViewById(R.id.webView);
webview.getSettings().setJavaScriptEnabled(true);
AssetManager assetManager = getAssets();
String[] files;
try {
files = assetManager.list("books");
List<String> list =Arrays.asList(files);
if (!this.makeDirectory("books")) {
debug("faild to make books directory");
}
copyBookToDevice(list.get(position));
String basePath = Environment.getExternalStorageDirectory() + "/books/";
InputStream epubInputStream = assetManager.open("books/"+list.get(position));
book = (new EpubReader()).readEpub(epubInputStream);
DownloadResource(basePath);
String linez = "";
Spine spine = book.getSpine();
List<SpineReference> spineList = spine.getSpineReferences() ;
int count = spineList.size();
StringBuilder string = new StringBuilder();
for (int i = 0; count > i; i++) {
Resource res = spine.getResource(i);
try {
InputStream is = res.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
try {
while ((line = reader.readLine()) != null) {
linez = string.append(line + "\n").toString();
}
} catch (IOException e) {e.printStackTrace();}
} catch (IOException e) {
e.printStackTrace();
}
}
linez = linez.replace("../", "");
// File file = new File(Environment.getExternalStorageDirectory(),"test.html");
// file.createNewFile();
// FileOutputStream fileOutputStream = new FileOutputStream(file);
// fileOutputStream.write(linez.getBytes());
// fileOutputStream.close();
webview.loadDataWithBaseURL("file://"+Environment.getExternalStorageDirectory()+"/books/", linez, "text/html", "utf-8", null);
} catch (IOException e) {
Log.e("epublib exception", e.getMessage());
}
}
public boolean makeDirectory(String dirName) {
boolean res;
String filePath = new String(Environment.getExternalStorageDirectory()+"/"+dirName);
debug(filePath);
File file = new File(filePath);
if (!file.exists()) {
res = file.mkdirs();
}else {
res = false;
}
return res;
}
public void debug(String msg) {
// if (Setting.isDebug()) {
Log.d("EPub", msg);
// }
}
public void copyBookToDevice(String fileName) {
System.out.println("Copy Book to donwload folder in phone");
try
{
InputStream localInputStream = getAssets().open("books/"+fileName);
String path = Environment.getExternalStorageDirectory() + "/books/"+fileName;
FileOutputStream localFileOutputStream = new FileOutputStream(path);
byte[] arrayOfByte = new byte[1024];
int offset;
while ((offset = localInputStream.read(arrayOfByte))>0)
{
localFileOutputStream.write(arrayOfByte, 0, offset);
}
localFileOutputStream.close();
localInputStream.close();
Log.d(TAG, fileName+" copied to phone");
}
catch (IOException localIOException)
{
localIOException.printStackTrace();
Log.d(TAG, "failed to copy");
return;
}
}
private void DownloadResource(String directory) {
try {
Resources rst = book.getResources();
Collection<Resource> clrst = rst.getAll();
Iterator<Resource> itr = clrst.iterator();
while (itr.hasNext()) {
Resource rs = itr.next();
if ((rs.getMediaType() == MediatypeService.JPG)
|| (rs.getMediaType() == MediatypeService.PNG)
|| (rs.getMediaType() == MediatypeService.GIF)) {
Log.d(TAG, rs.getHref());
File oppath1 = new File(directory, rs.getHref().replace("OEBPS/", ""));
oppath1.getParentFile().mkdirs();
oppath1.createNewFile();
System.out.println("Path : "+oppath1.getParentFile().getAbsolutePath());
FileOutputStream fos1 = new FileOutputStream(oppath1);
fos1.write(rs.getData());
fos1.close();
} else if (rs.getMediaType() == MediatypeService.CSS) {
File oppath = new File(directory, rs.getHref());
oppath.getParentFile().mkdirs();
oppath.createNewFile();
FileOutputStream fos = new FileOutputStream(oppath);
fos.write(rs.getData());
fos.close();
}
}
} catch (Exception e) {
}
}
}
For that you have to download all resources of epub files (i.e. images,stylesheet) in location where you downloaded .epub file in sdcard. please check below code to download images and css files from .epub files itself using epublib.
for that u have to send parameter of File objects where you want to store those images.
private void DownloadResource(File FileObj,String filename) {
try {
InputStream epubis = new FileInputStream(FileObj);
book = (new EpubReader()).readEpub(epubis);
Resources rst = book.getResources();
Collection<Resource> clrst = rst.getAll();
Iterator<Resource> itr = clrst.iterator();
while (itr.hasNext()) {
Resource rs = itr.next();
if ((rs.getMediaType() == MediatypeService.JPG)
|| (rs.getMediaType() == MediatypeService.PNG)
|| (rs.getMediaType() == MediatypeService.GIF)) {
File oppath1 = new File(directory, "Images/"
+ rs.getHref().replace("Images/", ""));
oppath1.getParentFile().mkdirs();
oppath1.createNewFile();
FileOutputStream fos1 = new FileOutputStream(oppath1);
fos1.write(rs.getData());
fos1.close();
} else if (rs.getMediaType() == MediatypeService.CSS) {
File oppath = new File(directory, "Styles/"
+ rs.getHref().replace("Styles/", ""));
oppath.getParentFile().mkdirs();
oppath.createNewFile();
FileOutputStream fos = new FileOutputStream(oppath);
fos.write(rs.getData());
fos.close();
}
}
} catch (Exception e) {
Log.v("error", e.getMessage());
}
}
after this use this your code to set path of images in webview.
if stored in sd card then
s1.loadDataWithBaseURL("file:///sdcard/",linez, "text/html",null,null);
or
s1.loadDataWithBaseURL("file://mnt/sdcard/",linez, "text/html", "UTF-8",null);
if in internal storage then
s1.loadDataWithBaseURL("file:///data/data/com.example.project/app_mydownload/",linez, "text/html",null,null);