1

我正在做一个小项目,我需要将电话号码及其各自的地址存储到sqliteAndroid 的数据库中。MyMainActivity有一个布局,其中用户有两个选项: 1. 他可以向数据库添加新值(电话号码和地址) 2. 他可以通过输入电话号码来搜索地址。

这是我的主要活动:

public class MainActivity extends Activity {


    private static final String TABLE_CONTACTS = "contacts";
    private static final int DATABASE_VERSION = 1;

    // Database Name
    private static final String DATABASE_NAME = "contactsManager";
    // Contacts Table Columns names
    private static final String KEY_ID = "id";
    private static final String KEY_ADDRESS = "name";
    private static final String KEY_PH_NO = "phone_number";

    SQLiteDatabase db;

    TextView numberTextview,addressTextView,fetchedAddressTextView;
    Button buttonSave,buttonSearch;
    EditText numberEditText,addressEditText,searchEditText;




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

        numberTextview=(TextView)findViewById(R.id.textView1);
        numberEditText=(EditText)findViewById(R.id.editText1);
        addressTextView=(TextView)findViewById(R.id.textView2);
        addressEditText=(EditText)findViewById(R.id.editText2);
        buttonSave=(Button)findViewById(R.id.button1);
        searchEditText=(EditText)findViewById(R.id.editText3);
        buttonSearch=(Button)findViewById(R.id.button2);
        fetchedAddressTextView=(TextView)findViewById(R.id.textView3);

        try {
            String CREATE_CONTACTS_TABLE = "CREATE TABLE IF NOT EXISTS " + TABLE_CONTACTS + "("
                    + KEY_ID + " INTEGER PRIMARY KEY," + KEY_ADDRESS + " TEXT,"
                    + KEY_PH_NO + " TEXT" + ")";
            db.execSQL(CREATE_CONTACTS_TABLE);
            Toast.makeText(MainActivity.this, "table created ", Toast.LENGTH_LONG).show();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        buttonSave.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                String address=addressEditText.getText().toString();
                long number = Integer.parseInt(numberEditText.getText().toString());

                try {
                    ContentValues values = new ContentValues();
                    values.put(KEY_ADDRESS, address); // Contact Address
                    values.put(KEY_PH_NO, number); // Contact Phone

                    // Inserting Row
                    db.insert(TABLE_CONTACTS, null, values);
                    db.close();
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }


            }
        });

        buttonSearch.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                long phone_number=Integer.parseInt(searchEditText.getText().toString());

                try {
                    Cursor c=db.query(TABLE_CONTACTS, new String[]{
                            KEY_ADDRESS
                    },
                    KEY_PH_NO + "=" + phone_number,
                    null,
                    null,
                    null,
                    null);

                    if (c != null) {
                        c.moveToFirst();
                    }
                    fetchedAddressTextView.setText(c.toString());
                } catch (Exception e) {

                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }




        });
    }


    @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;
    }

}

Logcat 跟踪:

03-28 11:45:12.562: E/AndroidRuntime(4079): FATAL EXCEPTION: main
03-28 11:45:12.562: E/AndroidRuntime(4079): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.fivetofive/com.example.fivetofive.MainActivity}: java.lang.NullPointerException
03-28 11:45:12.562: E/AndroidRuntime(4079):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2097)
03-28 11:45:12.562: E/AndroidRuntime(4079):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2122)
03-28 11:45:12.562: E/AndroidRuntime(4079):     at android.app.ActivityThread.access$600(ActivityThread.java:140)
03-28 11:45:12.562: E/AndroidRuntime(4079):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1228)
03-28 11:45:12.562: E/AndroidRuntime(4079):     at android.os.Handler.dispatchMessage(Handler.java:99)
03-28 11:45:12.562: E/AndroidRuntime(4079):     at android.os.Looper.loop(Looper.java:137)
03-28 11:45:12.562: E/AndroidRuntime(4079):     at android.app.ActivityThread.main(ActivityThread.java:4895)
03-28 11:45:12.562: E/AndroidRuntime(4079):     at java.lang.reflect.Method.invokeNative(Native Method)
03-28 11:45:12.562: E/AndroidRuntime(4079):     at java.lang.reflect.Method.invoke(Method.java:511)
03-28 11:45:12.562: E/AndroidRuntime(4079):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:994)
03-28 11:45:12.562: E/AndroidRuntime(4079):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:761)
03-28 11:45:12.562: E/AndroidRuntime(4079):     at dalvik.system.NativeStart.main(Native Method)
03-28 11:45:12.562: E/AndroidRuntime(4079): Caused by: java.lang.NullPointerException
03-28 11:45:12.562: E/AndroidRuntime(4079):     at com.example.fivetofive.MainActivity.onCreate(MainActivity.java:59)
03-28 11:45:12.562: E/AndroidRuntime(4079):     at android.app.Activity.performCreate(Activity.java:5163)
03-28 11:45:12.562: E/AndroidRuntime(4079):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
03-28 11:45:12.562: E/AndroidRuntime(4079):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2061)
03-28 11:45:12.562: E/AndroidRuntime(4079):     ... 11 more

该应用程序甚至没有启动。当我运行它时它崩溃了。这是我第一次sqlite在 android 中工作。所以请原谅任何愚蠢的错误并指出它们。

提前致谢。

更新 请注意:我现在已经解决了我的问题,方法是选择一个单独DataBaseHandler的扩展类SQLiteOpenHelper。我仍然不明白为什么我得到了我来到这里的错误。现在没有时间,所以如果我得到答案,稍后会回来。对于那些会遇到这个问题的人,我只想说制作DataBaseHandler课程有很大帮​​助。

4

3 回答 3

2

你必须extends SQLiteOpenHelper {

请用下面的行初始化你的数据库对象

db = new SQLiteDatabase(); 

你有没有在清单中添加这一行

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

请阅读本教程

http://www.androidhive.info/2011/11/android-sqlite-database-tutorial/

http://www.vogella.com/articles/AndroidSQLite/article.html

于 2013-03-28T06:34:28.743 回答
1

你应该在使用它之前打开你的数据库..只需在 try{} 上方放置 2 行,然后尝试让我知道发生了什么。

db = new SQLiteDatabase(); // pass context or activity its upon your SQLiteDatabase() class
db.open();

我想它可能会帮助你..

于 2013-03-28T06:31:35.903 回答
0

请检查您从中获得价值吗?

String address=addressEditText.getText().toString();
long number = Integer.parseInt(numberEditText.getText().toString());

如果是,则更改此行:

ContentValues values = new ContentValues();
                    values.put(KEY_ADDRESS, address); // Contact Address
                    values.put(KEY_PH_NO, number); // Contact Phone

对此

db.open();
ContentValues values = new ContentValues();
values.put(KEY_ADDRESS, ""+address); // Contact Address
values.put(KEY_PH_NO, ""+number); // Contact Phone

因为在查询KEY_PH_NO中是TEXT

String CREATE_CONTACTS_TABLE = "CREATE TABLE IF NOT EXISTS " + TABLE_CONTACTS + "("
                    + KEY_ID + " INTEGER PRIMARY KEY," + KEY_ADDRESS + " TEXT,"
                    + KEY_PH_NO + " TEXT" + ")";
于 2013-03-28T06:30:29.413 回答