从onClickListener调用new方法时返回Null

时间:2016-09-25 12:45:23

标签: java android sqlite

我已经搜索了相当的abit,我认为这个问题与上下文有关,但我仍在努力(编程新手)。问题如下:

我有一个方法可以将我的sqlite数据库同步到一个外部数据库,当下面的方法出现在带有按钮的类中时可以正常工作,但是我需要在它自己的类中使用这个方法,如下面所示的SyncToMYSQL。

public class SyncToMYSQL {

DowncroftDatabase downcroftDatabase;
ProgressDialog prgDialog;

public void syncSQLiteMySQLDB() {
    //Create AsycHttpClient object
    AsyncHttpClient client = new AsyncHttpClient();
    RequestParams params = new RequestParams();
    ArrayList<HashMap<String, String>> userList = downcroftDatabase.getAllUsers();
    if (userList.size() != 0) {
        if (downcroftDatabase.dbSyncCount() != 0) {
            prgDialog.show();
            params.put("usersJSON", downcroftDatabase.composeJSONfromSQLite());
            client.post("http://jakebreen.co.uk/android/sqlitemysqlsync/inseruser.php", params, new AsyncHttpResponseHandler() {
                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] response) {
                    System.out.println(response);
                    prgDialog.hide();
                    try {
                        JSONArray arr = new JSONArray(new String(response)); //new JSONArray(new String(response));
                        System.out.println(arr.length());
                        for (int i = 0; i < arr.length(); i++) {
                            JSONObject obj = (JSONObject) arr.get(i);
                            System.out.println(obj.get("id"));
                            System.out.println(obj.get("status"));
                            downcroftDatabase.updateSyncStatus(obj.get("id").toString(), obj.get("status").toString());
                        }
                        //Toast.makeText(getApplicationContext(), "DB Sync completed!", Toast.LENGTH_LONG).show();
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        //Toast.makeText(getBaseContext(), "DB Sync completed!", Toast.LENGTH_LONG).show(); //Toast.makeText(getApplicationContext(), "Error Occured [Server's JSON response might be invalid]!", Toast.LENGTH_LONG).show();
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

                    // TODO Auto-generated method stub
                    prgDialog.hide();
                    if (statusCode == 404) {
                        //Toast.makeText(getApplicationContext(), "Requested resource not found", Toast.LENGTH_LONG).show();
                    } else if (statusCode == 500) {
                        //Toast.makeText(getApplicationContext(), "Something went wrong at server end", Toast.LENGTH_LONG).show();
                    } else {
                        //Toast.makeText(getApplicationContext(), "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet]", Toast.LENGTH_LONG).show();
                    }
                }
            });
        } else {
            //Toast.makeText(getApplicationContext(), "SQLite and Remote MySQL DBs are in Sync!", Toast.LENGTH_LONG).show();
        }
    } else {
        //Toast.makeText(getApplicationContext(), "No data in SQLite DB, please do enter User name to perform Sync action", Toast.LENGTH_LONG).show();
    }
}
}

从我创建的另一个活动中调用它的按钮:

public void SyncButton() {
    btn_syncTo.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            syncToMYSQL.syncSQLiteMySQLDB();
        }
    });
}

这会返回错误

E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.year2.dck, PID: 2492
              java.lang.NullPointerException: Attempt to invoke virtual method 'void com.year2.dck.SyncToMYSQL.syncSQLiteMySQLDB()' on a null object reference
                  at com.year2.dck.LoginActivity$5.onClick(LoginActivity.java:157)
                  at android.view.View.performClick(View.java:5198)
                  at android.view.View$PerformClick.run(View.java:21147)
                  at android.os.Handler.handleCallback(Handler.java:739)
                  at android.os.Handler.dispatchMessage(Handler.java:95)
                  at android.os.Looper.loop(Looper.java:148)
                  at android.app.ActivityThread.main(ActivityThread.java:5417)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

2 个答案:

答案 0 :(得分:0)

尝试将syncToMYSQL定义为private final SyncToMYSQL syncToMYSQL;

答案 1 :(得分:0)

将此方法syncSQLiteMySQLDB更改为静态方法并尝试,

SyncToMYSQL.syncSQLiteMySQLDB();