开始使用SQLite和Android;启动程序时出错

时间:2014-05-27 15:38:09

标签: java android sql sqlite

最近,我一直在尝试将SQL与Android结合使用。但是,我的代码出错了。

程序很简单;它应该采用名称和电子邮件地址,按下按钮时保存,然后在按下加载按钮时加载数据。

到目前为止,我已经能够缩小范围,即setOnClickListener区域,并且在两种情况下最有可能出现问题。但我不知道为什么他们总是会返回错误。我已经编写了setOnClickListener正在运行的程序,所以我假设实际错误在我已经放入的两个案例中。

这里是代码:一个MainActivity.java,一个类和一个XML文件。 MainActivity.java:

package com.example.sqlpractice;

import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
import android.database.Cursor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity implements OnClickListener{

    Button bSave, bLoad;
    EditText etName, etEmail;
    DataHandler handler;

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

        bSave = (Button) findViewById(R.id.bSave);
        bLoad = (Button) findViewById(R.id.bLoad);
        etName = (EditText) findViewById(R.id.etName);
        etEmail = (EditText) findViewById(R.id.etEmail);

        bSave.setOnClickListener(this);
        bLoad.setOnClickListener(this);

        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                .add(R.id.container, new PlaceholderFragment()).commit();
        }
    }

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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container,
                    false);
            return rootView;
        }
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch(v.getId()){
            case R.id.bSave:
                String getName = etName.getText().toString();
                String getEmail = etEmail.getText().toString();
                handler = new DataHandler(getBaseContext());
                handler.open();
                long id = handler.insertData(getName, getEmail);
                Toast.makeText(getBaseContext(), "Data inserted", Toast.LENGTH_LONG).show();
                handler.close();
                break;

            case R.id.bLoad:
                String getName1 = "";
                String getEmail1 = "";

                handler = new DataHandler(getBaseContext());
                handler.open();
                Cursor crsLoad = handler.returnData();
                if(crsLoad.moveToFirst()) {
                    do {
                        getName1 = crsLoad.getString(0);
                        getEmail1 = crsLoad.getString(1);
                    } while(crsLoad.moveToNext());
                }
                handler.close();
                Toast.makeText(getBaseContext(), "Data loaded. Name: "+getName1 +" Email: "+getEmail1, Toast.LENGTH_LONG).show();
                break;
        }
    }
}

我收到的错误:

05-27 11:08:12.503: E/AndroidRuntime(908): FATAL EXCEPTION: main
05-27 11:08:12.503: E/AndroidRuntime(908): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.sqlpractice/com.example.sqlpractice.MainActivity}: java.lang.NullPointerException
05-27 11:08:12.503: E/AndroidRuntime(908):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
05-27 11:08:12.503: E/AndroidRuntime(908):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
05-27 11:08:12.503: E/AndroidRuntime(908):  at android.app.ActivityThread.access$600(ActivityThread.java:141)
05-27 11:08:12.503: E/AndroidRuntime(908):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
05-27 11:08:12.503: E/AndroidRuntime(908):  at android.os.Handler.dispatchMessage(Handler.java:99)
05-27 11:08:12.503: E/AndroidRuntime(908):  at android.os.Looper.loop(Looper.java:137)
05-27 11:08:12.503: E/AndroidRuntime(908):  at android.app.ActivityThread.main(ActivityThread.java:5103)
05-27 11:08:12.503: E/AndroidRuntime(908):  at java.lang.reflect.Method.invokeNative(Native Method)
05-27 11:08:12.503: E/AndroidRuntime(908):  at java.lang.reflect.Method.invoke(Method.java:525)
05-27 11:08:12.503: E/AndroidRuntime(908):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
05-27 11:08:12.503: E/AndroidRuntime(908):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
05-27 11:08:12.503: E/AndroidRuntime(908):  at dalvik.system.NativeStart.main(Native Method)
05-27 11:08:12.503: E/AndroidRuntime(908): Caused by: java.lang.NullPointerException
05-27 11:08:12.503: E/AndroidRuntime(908):  at com.example.sqlpractice.MainActivity.onCreate(MainActivity.java:34)
05-27 11:08:12.503: E/AndroidRuntime(908):  at android.app.Activity.performCreate(Activity.java:5133)
05-27 11:08:12.503: E/AndroidRuntime(908):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
05-27 11:08:12.503: E/AndroidRuntime(908):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
05-27 11:08:12.503: E/AndroidRuntime(908):  ... 11 more

DataHandler.java:

package com.example.sqlpractice;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DataHandler {
public static final String NAME = "name";
public static final String EMAIL = "email";
public static final String TABLE_NAME = "myTable";
public static final String DATABASE_NAME = "myDatabase";
public static final int DATABASE_VERSION = 1;
public static final String TABLE_CREATE = "create table myTable (name text not     null, email text not null)";

DatabaseHelper dbHelper;
Context ctx;
SQLiteDatabase db;

public DataHandler(Context ctx) {
    this.ctx = ctx;
    dbHelper = new DatabaseHelper(ctx);
}

private static class DatabaseHelper extends SQLiteOpenHelper {

    public DatabaseHelper(Context ctx) {
        super(ctx, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        try {
            db.execSQL(TABLE_CREATE);
            } catch(SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub

        db.execSQL("DROP TABLE IF EXISTS myTable");
        onCreate(db);
    }

}
public DataHandler open() {
    db = dbHelper.getWritableDatabase();
    return this;
}

public void close() {
    dbHelper.close();
}

public long insertData(String name, String email) {
    ContentValues content = new ContentValues();
    content.put(NAME, name);
    content.put(EMAIL, email);
    return db.insertOrThrow(TABLE_NAME, null, content);
}

public Cursor returnData() {

return db.query(TABLE_NAME, new String[] {NAME, EMAIL}, null, null, null, null, null);

}

}

fragment_main.xml:

    <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="com.example.sqlpractice.MainActivity$PlaceholderFragment" >

        <EditText
        android:id="@+id/etEmail"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/bSave"
        android:layout_centerHorizontal="true"
        android:ems="10"
        android:hint="Enter e-mail here." >

        <requestFocus />
    </EditText>

    <EditText
        android:id="@+id/etName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/etEmail"
        android:layout_alignLeft="@+id/etEmail"
        android:ems="10"
        android:hint="Enter name here." />

    <Button
        android:id="@+id/bLoad"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="16dp"
        android:text="Load Data" />

    <Button
        android:id="@+id/bSave"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/bLoad"
        android:layout_alignLeft="@+id/bLoad"
        android:text="Save Data" />



</RelativeLayout>

感谢您的帮助。

0 个答案:

没有答案