liuboris.slan 2021-11-20 19:52 采纳率: 100%
浏览 81
已结题

Android studio中向listview数据表中插入数据页面闪退问题,望解答!

问题遇到的现象和发生背景

Activity

import androidx.appcompat.app.AppCompatActivity;

import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class EnteringActivity extends AppCompatActivity implements View.OnClickListener {
    private EditText et_word;
    private EditText et_translate;
    private MyDAO myDAO;
    private ListView listView;
    private List<Map<String, Object>> listData;
    private Map<String, Object> listItem;
    private SimpleAdapter listAdapter;
    private String selId = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_entering);

        Button bt_enter = findViewById(R.id.bt_enter);
        bt_enter.setOnClickListener(this);

        myDAO = new MyDAO(this);
        if (myDAO.getRecordsNumber() == 0) {
            myDAO.insertInfo("apple", "苹果");
            myDAO.insertInfo("banana", "香蕉");
        }
        displayRecords();
    }

    private void displayRecords() {
        listView = findViewById(R.id.listview2);
        listData = new ArrayList<Map<String, Object>>();
        Cursor cursor = myDAO.allQuery();
        while (cursor.moveToNext()) {
            int id = cursor.getInt(0);
            String word = cursor.getString(1);
            String mean = cursor.getString(2);
            listItem = new HashMap<String, Object>();
            listItem.put("_id", id);
            listItem.put("word", word);
            listItem.put("mean", mean);
            listData.add(listItem);
        }
        listAdapter = new SimpleAdapter(this,
                listData,
                R.layout.list_item,
                new String[]{"_id", "word", "mean"},
                new int[]{R.id.tv_id, R.id.tv_word, R.id.tv_mean});
        listView.setAdapter(listAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Map<String, Object> rec = (Map<String, Object>) listAdapter.getItem(i);
                et_word.setText(rec.get("word").toString());
                et_translate.setText(rec.get("mean").toString());
                Log.i("ly", rec.get("_id").toString());
                selId = rec.get("_id").toString();
            }
        });
    }

    @Override
    public void onClick(View view) {

//        if (selId != null) {
        String  p1 = et_word.getText().toString();
        String p2 = et_translate.getText().toString();
            if (view.getId() == R.id.bt_enter) {

                Log.i("msg", "录入 ");

                if (p1.equals("") || p2.equals("")) {
                    Toast.makeText(getApplicationContext(), "请输入单词信息", Toast.LENGTH_SHORT).show();
                } else {
                    myDAO.insertInfo(p1,p2);
                }
            }
//
//        } else {
//            if (view.getId() == R.id.bt_enter) {
//                String p1 = et_word.getText().toString();
//                String p2 = et_translate.getText().toString();
//                if (p1.equals("") || p2.equals("")) {
//                    Toast.makeText(getApplicationContext(), "请填写录入的单词信息!", Toast.LENGTH_SHORT).show();
//                } else {
//                    myDAO.insertInfo(p1, p2);
//                }
//            }
//        }
//        displayRecords();
    }
}

问题相关代码,请勿粘贴截图

insertInfo方法

@Override
    public void insertInfo(String word, String mean) {
        myDb = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("word",word);
        values.put("mean",mean);
        long rowid = myDb.insert(MyDbHelper.TB_NAME,null,values);
        if (rowid == -1){
            Log.i("myDbDemo", "数据插入失败 ");
        }else {
            Log.i("myDbDemo", "数据插入成功 ");
        }
    }

MyDBhelper

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import androidx.annotation.Nullable;

    public class MyDbHelper extends SQLiteOpenHelper {
        public static final String TB_NAME="words";
    public MyDbHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE IF NOT EXISTS "+TB_NAME+"(_id integer primary key autoincrement,"+"word varchar,"+"mean varchar"+")");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int i, int i1) {
        db.execSQL("DROP TABLE IF EXISTS "+ TB_NAME);
        onCreate(db);

    }
}


运行结果及报错内容

报错信息
java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
at com.example.word.EnteringActivity.onClick(EnteringActivity.java:86)
at android.view.View.performClick(View.java:7448)
at android.view.View.performClickInternal(View.java:7425)
at android.view.View.access$3600(View.java:810)
at android.view.View$PerformClick.run(View.java:28305)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)

我的解答思路和尝试过的方法

造成问题的原因似乎是这两句代码原因
String p1 = et_word.getText().toString();
String p2 = et_translate.getText().toString();

我想要达到的结果

望帮助解答一下,感谢

  • 写回答

1条回答 默认 最新

  • pumpkin的玄学 2021-11-20 22:19
    关注

    et_word 和 et_translate 都没有用findViewById找控件然后赋值啊 不空指针才怪呢。。。。。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 11月28日
  • 已采纳回答 11月20日
  • 创建了问题 11月20日

悬赏问题

  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序