EditView only displays the last line of the text file - java

my App saves the text of a multi-line EditView to a text file, but the problem is that if I restart my app, only the last line gets restored. (Perhaps it's also possible that the FileOutputStream only saves the last line, I am not sure ¯_(ツ)_/¯)
Here is my code:
private static final String TAG = "EditDataActivity";
public static String Textfile = "test.txt";
private Button btnSave,btnDelete;
private EditText editable_item;
EditText Zutaten, Zubereitung;
DatabaseHelper mDatabaseHelper;
private String selectedName;
private int selectedID;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_data_layout);
btnSave = (Button) findViewById(R.id.btnSave);
btnDelete = (Button) findViewById(R.id.btnDelete);
editable_item = (EditText) findViewById(R.id.editable_item);
mDatabaseHelper = new DatabaseHelper(this);
Zutaten = (EditText)findViewById(R.id.editText4);
Zubereitung = (EditText)findViewById(R.id.editText2);
Zutaten.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
try{
EditText test = (EditText)findViewById(R.id.editable_item);
String testText = test.getText().toString();
String Textfile2 = testText + ".txt";
EditText field = (EditText)findViewById(R.id.editText4);
String text = field.getText().toString();
FileOutputStream fos = openFileOutput(Textfile2, Context.MODE_PRIVATE);
fos.write(text.getBytes());
fos.close();
}catch (IOException e){
System.out.println("Error");
}
}
});
Intent receivedIntent = getIntent();
selectedID = receivedIntent.getIntExtra("id",-1); //NOTE: -1 is just the default value
selectedName = receivedIntent.getStringExtra("name");
editable_item.setText(selectedName);
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try{
EditText test = (EditText)findViewById(R.id.editable_item);
String testText = test.getText().toString();
String Textfile2 = testText + ".txt";
EditText field = (EditText)findViewById(R.id.editText4);
String text = field.getText().toString();
FileOutputStream fos = openFileOutput(Textfile2, Context.MODE_PRIVATE);
fos.write(text.getBytes());
fos.close();
}catch (IOException e){
System.out.println("Error");
}
Toast.makeText(getApplicationContext(), "Rezept erfolgreich gespeichert!", Toast.LENGTH_SHORT).show();
Intent back = new Intent(EditDataActivity.this, MainActivity.class);
startActivity(back);
String item = editable_item.getText().toString();
if (!item.equals("")) {
mDatabaseHelper.updateName(item, selectedID, selectedName);
} else {
toastMessage("Du musst das Rezept benennen!");
}
}
});
btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try{
EditText test = (EditText)findViewById(R.id.editable_item);
String testText = test.getText().toString();
String Textfile2 = testText + ".txt";
EditText field = (EditText)findViewById(R.id.editText4);
String text = field.getText().toString();
FileOutputStream fos = openFileOutput(Textfile2, Context.MODE_APPEND);
fos.write("".getBytes());
fos.close();
System.out.println("did it");
}catch (IOException e){
System.out.println("Error");
}
Intent back = new Intent(EditDataActivity.this, MainActivity.class);
startActivity(back);
mDatabaseHelper.deleteName(selectedID,selectedName);
editable_item.setText("");
toastMessage("Rezept erfolgreich gelöscht!");
}
});
}
private void toastMessage(String message){
Toast.makeText(this,message, Toast.LENGTH_SHORT).show();
}
public void loadsavedfile(){
try {
EditText test1 = (EditText) findViewById(R.id.editable_item);
String test1Text = test1.getText().toString();
String Textfile2 = test1Text + ".txt";
if (!Textfile2.isEmpty()) {
FileInputStream fis = openFileInput(Textfile2);
BufferedReader reader = new BufferedReader(new InputStreamReader(new DataInputStream(fis)));
String test;
EditText Test = (EditText) findViewById(R.id.editText4);
while ((test = reader.readLine()) != null) {
Test.setText(test);
}
}else{
}
}catch(IOException e){
}
Hope fully you can help me :)
Thanks!

Just do
while ((test = reader.readLine()) != null) {
Test.setText(Test.getText()+"\n" + test);
}
When you had setText(test) only it was replacing the text from the edit text every time the loop ran but you have to append the new text to the last line. A better way to do this would be to create the String first and then set it to EditText as it is better for performance.
StringBuilder str = new StringBuilder();
while((test = reader.readLine()) != null)
str.append('\n' + test);
Test.setText(str.toString());
Hope this solves your problem.

Related

There was a problem saving the text in EditText to a file

This code receives information from an acquaintance you want to register in editText, and then clicks finButton to save the information you receive as a file called friendlist.txt.
However, the Toast message is outputted from the try-catch statement that is currently performed when finButton is pressed.
Also, the checkpermission does not work, which is wrapped in a try~catch statement, but does not have output on the logcat.
And manifest.
uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"
uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
is written.
Please let me know the solution.
And this content is written with a translator, so the sentence can be strange.
when you press finButton, the logcat is shown below.
The code corresponding to the 116th line is this.
FileOutputStream outstream = openFileOutput("friendList.txt", Activity.MODE_WORLD_WRITEABLE);
logcat
public class EnteringInformationOfFriendActivity extends AppCompatActivity {
Button finButton;
EditText phoneNumberEditText, nameEditText, emailEditText, groupEditText, memoEditText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_entering_information_of_friend);
phoneNumberEditText = (EditText) findViewById(R.id.phoneNumberEditText);
nameEditText = (EditText) findViewById(R.id.nameEditText);
emailEditText = (EditText) findViewById(R.id.emailEditText);
groupEditText = (EditText) findViewById(R.id.groupEditText);
memoEditText = (EditText) findViewById(R.id.memoEditText);
try{
checkPermission();
}
catch (Exception e){
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String exceptionAsStrting = sw.toString();
Log.e("CSP", exceptionAsStrting);
e.printStackTrace();
}
finButton = (Button) findViewById(R.id.finButton);
finButton.setOnClickListener(v -> {
try{
String phoneTxt = phoneNumberEditText.getText().toString().trim();
String nameTxt = nameEditText.getText().toString().trim();
String emailTxt = emailEditText.getText().toString().trim();
String groupTxt = groupEditText.getText().toString().trim();
String memoTxt = memoEditText.getText().toString().trim();
String friendInfoTxt = phoneTxt + "-" + nameTxt + "-" + emailTxt + "-" + groupTxt + "-" + memoTxt;
FileOutputStream outstream = openFileOutput("friendList.txt", Activity.MODE_WORLD_WRITEABLE);
outstream.write(friendInfoTxt.getBytes());
outstream.close();
Intent intent = new Intent(v.getContext(), FriendListActivity.class);
startActivity(intent);
} catch (Exception e){
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String exceptionAsStrting = sw.toString();
Log.e("Filesave", exceptionAsStrting);
e.printStackTrace();
Toast.makeText(this.getApplicationContext(), "Save failed.", Toast.LENGTH_SHORT).show();
}
});
}
public void checkPermission(){
if(checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
}
}
}
Try with Context.MODE_APPEND or Context.MODE_PRIVATE instead of Activity.MODE_WORLD_WRITEABLE

Error: 'Exception thrown while unbinding java.lang.IllegalArgumentException: Service not registered: ll#3b848368' in Android Studio

I have been frustrated by again and again trying to resolve the issue I am getting in Android Studio. I know there are a lot of question like this on internet but none of them work with me. I am trying to test the app in LDPlayer. I actually have an activity opening another activity:
Button btn = findViewById(R.id.button2);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, prac_ques.class);
startActivity(intent);
}
});
This is all my code. The activity that opens('activity A') get the data from another class(class B)
activity A code
public static String selected_ans = "";
RadioButton radioButton;
RadioGroup radioGroup;
public static RadioButton ch1;
public static RadioButton ch2;
public static RadioButton ch3;
public static RadioButton ch4;
public static TextView textView;
public static Button click;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_a);
radioGroup = findViewById(R.id.radioGroup);
int selectedId = radioGroup.getCheckedRadioButtonId();
radioButton = findViewById(selectedId);
ch1 = findViewById(R.id.radio1);
ch2 = findViewById(R.id.radio2);
ch3 = findViewById(R.id.radio3);
ch4 = findViewById(R.id.radio4);
selected_ans = selected_ans + radioButton.getText().toString();
class_a process = new class_a();
process.execute();
textView = findViewById(R.id.questions);
click = findViewById(R.id.button);
}
Here is class a code
public class class_a extends AsyncTask<Void , Void, Void> {
int over;
int ans;
String raw_dat = "";
String question = "";
String question2 = "";
String ch1 = "";
String ch2 = "";
String ch3 = "";
String ch4 = "";
String anss = "";
#Override
protected Void doInBackground(Void... voids) {
try {
URL url = new URL("json_url");
HttpURLConnection htc = (HttpURLConnection) url.openConnection();
InputStream inputStream = htc.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
String raw = "";
while (raw != null){
raw = br.readLine();
raw_dat = raw_dat+raw;
}
JSONArray jsonArray = new JSONArray(raw_dat);
for (int i = 0; i == 0; i++) {
JSONObject jo = jsonArray.getJSONObject(i);
question = "" + jo.get("question");
ch1 = "" + jo.get("cha");
ch2 = "" + jo.get("chb");
ch3 = "" + jo.get("chc");
ch4 = "" + jo.get("chd");
anss = "" + jo.get("ans");
}
for (int i = 1; i == 1; i++){
JSONObject jo = jsonArray.getJSONObject(i);
question2 = "" +jo.get("question");
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
activity_a.ch1.setText(ch1);
activity_a.ch2.setText(ch2);
activity_a.ch3.setText(ch3);
activity_a.ch4.setText(ch4);
activity_a.textView.setText(question);
activity_a.click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
over++;
if (activity_a.selected_ans.equals(anss)){
ans++;
}
activity_a.textView.setText(question2);
activity_a.click.setOnClickListener(null);
activity_a.click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
over++;
activity_a.textView.setText("over !!");
}
});
}
});
}
}
I am in a big trouble please help me.... Thank you in advance.

Sending SMS on android through a Third-party Gateway

Please i would like to know what is wrong with the below code and why it does not deliver sms, when i debug no error was found. please can i get help?
public class LaunchSMS extends Activity implements OnClickListener {
private TextView phone;
private TextView phone2;
private EditText TFmsg;
private TextView TVfrom;
Button btnsend;
static final String username = "xxxxxxx";
static final String password = "xxxxxxx";
static String url = "http://www.esmsafrica.com/components/com_spc/smsapi.php";
static final String charset = "UTF-8";
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display);
TFmsg = (EditText) findViewById(R.id.TFmsg);
phone = (TextView) findViewById(R.id.phone);
btnsend = (Button) findViewById(R.id.btnsend);
Button mBtnContacts = (Button) findViewById(R.id.mBtnContacts);
Button btnLogout = (Button) findViewById(R.id.btnlogout);
mBtnContacts.setOnClickListener(this);
btnsend.setOnClickListener(this);
btnLogout.setOnClickListener(this);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data != null) {
Uri uri = data.getData();
if (uri != null) {
Cursor c = null;
try {
c = getContentResolver().query(uri, new String[]{
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.TYPE},
null, null, null);
if (c != null && c.moveToFirst()) {
String number = c.getString(0);
showSelectedNumber(number);
}
} finally {
if (c != null) {
c.close();
}
}
}
}
}
public void showSelectedNumber(String number) {
phone.setText(number);
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.mBtnContacts) {
// user BoD suggests using Intent.ACTION_PICK instead of .ACTION_GET_CONTENT to avoid the chooser
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
// BoD con't: CONTENT_TYPE instead of CONTENT_ITEM_TYPE
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
startActivityForResult(intent, 1);
}
if (v.getId() == R.id.btnsend) {
String reciever = phone.getText().toString();
String message = TFmsg.getText().toString();
if (reciever.length() > 0 && message.length() > 0)
try {
sendSMS(reciever, message);
} catch (Exception e) {
e.printStackTrace();
}
else
Toast.makeText(getBaseContext(),
"Please enter both reciever number and message.",
Toast.LENGTH_SHORT).show();
}
if (v.getId() == R.id.btnlogout) {
logoutUser();
}
}
private void logoutUser() {
Intent intent = new Intent(LaunchSMS.this, Sendsms.class);
startActivity(intent);
finish();
}
public static void sendSMS(String reciever, String message) throws Exception {
System.out.println("Welcome to eSMS");
//To establish the connection and perform the post request
URLConnection connection = new URL(url + "?" + buildRequestString(reciever,message)).openConnection();
connection.setRequestProperty("Accept-Charset", charset);
//This automatically fires the request and we can use it to determine the response status
InputStream response = connection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(response));
//System.out.println(br);
System.out.println(br.readLine());
}
private static String buildRequestString(String reciever, String message) throws UnsupportedEncodingException {
String [] params = new String [5];
params[0] = username;
params[1] = password;
params[2] = message;
params[3] = reciever;
params[4] = "esmsafrica";
String query = String.format("uid=%s&pwd=%s&msg=%s&phone=%s&provider=%s",
URLEncoder.encode(params[0],charset),
URLEncoder.encode(params[1],charset),
URLEncoder.encode(params[2],charset),
URLEncoder.encode(params[3],charset),
URLEncoder.encode(params[4],charset)
);
return query;
}
public static void main(String [] args) throws Exception {
System.out.println("enter Mobile No:");
Scanner scanIn = new Scanner(System.in);
String testPhoneNo = scanIn.nextLine();
scanIn.close();
String testMessage = "Sending Messages";
sendSMS(testPhoneNo, testMessage);
}
}
I have implemented Send SMS from MSG91 messaging service.
public static void sendSMS(String reciever, String message) {
URLConnection myURLConnection=null;
URL myURL=null;
BufferedReader reader=null;
try
{
//prepare connection
myURL = new URL(buildRequestString(reciever, message));
myURLConnection = myURL.openConnection();
myURLConnection.connect();
reader= new BufferedReader(new
InputStreamReader(myURLConnection.getInputStream()));
//reading response
String response;
while ((response = reader.readLine()) != null)
//print response
Log.d("RESPONSE", ""+response);
//finally close connection
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private static String buildRequestString(String reciever, String message){
//encoding message
String encoded_message=URLEncoder.encode(message);
//Send SMS API
String mainUrl="http://api.msg91.com/sendhttp.php?";
//Prepare parameter string
StringBuilder sbPostData= new StringBuilder(mainUrl);
sbPostData.append("authkey="+authkey);
sbPostData.append("&mobiles="+reciever);
sbPostData.append("&message="+encoded_message);
sbPostData.append("&route="+"4");
sbPostData.append("&sender="+"CustomSenderID");
return sbPostData.toString();
}

Android reading from file on SD Card

I am trying to read in some data from a text file I created on my SDcard. However, when I am done reading it in, the stringbuilder is still blank. I don't know if it isn't reading the file. I looked on the android device monitor and the fie exists with data in it. It is on my sdcard inside a "Notes" directory. Here is the code.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
welcomeText = (TextView) findViewById(R.id.welcomeText);
userName = (EditText) findViewById(R.id.userName);
submitButton = (Button) findViewById(R.id.submitButton);
password = (EditText) findViewById(R.id.passInput);
viewAll = (Button) findViewById(R.id.viewAll);
submitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
generateNoteOnSD("info", userName.getText().toString() + "," +password.getText().toString() );
}
});
viewAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
File sdCard = Environment.getExternalStorageDirectory();
File file = new File(sdCard, "info");
String line;
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
br.close();
}
catch (IOException e) {
}
welcomeText.setText("Welcome, " + text);
}
});
}
public void generateNoteOnSD(String sFileName, String sBody){
try
{
File root = new File(Environment.getExternalStorageDirectory(), "Notes");
if (!root.exists()) {
root.mkdirs();
}
File gpxfile = new File(root, sFileName);
FileWriter writer = new FileWriter(gpxfile);
writer.append(sBody);
writer.flush();
writer.close();
Toast.makeText(this, "Saved", Toast.LENGTH_SHORT).show();
}
catch(IOException e)
{
e.printStackTrace();
}
}
Try to change like below
viewAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String fileName = "/Notes/info";
File myFile = new File(baseDir + File.separator + fileName);
try {
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
String text = "";
String aDataRow = "";
while ((aDataRow = myReader.readLine()) != null) {
text += aDataRow + "\n";
}
}
catch (IOException e) {
}
welcomeText.setText("Welcome, " + text);
}
});

Reading/Writing database error

I have a read and write operation at a android app. On onCreate, a file will be read and display it to an editext and can be editted. When the save is pressed, the data will be written to the same file that will be read on onCreate. But I got an error. No such file in directory. I don't get it. I'm creating the file when the save button is pressed. Any ideas?
Java code:
EditText Name;
EditText Age;
EditText Height;
EditText Weight;
EditText MedHistory;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_medicalhistory);
Name = (EditText) findViewById(R.id.medhistName);
Age = (EditText) findViewById(R.id.medhistAge);
Height = (EditText) findViewById(R.id.medhistHeight);
Weight = (EditText) findViewById(R.id.medhistWeight);
MedHistory = (EditText) findViewById(R.id.MedHist);
int i = 0;
String MedHistData[] = new String[5];
try {
File myFile = new File("/data/data/Project.Package.Structure/files/MedicalHistory.txt");
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(new InputStreamReader(fIn));
String aDataRow = "";
while ((aDataRow = myReader.readLine()) != null)
{
MedHistData[i] = aDataRow;
i++;
}
i = 0;
Name.setText(MedHistData[0]);
Age.setText(MedHistData[1]);
Height.setText(MedHistData[2]);
Weight.setText(MedHistData[3]);
MedHistory.setText(MedHistData[4]);
myReader.close();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
Button Save = (Button) findViewById(R.id.SaveBtn);
Save.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try {
File myFile = new File("/data/data/Project.Package.Structure/files/MedicalHistory.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(Name.getText() + "\n");
myOutWriter.append(Age.getText() + "\n");
myOutWriter.append(Height.getText() + "\n");
myOutWriter.append(Weight.getText() + "\n");
myOutWriter.append(MedHistory.getText());
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),
"Medical History Saved'",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
});
}
You should use openFileInput() method to open file for reading and openFileOutput() for writing. These functions return a FileInputStream and FileOutputStream respectively.
My guess: you don't have write access to the file.
You only can access specific folders for writing in android.
Have a look at
http://developer.android.com/guide/topics/data/data-storage.html#filesInternal
They have a simple example on how to write a text file.

Categories