当我尝试打开使用SQLite

时间:2016-06-15 06:19:09

标签: android sqlite android-fragments android-viewpager

所以基本上我是一个真正的业余爱好者,对编程非常感兴趣。我精通核心Java甚至Swing。现在我开始为我和我的编程爱好者伙伴正在开发的一个更大的项目开发一个模块,我需要一些帮助。 我正在开发一个非常简单的联系人管理器活动,它使用ViewPager显示三个屏幕,即只有两个标签的介绍屏幕,添加联系人屏幕和列表联系人屏幕。现在打开分页器FragmentActivity的一切都很顺利,但是一旦我将寻呼机设置为打开添加联系人片段,应用程序就会崩溃。我使用简单的SQLite方式,现在使用来自logcat的错误消息附加Fragment类,数据库适配器类和数据库帮助程序类。请帮忙。

ContactEdit.class

package com.example.nikhil.test1;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;

public class ContactEdit extends Fragment {
    ContactsAdapter databaseAdapter = new ContactsAdapter(this.getActivity());
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        ViewGroup rootView = (ViewGroup) inflater.inflate(
                R.layout.fragment_contact_edit, container, false);
databaseAdapter.open();

        Button SaveBTN = (Button) getActivity().findViewById(R.id.BtnSave);
        SaveBTN.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                EditText _Name = (EditText) getView().findViewById(R.id.textName);
                EditText _Mobile = (EditText) getView().findViewById(R.id.textMobile);
                EditText _Home = (EditText) getView().findViewById(R.id.textHome);
                EditText _Address = (EditText) getView().findViewById(R.id.textAddress);

                String name = _Name.getText().toString();
                String mobile = _Mobile.getText().toString();
                String home = _Home.getText().toString();
                String address = _Address.getText().toString();

             databaseAdapter.addFriend(name, address, mobile, home);

            }
        });
databaseAdapter.close();
        return rootView;

    }

}

ContactsAdapter.class

package com.example.nikhil.test1;
import android.content.ContentValues;
import android.content.Context;
import android.database.*;
import android.database.sqlite.*;
public class ContactsAdapter {
    private static final String DATABASE_NAME ="myDatabase.db";
    private static final String DATABASE_TABLE ="mainTable";
    private static final int DATABASE_VERSION = 1;


     private SQLiteDatabase db;

    private final Context context;

    private MyDatabaseHelper dbHelper;
    public ContactsAdapter(Context _context){
        context = _context;
        dbHelper = new MyDatabaseHelper(context, DATABASE_NAME, null,DATABASE_VERSION);
    }
    public ContactsAdapter open() throws SQLException {
        try {
            db = dbHelper.getWritableDatabase();
        }
        catch(SQLException ex){
            db=dbHelper.getReadableDatabase();
        }
        return this;
    }
    public void close() {
        db.close();
    }
    public void addFriend(String name, String address, String mobile, String home)

    {

        ContentValues values=new ContentValues(4);

        values.put("name", name);
        values.put("address", address);
        values.put("mobile", mobile);
        values.put("home", home);

        db.insert(DATABASE_TABLE, null, values);

    }
    public Cursor getFriend(int id)
    {
        Cursor res = db.rawQuery( "SELECT * FROM " + DATABASE_TABLE + " WHERE _id=", new String[] { Integer.toString(id) } );
        return res;
    }
    public Cursor getAllFriends() {
        Cursor res = db.rawQuery( "SELECT * FROM friends", null );
        return res;
    }
}

MyDatabaseHelper.class

package com.example.nikhil.test1;

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


public class MyDatabaseHelper extends SQLiteOpenHelper {
    private static final String DATABASE_TABLE ="mainTable";
    public static final String KEY_ID="_id";
    public static final String KEY_NAME="name";
    public static final int NAME_COLUMN = 1;


    public static final String KEY_Phone="phone";
    public static final int Phone_COLUMN = 2;


    public static final String KEY_Home="home";
    public static final int Home_COLUMN = 3;


    public static final String KEY_Address="address";
    public static final int Address_COLUMN = 4;

    private static final String DATABASE_CREATE = "create table " +
            DATABASE_TABLE + " (" + KEY_ID +" integer primary key autoincrement, " +KEY_NAME + " text not null,"+KEY_Phone+" text not null,"+KEY_Home+" text,"+KEY_Address+" text);";

    private SQLiteDatabase db;
    public MyDatabaseHelper(Context context, String name,
                            SQLiteDatabase.CursorFactory factory, int version) {

        super(context, name, factory, version);

    }



    @Override
    public void onCreate(SQLiteDatabase database) {

        database.execSQL(DATABASE_CREATE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS "+DATABASE_TABLE+";");

        onCreate(db);
    }



}

这是logcat错误日志:

06-14 22:31:59.660  30738-30738/com.example.nikhil.test1 E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.example.nikhil.test1, PID: 30738
    java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.sqlite.SQLiteDatabase android.content.Context.openOrCreateDatabase(java.lang.String, int, android.database.sqlite.SQLiteDatabase$CursorFactory, android.database.DatabaseErrorHandler)' on a null object reference
            at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:223)
            at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:163)
            at com.example.nikhil.test1.ContactsAdapter.open(ContactsAdapter.java:24)
            at com.example.nikhil.test1.ContactEdit.onCreateView(ContactEdit.java:21)
            at android.support.v4.app.Fragment.performCreateView(Fragment.java:1789)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:955)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1138)
            at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:740)
            at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1501)
            at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:490)
            at android.support.v4.app.FragmentStatePagerAdapter.finishUpdate(FragmentStatePagerAdapter.java:163)
            at android.support.v4.view.ViewPager.populate(ViewPager.java:1072)
            at android.support.v4.view.ViewPager.populate(ViewPager.java:918)
            at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1440)
            at android.view.View.measure(View.java:17565)
            at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:728)
            at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:464)
            at android.view.View.measure(View.java:17565)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5545)
            at android.widget.FrameLayout.onMeasure(FrameLayout.java:436)
            at android.view.View.measure(View.java:17565)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5545)
            at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1436)
            at android.widget.LinearLayout.measureVertical(LinearLayout.java:722)
            at android.widget.LinearLayout.onMeasure(LinearLayout.java:613)
            at android.view.View.measure(View.java:17565)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5545)
            at android.widget.FrameLayout.onMeasure(FrameLayout.java:436)
            at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2652)
            at android.view.View.measure(View.java:17565)
            at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2027)
            at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1185)
            at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1391)
            at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1073)
            at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5903)
            at android.view.Choreographer$CallbackRecord.run(Choreographer.java:828)
            at android.view.Choreographer.doCallbacks(Choreographer.java:588)
            at android.view.Choreographer.doFrame(Choreographer.java:558)
            at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:814)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5268)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:902)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:697)

我意识到这可能是一件非常愚蠢和明显的事情,但请耐心等待并帮助一位朋友。和平了!

2 个答案:

答案 0 :(得分:1)

问题在于这一行:

ContactsAdapter databaseAdapter = new ContactsAdapter(this.getActivity());

这在构造时运行,此时你的Fragment没有附加到任何Activity,getActivity()返回null。您需要在其中一个生命周期回调方法中实例化databaseAdapter,例如onActivityCreated()

此外,最好让您的SQLiteOpenHelper实施为使用单SQLiteDatabase进行所有操作的单身人士。

答案 1 :(得分:1)

像这样写:

public class ContactEdit extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    ViewGroup rootView = (ViewGroup) inflater.inflate(
            R.layout.fragment_contact_edit, container, false);
    ContactsAdapter databaseAdapter = new ContactsAdapter(this.getActivity());
    databaseAdapter.open();

    // Rest of your code..!!
}

ContactsAdapter内初始化onCreateView()将有助于通过getActivity()

获取活动
  

编辑1:

而不是:

 Button SaveBTN = (Button) getActivity().findViewById(R.id.BtnSave);

写下这个:

 Button SaveBTN = (Button) rootView.findViewById(R.id.BtnSave);