weixin_43890706
雪狼之眼
2020-04-07 13:49
采纳率: 100%
浏览 446

安卓开发 java.lang.RuntimeException: Unable to start activity ComponentInfo{(xxx)}: java.lang.NullPointerException

安卓开发实验预习,代码没有报错,虚拟机运行(API19)闪退,不知道哪里出了问题

Activity:

package com.example.ght201621111093_yuxi3_1;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {
    SharedPreferences sp;//数据读写变量  
    Editor edit; //Editor编辑对象
    /* 定义账户 和密码的控件变量 定义登录按钮的控件变量 */
    private Button delete,saveINSIDE,saveSD,saveSP,readINSIDE,readSD,readSP;
    private EditText stu_name,stu_age,stu_number;
    // 1 定义记住密码控件变量以及文件操作变量


    private File sdCardDir;//sd卡路径
    private File saveFile;//文件名
    private FileOutputStream outStream;//输入文件流
    private FileInputStream inStream;//输入文件


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        delete = (Button) findViewById(R.id.delete);
        saveINSIDE = (Button) findViewById(R.id.saveINSIDE);
        saveSD = (Button) findViewById(R.id.saveSD);
        saveSP = (Button) findViewById(R.id.saveSP);
        readINSIDE = (Button) findViewById(R.id.readINSIDE);
        readSD = (Button) findViewById(R.id.readSD);
        readSP = (Button) findViewById(R.id.readSP);

        stu_name = (EditText) findViewById(R.id.et_name);
        stu_age = (EditText) findViewById(R.id.et_age);
        stu_number = (EditText) findViewById(R.id.et_num);

        super.onCreate(savedInstanceState);

        setContentView(R.layout.login);

        //利用edit()方法获取Editor对象。
        edit = sp.edit();  
        /* 账户 和密码的控件变量赋值 登录按钮的控件变量 赋值 */

        // 4 完成用户名密码的保存功能
        //m_pswSave = (CheckBox) findViewById(R.id.checkBox1);
        // 为每一个选项设置监听
        //清除
        delete.setOnClickListener(new OnClickListener(){
            public void onClick(View v){
                stu_name.setText("");
                stu_age.setText("");
                stu_number.setText("");
        }
        });
        //保存内部
        saveINSIDE.setOnClickListener(new OnClickListener(){
            public void onClick(View v) {
                final String a=stu_age.getText().toString();
                int a1= Integer.parseInt(a);
                if (a1<1||a1>100) {
                    Toast toast = Toast.makeText(getApplicationContext(),
                            "请输入正确的年龄", Toast.LENGTH_SHORT);
                    toast.show();
                } else {
                    Write_Files_INSIDE("name.txt",stu_name.getText().toString());
                    Write_Files_INSIDE("age.txt",stu_age.getText().toString());
                    Write_Files_INSIDE("number.txt",stu_number.getText().toString());
                }
            }

        });
        //保存SD
        saveSD.setOnClickListener(new OnClickListener(){
            public void onClick(View v) {
                final String a=stu_age.getText().toString();
                int a1= Integer.parseInt(a);
                if (a1<1||a1>100) {
                    Toast toast = Toast.makeText(getApplicationContext(),
                            "请输入正确的年龄", Toast.LENGTH_SHORT);
                    toast.show();
                }  else {
                    Write_Files_SD("name.txt",stu_name.getText().toString());
                    Write_Files_SD("age.txt",stu_age.getText().toString());
                    Write_Files_SD("number.txt",stu_number.getText().toString());
                }
            }
        });
        //保存SP
        saveSP.setOnClickListener(new OnClickListener(){
            public void onClick(View v) {
                final String a=stu_age.getText().toString();
                int a1= Integer.parseInt(a);
                if (a1<1||a1>100) {
                    Toast toast = Toast.makeText(getApplicationContext(),
                            "请输入正确的年龄", Toast.LENGTH_SHORT);
                    toast.show();
                }  else {
                    //通过Editor对象存储key-value键值对数据
                    edit.putString("name",stu_name.getText().toString()); 
                    edit.putString("age",stu_age.getText().toString()); 
                    edit.putString("number",stu_number.getText().toString()); 
                    //通过commit()方法提交数据
                    edit.commit();  
                }
            }
        });
        //读取INSIDE
        readINSIDE.setOnClickListener(new OnClickListener(){
            public void onClick(View v) {
                if(null!=Read_Files_INSIDE("name.txt"))
                {
                    stu_name.setText(Read_Files_INSIDE("name.txt"));
                }
                if(null!=Read_Files_INSIDE("age.txt"))
                {
                    stu_age.setText(Read_Files_INSIDE("age.txt"));
                }
                if(null!=Read_Files_INSIDE("number.txt"))
                {
                    stu_number.setText(Read_Files_INSIDE("number.txt"));
                }
            }
        });
        //读取SD
        readSD.setOnClickListener(new OnClickListener(){
            public void onClick(View v) {
                if(null!=Read_Files_INSIDE("name.txt"))
                {
                    stu_name.setText(Read_Files_INSIDE("name.txt"));
                }
                if(null!=Read_Files_INSIDE("age.txt"))
                {
                    stu_age.setText(Read_Files_INSIDE("age.txt"));
                }
                if(null!=Read_Files_INSIDE("number.txt"))
                {
                    stu_number.setText(Read_Files_INSIDE("number.txt"));
                }
            }
        });
        //读取SP
        readSP.setOnClickListener(new OnClickListener(){
            public void onClick(View v) {
                if(null!=sp.getString("name",""))
                {
                    stu_name.setText(sp.getString("name",""));
                }
                if(null!=sp.getString("age",""))
                {
                    stu_age.setText(sp.getString("age",""));
                }
                if(null!=sp.getString("number",""))
                {
                    stu_number.setText(sp.getString("number",""));
                }
            }
        });
    }
        /*
        //5 INSIDE读取功能
        if(null!=Read_Files_INSIDE("name.txt"))
        {
            name.setText(Read_Files_INSIDE("name.txt"));
        }
        if(null!=Read_Files_INSIDE("age.txt"))
        {
            age.setText(Read_Files_INSIDE("age.txt"));
        }
        if(null!=Read_Files_INSIDE("number.txt"))
        {
            number.setText(Read_Files_INSIDE("number.txt"));
        }
        //5 SD读取功能
        if(null!=Read_Files_SD("name.txt"))
        {
            name.setText(Read_Files_SD("name.txt"));
        }
        if(null!=Read_Files_SD("age.txt"))
        {
            age.setText(Read_Files_SD("age.txt"));
        }
        if(null!=Read_Files_SD("number.txt"))
        {
            number.setText(Read_Files_SD("number.txt"));
        }
        //5 SP读取功能
        if(null!=sp.getString("name",""))
        {
            name.setText(sp.getString("name",""));
        }
        if(null!=sp.getString("age",""))
        {
            age.setText(sp.getString("age",""));
        }
        if(null!=sp.getString("number",""))
        {
            number.setText(sp.getString("number",""));
        }
        */


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    //2 INSIDE完成文件写操作功能
        private void Write_Files_INSIDE(String fileName, String strContent) {

             try {
                 FileOutputStream outStream=this.openFileOutput(fileName,Context.MODE_WORLD_READABLE);
                 outStream.write(strContent.getBytes());
                 outStream.close();
                 Toast.makeText(this,"文件保存成功",Toast.LENGTH_LONG).show();
             } catch (FileNotFoundException e) {
                 return;
             }
             catch (IOException e){
                 return ;
             }
        }

        // 3 INSIDE读操作功能
        private String Read_Files_INSIDE(String fileName) {
            try {
                 FileInputStream inStream=this.openFileInput(fileName);
                 ByteArrayOutputStream stream=new ByteArrayOutputStream();
                 byte[] buffer=new byte[1024];
                 int length=-1;


             while((length=inStream.read(buffer))!=-1)   {
                     stream.write(buffer,0,length);
                 }



                 stream.close();
                 inStream.close();           
                 Toast.makeText(this,"文件读取成功",Toast.LENGTH_LONG).show();
                 return stream.toString();
             } catch (FileNotFoundException e) {
                 e.printStackTrace();
                 return null;
             }
             catch (IOException e){
                 return null;
             }
        }
            //2 SD文件写操作功能
            private void Write_Files_SD(String fileName, String strContent) {

                sdCardDir = Environment.getExternalStorageDirectory();
                saveFile = new File(sdCardDir, fileName);

                if (Environment.getExternalStorageState().equals(
                        Environment.MEDIA_MOUNTED)) {

                    // 创建 初始化 流对象
                    try {

                        outStream = new FileOutputStream(saveFile);
                    } catch (FileNotFoundException e) {
                        Toast.makeText(this, "文件不存在!", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    try {

                        // 把内容写入文件
                        outStream.write(strContent.getBytes());

                    } catch (FileNotFoundException e) {

                        // TODO Auto-generated catch block
                        Toast.makeText(this, "文件未发现异常!", Toast.LENGTH_SHORT).show();

                    } catch (IOException e) {

                        // TODO Auto-generated catch block
                        Toast.makeText(this, "文件读写异常!", Toast.LENGTH_SHORT).show();

                    } catch (NullPointerException e) {
                        Toast.makeText(this, "文件读写空指针异常!", Toast.LENGTH_SHORT).show();
                    } finally {

                        try {

                            // 关闭文件输出流

                            outStream.close();

                        } catch (IOException e) {

                            // TODO Auto-generated catch block
                            Toast.makeText(this, "文件读写异常!", Toast.LENGTH_SHORT).show();

                        }

                        Toast.makeText(this, "文件写入成功!", Toast.LENGTH_SHORT).show();

                    }

                } else {
                    Toast.makeText(this, "内存卡不存在!", Toast.LENGTH_SHORT).show();
                    return;
                }

            }

            // 3 SD文件读操作功能
            private String Read_Files_SD(String fileName) {
                sdCardDir = Environment.getExternalStorageDirectory();
                saveFile = new File(sdCardDir, fileName);
                int len;
                // 然后创建一个字节数组输出流
                byte[] buffer = new byte[1024];

                ByteArrayOutputStream ostream = new ByteArrayOutputStream();

                if (Environment.getExternalStorageState().equals(
                        Environment.MEDIA_MOUNTED)) {

                    // 创建 初始化 流对象
                    try {
                        inStream = new FileInputStream(saveFile);
                        Log.v("Instance inStream", "实例化inStream!");
                    } catch (FileNotFoundException e) {
                        Toast.makeText(this, "文件不存在!", Toast.LENGTH_SHORT).show();
                        return null;
                    }

                    try {

                        Log.v("Read", "读数据!");
                        Toast.makeText(this, "文件读取成功!", Toast.LENGTH_SHORT).show();

                        while ((len = inStream.read(buffer)) != -1) {
                            ostream.write(buffer, 0, len);

                        }

                        Log.v("Read", "读成功!");

                    } catch (IOException e) {
                        Toast.makeText(this, "读 异常!", Toast.LENGTH_SHORT).show();
                    }

                    try {
                        // 最后关闭输入流和输出流
                        inStream.close();
                        ostream.close();

                        Log.v("Read", "读成功!");

                    } catch (IOException e) {
                        Toast.makeText(this, "读 异常!", Toast.LENGTH_SHORT).show();
                    }

                    String str = new String(ostream.toByteArray());

                    Log.v("Disp", "文本显示!");

                    return str;

                } else {
                    Toast.makeText(this, "内存卡不存在!", Toast.LENGTH_SHORT).show();
                    return null;
                }
            }

}

layout:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <EditText
        android:id="@+id/et_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:ems="10" />

    <Button
        android:id="@+id/saveINSIDE"
        android:layout_width="135dp"
        android:layout_height="50dp"
        android:layout_alignLeft="@+id/delete"
        android:layout_below="@+id/delete"
        android:layout_marginTop="21dp"
        android:text="保存内部" />

    <Button
        android:id="@+id/saveSD"
        android:layout_width="135dp"
        android:layout_height="50dp"
        android:layout_alignLeft="@+id/saveINSIDE"
        android:layout_below="@+id/saveINSIDE"
        android:layout_marginTop="18dp"
        android:text="保存SD" />

    <Button
        android:id="@+id/saveSP"
        android:layout_width="135dp"
        android:layout_height="50dp"
        android:layout_alignLeft="@+id/saveSD"
        android:layout_below="@+id/saveSD"
        android:layout_marginTop="22dp"
        android:text="保存SP" />

    <Button
        android:id="@+id/readINSIDE"
        android:layout_width="135dp"
        android:layout_height="50dp"
        android:layout_alignBottom="@+id/saveINSIDE"
        android:layout_alignRight="@+id/et_age"
        android:text="读取内部" />

    <Button
        android:id="@+id/readSD"
        android:layout_width="135dp"
        android:layout_height="50dp"
        android:layout_alignBaseline="@+id/saveSD"
        android:layout_alignBottom="@+id/saveSD"
        android:layout_alignLeft="@+id/readINSIDE"
        android:text="读取SD" />

    <Button
        android:id="@+id/readSP"
        android:layout_width="135dp"
        android:layout_height="50dp"
        android:layout_alignBaseline="@+id/saveSP"
        android:layout_alignBottom="@+id/saveSP"
        android:layout_alignRight="@+id/readSD"
        android:text="读取SP" />

    <TextView
        android:id="@+id/age"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/delete"
        android:layout_below="@+id/name"
        android:layout_marginTop="34dp"
        android:text="年龄:" />

    <EditText
        android:id="@+id/et_age"
        android:layout_width="wrap_content"
        android:inputType="number"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/age"
        android:layout_alignLeft="@+id/et_name"
        android:ems="10" />

    <EditText
        android:id="@+id/et_num"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/et_age"
        android:layout_below="@+id/et_age"
        android:layout_marginTop="18dp"
        android:ems="10" />

    <TextView
        android:id="@+id/number"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/et_num"
        android:layout_alignLeft="@+id/age"
        android:text="学号:" />

    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/et_name"
        android:layout_alignLeft="@+id/age"
        android:text="姓名:" />

    <Button
        android:id="@+id/delete"
        android:layout_width="135dp"
        android:layout_height="50dp"
        android:layout_below="@+id/et_num"
        android:layout_marginTop="17dp"
        android:text="清除" />

</RelativeLayout>

Logcat:

04-07 13:23:38.877: W/dalvikvm(1340): threadid=1: thread exiting with uncaught exception (group=0xb3a77b90)
04-07 13:23:38.887: E/AndroidRuntime(1340): FATAL EXCEPTION: main
04-07 13:23:38.887: E/AndroidRuntime(1340): Process: com.example.ght201621111093_yuxi3_1, PID: 1340
04-07 13:23:38.887: E/AndroidRuntime(1340): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.ght201621111093_yuxi3_1/com.example.ght201621111093_yuxi3_1.MainActivity}: java.lang.NullPointerException
04-07 13:23:38.887: E/AndroidRuntime(1340):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2176)
04-07 13:23:38.887: E/AndroidRuntime(1340):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2226)
04-07 13:23:38.887: E/AndroidRuntime(1340):     at android.app.ActivityThread.access$700(ActivityThread.java:135)
04-07 13:23:38.887: E/AndroidRuntime(1340):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1397)
04-07 13:23:38.887: E/AndroidRuntime(1340):     at android.os.Handler.dispatchMessage(Handler.java:102)
04-07 13:23:38.887: E/AndroidRuntime(1340):     at android.os.Looper.loop(Looper.java:137)
04-07 13:23:38.887: E/AndroidRuntime(1340):     at android.app.ActivityThread.main(ActivityThread.java:4998)
04-07 13:23:38.887: E/AndroidRuntime(1340):     at java.lang.reflect.Method.invokeNative(Native Method)
04-07 13:23:38.887: E/AndroidRuntime(1340):     at java.lang.reflect.Method.invoke(Method.java:515)
04-07 13:23:38.887: E/AndroidRuntime(1340):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
04-07 13:23:38.887: E/AndroidRuntime(1340):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
04-07 13:23:38.887: E/AndroidRuntime(1340):     at dalvik.system.NativeStart.main(Native Method)
04-07 13:23:38.887: E/AndroidRuntime(1340): Caused by: java.lang.NullPointerException
04-07 13:23:38.887: E/AndroidRuntime(1340):     at com.example.ght201621111093_yuxi3_1.MainActivity.onCreate(MainActivity.java:57)
04-07 13:23:38.887: E/AndroidRuntime(1340):     at android.app.Activity.performCreate(Activity.java:5243)
04-07 13:23:38.887: E/AndroidRuntime(1340):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
04-07 13:23:38.887: E/AndroidRuntime(1340):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2140)
04-07 13:23:38.887: E/AndroidRuntime(1340):     ... 11 more

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • as_csdn
    代码的灵魂是bug! 2020-04-07 14:53
    已采纳

    oncreate里面有问题,正确代码应该是

    @Override
        protected void onCreate(Bundle savedInstanceState) {
                    super.onCreate(savedInstanceState);
            setContentView(R.layout.login);
    
            delete = (Button) findViewById(R.id.delete);
            saveINSIDE = (Button) findViewById(R.id.saveINSIDE);
            saveSD = (Button) findViewById(R.id.saveSD);
            saveSP = (Button) findViewById(R.id.saveSP);
            readINSIDE = (Button) findViewById(R.id.readINSIDE);
            readSD = (Button) findViewById(R.id.readSD);
            readSP = (Button) findViewById(R.id.readSP);
    
            stu_name = (EditText) findViewById(R.id.et_name);
            stu_age = (EditText) findViewById(R.id.et_age);
            stu_number = (EditText) findViewById(R.id.et_num);
    
    
    点赞 评论

相关推荐