Ryan Moseley
Ryan Moseley

Reputation: 11

Can't save my edittext as a txt file. Android

Hi I am building an android app that loads a text file and then allows the user to edit it. I have this working. I now want to be able to save that edittext data as a new txt file on the root of the device or the sdcard. Here is my code so far:

package com.example.ryan.ciscorouterhelper;

import android.app.Activity;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;


public class MainActivity extends Activity {
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        EditText LoadedText = new EditText(this);
        setContentView(LoadedText);
        AssetManager assetManager = getAssets();
        InputStream Reader = null;
        try {
            Reader = assetManager.open("text.txt");
            String text = loadTextFile(Reader);
            LoadedText.setText(text);
        } catch (IOException e) {
            LoadedText.setText("Couldn't load file");
        } finally {
            if (Reader != null)
                try {
                    Reader.close();
                } catch (IOException e) {
                    LoadedText.setText("Couldn't close file");
                }
        }
    }

    public String loadTextFile(InputStream Reader) throws IOException {
        ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
        byte[] bytes = new byte[4096];
        int len;
        while ((len = Reader.read(bytes)) > 0)
            byteStream.write(bytes, 0, len);
        return new String(byteStream.toByteArray(), "UTF8");
    }
   public void saveFile(MenuItem item) {
      try {
            FileOutputStream fileout=openFileOutput("RouterSetup.txt", MODE_PRIVATE);
          OutputStreamWriter outputWriter=new OutputStreamWriter(fileout);
          outputWriter.write(LoadedText.getText().toString());
            outputWriter.close();

            //display file saved message
           Toast.makeText(getBaseContext(), "File saved successfully!",
                    Toast.LENGTH_SHORT).show();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

I have a button on the Action bar to save the file. Here is the code from the menu_main.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context=".MainActivity">
    <item android:id="@+id/action_settings" android:title="@string/action_settings"
        android:orderInCategory="100" android:showAsAction="never"
        />
    <item android:id="@+id/action_save"
        android:title="@string/action_save"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:icon="@drawable/ic_save_black_48dp"
    android:showAsAction="ifRoom"
        android:onClick="saveFile"
    />
</menu>

At the moment the app crashes as the saveFile can't seem to find the edittext loadedtext. Any help would be great.

EDIT:

08-02 21:53:43.985    1113-1113/com.example.ryan.ciscorouterhelper W/System.err﹕ java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
08-02 21:53:44.024    1113-1113/com.example.ryan.ciscorouterhelper W/System.err﹕ at com.example.ryan.ciscorouterhelper.MainActivity.saveFile(MainActivity.java:57)
08-02 21:53:44.024    1113-1113/com.example.ryan.ciscorouterhelper W/System.err﹕ at java.lang.reflect.Method.invoke(Native Method)
08-02 21:53:44.024    1113-1113/com.example.ryan.ciscorouterhelper W/System.err﹕ at java.lang.reflect.Method.invoke(Method.java:372)
08-02 21:53:44.024    1113-1113/com.example.ryan.ciscorouterhelper W/System.err﹕ at android.view.MenuInflater$InflatedOnMenuItemClickListener.onMenuItemClick(MenuInflater.java:254)
08-02 21:53:44.024    1113-1113/com.example.ryan.ciscorouterhelper W/System.err﹕ at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:147)
08-02 21:53:44.024    1113-1113/com.example.ryan.ciscorouterhelper W/System.err﹕ at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:904)
08-02 21:53:44.024    1113-1113/com.example.ryan.ciscorouterhelper W/System.err﹕ at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:894)
08-02 21:53:44.024    1113-1113/com.example.ryan.ciscorouterhelper W/System.err﹕ at android.widget.ActionMenuView.invokeItem(ActionMenuView.java:587)
08-02 21:53:44.024    1113-1113/com.example.ryan.ciscorouterhelper W/System.err﹕ at com.android.internal.view.menu.ActionMenuItemView.onClick(ActionMenuItemView.java:141)
08-02 21:53:44.024    1113-1113/com.example.ryan.ciscorouterhelper W/System.err﹕ at android.view.View.performClick(View.java:4761)
08-02 21:53:44.024    1113-1113/com.example.ryan.ciscorouterhelper W/System.err﹕ at android.view.View$PerformClick.run(View.java:19767)
08-02 21:53:44.025    1113-1113/com.example.ryan.ciscorouterhelper W/System.err﹕ at android.os.Handler.handleCallback(Handler.java:739)
08-02 21:53:44.025    1113-1113/com.example.ryan.ciscorouterhelper W/System.err﹕ at android.os.Handler.dispatchMessage(Handler.java:95)
08-02 21:53:44.025    1113-1113/com.example.ryan.ciscorouterhelper W/System.err﹕ at android.os.Looper.loop(Looper.java:135)
08-02 21:53:44.025    1113-1113/com.example.ryan.ciscorouterhelper W/System.err﹕ at android.app.ActivityThread.main(ActivityThread.java:5312)
08-02 21:53:44.025    1113-1113/com.example.ryan.ciscorouterhelper W/System.err﹕ at java.lang.reflect.Method.invoke(Native Method)
08-02 21:53:44.025    1113-1113/com.example.ryan.ciscorouterhelper W/System.err﹕ at java.lang.reflect.Method.invoke(Method.java:372)
08-02 21:53:44.025    1113-1113/com.example.ryan.ciscorouterhelper W/System.err﹕ at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
08-02 21:53:44.025    1113-1113/com.example.ryan.ciscorouterhelper W/System.err﹕ at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)

These are the new errors i now get after implementing the fix below.Not very good at debugging yet but looks like it could be an issue with the gettext command?

Upvotes: 0

Views: 1073

Answers (1)

Salah Nour ElDin
Salah Nour ElDin

Reputation: 508

Set on xml file the following xml code

<EditText
        android:id="@+id/LoadedText "
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="textMultiLine" >

        <requestFocus />
    </EditText>

Please declare EditText LoadedText as Global variable out side onCreate() Method and define it inside onCreate() like following code

EditText LoadedText;
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        LoadedText=(EditText) findViewById(R.id.LoadedText);
        AssetManager assetManager = getAssets();
        InputStream Reader = null;
        try {
            Reader = assetManager.open("text.txt");
            String text = loadTextFile(Reader);
            LoadedText.setText(text);
        } catch (IOException e) {
            LoadedText.setText("Couldn't load file");
        } finally {
            if (Reader != null)
                try {
                    Reader.close();
                } catch (IOException e) {
                    LoadedText.setText("Couldn't close file");
                }
        }
    }

and to solve problem of Saving file use the following Save Function

 public void saveFile(MenuItem item) {
         try {

             File  myFile = new File("/sdcard/RouterSetup.txt");
                myFile.createNewFile();
            FileOutputStream fOut = new FileOutputStream(myFile);
            OutputStreamWriter myOutWriter = 
                                    new OutputStreamWriter(fOut);
            myOutWriter.append(LoadedText.getText());
            myOutWriter.close();
            fOut.close();
            Toast.makeText(getBaseContext(),
                    "Done writing SD " + LoadedText.getText() + ".txt",
                    Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            Toast.makeText(getBaseContext(), e.getMessage(),
                    Toast.LENGTH_SHORT).show();
        }
        }

and set the following permission to AndroidManifest.xml

 <uses-permission android:name="android.permission.INTERNET"></uses-permission>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
    <uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>

Upvotes: 1

Related Questions