android reading from 2 different files - java

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

Related

Call the saved text from any activitie

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.

Android : Cannot return the values

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

Reading a text document's contents from a URL is always equal to null

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

Why i can't read a textfile in sd?

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

Android Show Internal Data in to textviews

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

Categories