【问题标题】:Write to File from string in android从android中的字符串写入文件
【发布时间】:2016-04-22 23:43:54
【问题描述】:

我试图制作一个可以预订空置教室的应用程序,但是当我从文件中读取时它很好,但是当我写一个获取空指针引用错误时 它是我试图存储在文件中的字符串,这是我的代码。 当我点击前一个意图的按钮来进入这个意图应用程序崩溃时。但是如果我评论“button.setOnClickListener(new View.OnClickListener()”这个块它工作正常。

public class result extends AppCompatActivity {

Button button;
TextView tv1;
TextView tv2;
TextView tv3;
EditText ed1;
public String f;
public static String[] strarray = new String[3];
public String slot;
public int roomno;


String[] mystr = null;

int i = 0,j;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_result);
    Intent intent = getIntent();
    f = intent.getExtras().getString("day");
    slot=intent.getExtras().getString("time");
    tv1 = (TextView) findViewById(R.id.tv1);
    tv1.setText(f);
    tv1 = (TextView) findViewById(R.id.tv1);
    tv2 = (TextView) findViewById(R.id.tv2);
    tv3 = (TextView) findViewById(R.id.tv3);


    InputStream fin = null;
    try {
        fin = openFileInput(f);
    } catch (FileNotFoundException e1) {
        e1.printStackTrace();
    }
    InputStreamReader ip = new InputStreamReader(fin);
    BufferedReader br = new BufferedReader(ip);
    int c;
    String str = "";
    String abc = "";
    String def = "";
    String xyz = "";
    int j=0;
    try {
        while((str = br.readLine())!= null)
        {

            String temp[] = str.split(" ");
            if (temp[0].compareTo(slot) == 0) {


                if(temp[1].compareTo("0") == 0) {
                    abc = "1301";
                    tv1.setText(abc);
                }
                if(temp[2].compareTo("0") == 0) {
                    def = "1302";
                    tv2.setText(def);
                }
                if(temp[3].compareTo("0") == 0) {
                    xyz = "1303";
                    tv3.setText(xyz);
                }
            }
        }

    } catch (IOException e1) {
        e1.printStackTrace();
    }





   // Toast.makeText(getBaseContext(), "file read", Toast.LENGTH_SHORT).show();
    button.setOnClickListener(new View.OnClickListener() {
        @Override

        public void onClick(View v) {
            int i = 0,j;
            String line;

            try {
                BufferedReader br = new BufferedReader(new FileReader(f));
                StringBuffer str = new StringBuffer();

                while((line = br.readLine()) != null)
                {
                    strarray[i] = line;     //Store each line i file in string array.
                    i++;
                }
                for(j=0; j<=i; j++)
                {
                    if(j==0)            //This i hav taken for 2nd slot (starting from 0)
                    //make it if(j==timeslot/time-1)
                    {
                        String temp = strarray[j];
                        //temp = trim(temp);
                        mystr = temp.split(" ",4);          //Processing that particular line ka string.
                        for(int k=0; k<4; k++)
                            //System.out.println(mystr[k]);
                        mystr[roomno] = "1";                        //Changing from 0 to 1 where classroom = 1301 hence here index=1 in mystr[1] = '1'.
                        //Make it mystr[roomno] = "1";


                        str.append(mystr[0]);
                        str.append(" ");
                        str.append(mystr[1]);
                        str.append(" ");
                        str.append(mystr[2]);           //Creating a new changed string
                        str.append(" ");
                        str.append(mystr[2]);



                        strarray[j] = str.toString();   //Since its a buffer convert it to string.

                    }
                }

                br.close();

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            FileWriter fileWriter = null;
            try {
                fileWriter = new FileWriter(f);
            } catch (IOException e) {
                e.printStackTrace();
            }

            // Always wrap FileWriter in BufferedWriter.
            BufferedWriter b = new BufferedWriter(fileWriter);

            for(int m=0; m<3; m++)
            {
                String temp = strarray[m];   //Write back everything to a file.
                try {
                    b.write(temp);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    b.newLine();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                b.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                b.close();
            } catch (IOException e) {
                e.printStackTrace();
            }



        }});
    }

}

已编辑:logcat

ActivityRecord{bd77102 u0 demo.myapplication/.login t49 f}} 无效;您的活动正在运行吗? 04-23 05:57:40.028 1298-1317/? W/WindowManager:视图未成功添加到 wm,正在删除视图 04-23 05:57:40.028 1298-1317/? W/WindowManager:添加启动窗口时出现异常 java.lang.IllegalArgumentException: View=com.android.internal.policy.PhoneWindow$DecorView{230ab45 V.E...... R.....ID 0,0-0,0} 未附加到窗口管理器 在 android.view.WindowManagerGlobal.findViewLocked(WindowManagerGlobal.java:424) 在 android.view.WindowManagerGlobal.removeView(WindowManagerGlobal.java:350) 在 android.view.WindowManagerImpl.removeViewImmediate(WindowManagerImpl.java:116) 在 com.android.server.policy.PhoneWindowManager.addStartingWindow(PhoneWindowManager.java:2359) 在 com.android.server.wm.WindowManagerService$H.handleMessage(WindowManagerService.java:7840) 在 android.os.Handler.dispatchMessage(Handler.java:102) 在 android.os.Looper.loop(Looper.java:148) 在 android.os.HandlerThread.run(HandlerThread.java:61) 在 com.android.server.ServiceThread.run(ServiceThread.java:46) 04-23 05:57:40.070 1298-1661/? I/ActivityManager: Killing 2036:com.android.providers.calendar/u0a1 (adj 15): empty for 6000s 04-23 05:57:40.095 2336-2353/? I/OpenGLRenderer:初始化的 EGL,版本 1.4 04-23 05:57:40.097 4016-4016/? W/System:ClassLoader 引用了未知路径:/data/app/demo.myapplication-2/lib/x86 04-23 05:57:40.124 2336-2353/? W/EGL_emulation:eglSurfaceAttrib 未实现 04-23 05:57:40.124 2336-2353/? W/OpenGLRenderer:无法在表面 0xa3818be0 上设置 EGL_SWAP_BEHAVIOR,错误 = EGL_SUCCESS 04-23 05:57:40.177 1298-1426/? W/InputMethodManagerService:得到 RemoteException 向 pid 3978 uid 10060 发送 setActive(false) 通知 04-23 05:57:40.273 1505-2475/? E/Surface:getSlotFromBufferLocked:未知缓冲区:0xb3fd66e0 04-23 05:57:40.785 4034-4034/? D/AndroidRuntime: >>>>>> START com.android.internal.os.RuntimeInit uid 0 >>>>> START com.android.internal.os.RuntimeInit uid 0

【问题讨论】:

  • 总是有助于包含确切的错误消息。

标签: android string file file-handling


【解决方案1】:

您不能对从未初始化为非空的 Button 引用调用 setContentView()。

试试类似的东西

button = (Button) findViewById(R.id.whateverYouCalledYourButtonInTheXML);

您随后的错误是:

open failed: EROFS (Read-only file system

如果您未能指定适当的位置,这往往表明您正在尝试写入不允许的位置(可能是设备的根目录)中的文件。您可能需要添加类似 getFilesDir() 在有效上下文(例如您的 Activity 本身)上调用的结果。

【讨论】:

  • 感谢帮助现在能够转到“结果”活动,但现在当我单击结果活动按钮时应用程序崩溃
  • “应用程序崩溃”在这里不是可接受的问题陈述。不过,您的 try/catch 设置不是很好 - 您已经处理了失败,然后继续尝试使用 try{} 之外的结果,即使它失败了。
  • 在日志前面查看获取 FileWriter 是否失败,并在代码中添加一些积极的日志记录以查看是否有效。
  • 添加了从第一个活动到最后一个活动的整个日志
猜你喜欢
  • 1970-01-01
  • 2012-12-31
  • 1970-01-01
  • 2011-07-12
  • 2014-07-28
  • 2019-09-18
  • 2011-10-24
相关资源
最近更新 更多