无法将我的edittext保存为txt文件。 Android的

时间:2015-08-02 17:15:05

标签: android android-edittext save android-sdcard

您好我正在构建一个加载文本文件的Android应用程序,然后允许用户编辑它。我有这个工作。我现在希望能够将该edittext数据保存为设备根目录或SD卡上的新txt文件。到目前为止,这是我的代码:

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

我在操作栏上有一个按钮来保存文件。以下是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>

当应用程序崩溃时,saveFile似乎无法找到edittext loadedtext。任何帮助都会很棒。

编辑:

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)

这些是我在实现下面的修复后现在得到的新错误。不是很擅长调试但看起来这可能是gettext命令的问题?

1 个答案:

答案 0 :(得分:1)

在xml文件上设置以下xml代码

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

        <requestFocus />
    </EditText>

请将EditText LoadedText声明为全局变量外侧onCreate()方法,并在onCreate()内定义,如下面的代码

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

并解决保存文件的问题使用以下保存功能

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

并将以下权限设置为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>