NullPointerException从实用程序类访问会议室数据库(非活动)

时间:2019-02-01 13:12:08

标签: java android android-activity nullpointerexception android-room

我一直在尝试为我的Android应用程序创建一个实用程序类,因此,不是每个Activity都调用Room数据库,而是所有操作都将在一个“ Utility”类中执行,并在需要的任何时间和地点向每个活动请求。

我试图以与SettingsActivity(在onCreate中)以及负责所需操作的相应类中相同的方式建立与数据库的连接-没有任何运气。

首先,该代码用于从Activity类中检索Room数据库中保存的票价数量。

SettingsActivity.java

public void deletingFares(View view) {

// start of attempt of getting the value from QueriesUtility class

    QueriesUtility qu = new QueriesUtility();
    String quString = qu.returnNumberOfFares();

    Toast.makeText(SettingsActivity.this, 
    "Data from Queries Utilities class: (number of fares):" 
                    + quString, Toast.LENGTH_LONG).show();
// end

QueriesUtility.java类的代码:

public class QueriesUtility extends AppCompatActivity {

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

    // FARES DB
    // establishing connection with db
    mFareDAO = Room.databaseBuilder(getApplicationContext(), AppDatabase.class, "db-fares")
            .build()
            .getFareDAO();
}

public String returnNumberOfFares() {

    CalcNumberOfFares ss = new CalcNumberOfFares();
    ss.execute("");

    return numberOfFares;
}

String numberOfFares = "d0";
private FareDAO mFareDAO;
/**
 * CALCULATING NUMBER OF FARES
 */
private class CalcNumberOfFares extends AsyncTask<String, Integer, String> {

    // #1 - This is run in a background thread
    @Override
    protected String doInBackground(String... params) {
        // get the string from params, which is an array
        String myString = params[0];

        // FARES DB
        // establishing connection with db
        mFareDAO = Room.databaseBuilder(getApplicationContext(), AppDatabase.class, "db-fares")
                .build()
                .getFareDAO();

        List<Fare> fares = mFareDAO.getAllFares();

        myString = String.valueOf(fares.size());
        numberOfFares = myString;

        return myString;
    }


    // #2 - This runs in UI when background thread finishes
    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        numberOfFares = result;

// todo


    }
}

/**
 *
 * END
 */
}

您可以说-我试图以一种绝望的方式用两种方式建立与数据库的连接;)(在onCreate以及CalcNumberOfFares中)。 是否将“ onCreate”忽略了-因为类是非活动类?

以下是带有错误的日志:

E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #4
              Process: com.example.android.taxidriverassistant, PID: 26280
              java.lang.RuntimeException: An error occurred while executing doInBackground()
                  at android.os.AsyncTask$3.done(AsyncTask.java:353)
                  at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:383)
                  at java.util.concurrent.FutureTask.setException(FutureTask.java:252)
                  at java.util.concurrent.FutureTask.run(FutureTask.java:271)
                  at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245)
                  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
                  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
                  at java.lang.Thread.run(Thread.java:764)
               Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
                  at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:119)
                  at com.example.android.taxidriverassistant.QueriesUtility$CalcNumberOfFares.doInBackground(QueriesUtility.java:57)
                  at com.example.android.taxidriverassistant.QueriesUtility$CalcNumberOfFares.doInBackground(QueriesUtility.java:47)
                  at android.os.AsyncTask$2.call(AsyncTask.java:333)
                  at java.util.concurrent.FutureTask.run(FutureTask.java:266)
                  at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245) 
                  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162) 
                  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636) 
                  at java.lang.Thread.run(Thread.java:764) 
I/Process: Sending signal. PID: 26280 SIG: 9
Application terminated. 

在“活动”的类中执行对Room DB的调用时,一切都会正常进行。

这是在SettingsActivity.java中与Room数据库建立连接的方式:

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

    // FARES DB
    // establishing connection with db
    mFareDAO = Room.databaseBuilder(this, AppDatabase.class, "db-fares")
            .build()
            .getFareDAO();

以及DeletingFares的代码(可在SettingsActivity.java类中使用):

    /**
 * DELETING FARES CLASS
 */
private class DeletingFares extends AsyncTask<String, Integer, String> {

    // #1 - This is run in a background thread
    @Override
    protected String doInBackground(String... params) {
        // get the string from params, which is an array
        String myString = params[0];

        List<Fare> fares = mFareDAO.getAllFares();

        myString = String.valueOf(fares.size());
        numberOfFares = myString;
        // value of myString is send over to onPostExecute and used in the end to make an Alert

        // if there are no fares - no further action should take place
        if (fares.size() > 0) {
            for (int i = 0; i < fares.size(); i++) {
                Fare ff = fares.get(i);
                mFareDAO.delete(ff);
            }
        }
        return myString;
    }


    // #2 - This runs in UI when background thread finishes
    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        // invoking method which displays the alert at the end
        alertAfterDeletingFares();


    }
}

据我所了解,NullPointerException的概念是-对QueriesUtility类中对象的引用(但从SettingsActivity类请求)不存在,因为它与数据库没有连接,因此要引用该对象并返回null(是正确吗?)。

如果有人能指出我正确的方向,我将不胜感激。非常感谢!

1 个答案:

答案 0 :(得分:0)

您需要传递contextAsyncTask,而不是使用getApplicationContext()

引用getApplicationContext in AsyncTask class?