简体   繁体   English

如何在片段中获取应用程序的上下文

[英]How to get the Context of an Application in a Fragment

First I have this error message 首先,我有此错误信息

Caused by: 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 net.purplebug.mydoctorfinder.MyDBHandler.showDoctors(MyDBHandler.java:133)
                                                                              at net.purplebug.mydoctorfinder.HomeFragment.showDoctorList(HomeFragment.java:131)

So I thought it could be the way I wrote the Context as parameter for the dbhandler instance. 因此,我认为这可能是我将Context作为dbhandler实例的参数编写的方式。

This is the code which triggers the error. 这是触发错误的代码。 It's a method in a class that extends Fragment. 这是扩展Fragment的类中的方法。

public void showDoctorList() {
    String result = "Match Found";

    MyDBHandler dbHandler = new MyDBHandler(getContext(), null, null, 1);

    ArrayList<ArrayList<String>> docArray = new ArrayList<ArrayList<String>>();

    DoctorDataModel doctor = null;
    try {
        doctor = dbHandler.showDoctors();
    } catch (SQLException e) {
        e.printStackTrace();
    }

    if (doctor != null) {

        TableRow row = new TableRow(getActivity());
        row.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));

        docArray = doctor.getDocArray();

        for(int i = 0; i < docArray.size(); i++) {
            for(int j = 0; j < docArray.get(i).size(); j++) {
                TextView textView = new TextView(getActivity());
                textView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
                textView.setPadding(5, 5, 5, 5);
                textView.setText(docArray.get(i).get(j) + " ");

                row.addView(textView);
            }
            tableLayout.addView(row);
        }

    } else {
        result = "No Match Found";
    }

    Log.d("QUERY RESULT", result);

}

And finally the code in the DBHandler in relation to the error. 最后是与错误有关的DBHandler中的代码。

public MyDBHandler(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
    super(context, DATABASE_NAME, factory, DATABASE_VERSION);
    this.myContext = context;
}

public DoctorDataModel showDoctors() throws SQLException {

    int index = 0;
    String docLastName, docFirstName, docId;

    String query = "Select doctor_id, lastName, firstName FROM " + TABLE_DOCTOR;

    SQLiteDatabase db = this.getWritableDatabase();

    Cursor cursor = db.rawQuery(query, null);

    DoctorDataModel doctor = new DoctorDataModel();

    while (cursor.moveToNext()) {
        docId = cursor.getString(0);
        docLastName = cursor.getString(1);
        docFirstName = cursor.getString(2);
        doctor.setdocArrayList(index, docId, docLastName, docFirstName);
        index++;
    }
    index = 0;
    cursor.close();
    db.close();
    return doctor;
}

I really think it's with the way I get the Context in this code. 我真的认为这与我在此代码中获取Context的方式有关。

MyDBHandler dbHandler = new MyDBHandler(getContext(), null, null, 1); MyDBHandler dbHandler = new MyDBHandler(getContext(),null,null,1);

Or it could be something else which is the problem. 否则可能是其他问题。 So what do you guys think? 那么你们怎么看?

If you want to get application context in fragments then you can use getActivity().getApplicationContext() 如果要分段获取应用程序上下文,则可以使用getActivity().getApplicationContext()

Note:- Please consider the lifecycle of fragment and make sure the fragment is attached to activity. 注意:-请考虑片段的生命周期,并确保片段已附加到活动中。

You just have to do: 您只需要做:

`Context context;`
context = getActivity();

and you can use it anywhere in the fragment. 您可以在片段中的任何位置使用它。

you can define a global variable: 您可以定义一个全局变量:

private Context context;

and in the onCreate method, initialize it : 然后在onCreate方法中将其初始化:

context = this.getActivity();

Later use it as following to avoid NullPointerException : 以后按如下所示使用它来避免NullPointerException

if(context!=null){
//your code
}

And by that you can use the context variable in all your fragment functions/methods. 这样,您就可以在所有片段函数/方法中使用context变量。

In fragment you can get context by :: getActivity() 在片段中,您可以通过:: getActivity()获取上下文。

Before use it just check, Is fragment attached to activity or not ? 在使用前,只需检查,碎片是否附着在活动上?

Context context = getActivity();

 if(context != null){
     //write your code here...
   }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM