从另一个班级打电话给排球

时间:2015-08-19 08:47:17

标签: java android object

我有一个Activity类,运行了很多Web服务,并希望使我的程序更“面向对象”,因此它可以维护且易于阅读。例如,请查看以下示例。

public class Welcome extends ActionBarActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    getSupportActionBar().hide();
    setContentView(R.layout.activity_sample);





    buildFitnessClient();

    showUser(username,password);

}

private void buildFitnessClient() {
    // Create the Google API Client
    mClient = new GoogleApiClient.Builder(this)
            .addApi(Fitness.SENSORS_API)
            .addApi(Fitness.HISTORY_API)
            .addScope(new Scope(Scopes.FITNESS_ACTIVITY_READ_WRITE))

            .addConnectionCallbacks(
                    new GoogleApiClient.ConnectionCallbacks() {
                        @Override
                        public void onConnected(Bundle bundle) {
                            Log.i(TAG, "Connected!!!");
                            // Now you can make calls to the Fitness APIs.  What to do?
                            // Look at some data!!

                            //showUser(username,password);

                            new InsertAndVerifyDataTask().execute();


                        }

                        @Override
                        public void onConnectionSuspended(int i) {
                            // If your connection to the sensor gets lost at some point,
                            // you'll be able to determine the reason and react to it here.
                            if (i == GoogleApiClient.ConnectionCallbacks.CAUSE_NETWORK_LOST) {
                                Log.i(TAG, "Connection lost.  Cause: Network Lost.");
                            } else if (i == GoogleApiClient.ConnectionCallbacks.CAUSE_SERVICE_DISCONNECTED) {
                                Log.i(TAG, "Connection lost.  Reason: Service Disconnected");
                            }
                        }
                    }
            )
            .addOnConnectionFailedListener(
                    new GoogleApiClient.OnConnectionFailedListener() {
                        // Called whenever the API client fails to connect.
                        @Override
                        public void onConnectionFailed(ConnectionResult result) {
                            Log.i(TAG, "Connection failed. Cause: " + result.toString());
                            if (!result.hasResolution()) {
                                // Show the localized error dialog
                                GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(),
                                        Welcome.this, 0).show();
                                return;
                            }
                            // The failure has a resolution. Resolve it.
                            // Called typically when the app is not yet authorized, and an
                            // authorization dialog is displayed to the user.
                            if (!authInProgress) {
                                try {
                                    Log.i(TAG, "Attempting to resolve failed connection");
                                    authInProgress = true;
                                    result.startResolutionForResult(Welcome.this,
                                            REQUEST_OAUTH);
                                } catch (IntentSender.SendIntentException e) {
                                    Log.e(TAG,
                                            "Exception while starting resolution activity", e);
                                }
                            }
                        }
                    }
            )
            .build();
}

@Override
protected void onStart() {
    super.onStart();
    // Connect to the Fitness API
    Log.i(TAG, "Connecting...");

    mClient.connect();

}

@Override
protected void onStop() {
    super.onStop();
    if (mClient.isConnected()) {
        mClient.disconnect();
        //showUser(username,password);


    }

}



@Override
protected void onDestroy() {
    super.onDestroy();
    //showUser(username,password);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_OAUTH) {
        authInProgress = false;
        if (resultCode == RESULT_OK) {
            // Make sure the app is not already connected or attempting to connect
            if (!mClient.isConnecting() && !mClient.isConnected()) {
                mClient.connect();
            }
        }
    }
}
 private void showUser(final String username, final String password) {
    HttpsTrustManager.allowAllSSL();
    String tag_json_obj = "json_obj_req";

    location = getResources().getConfiguration().locale.getCountry();
    final HashMap<String, String> postParams = new HashMap<String, String>();

    postParams.put("username", username);

    postParams.put("password", password);

    Response.Listener<JSONObject>  listener;
    Response.ErrorListener errorListener;
    final JSONObject jsonObject = new JSONObject(postParams);

    //{"password":"larissa","username":"samsungtest"}
    //{"password":"larissa","username":"theo81developer@gmail.com"}
    JsonObjectRequest jsonObjReq = new JsonObjectRequest(AppConfig.URL_USER_CHECK, jsonObject,

            new com.android.volley.Response.Listener<JSONObject>() {

                @Override
                public void onResponse(JSONObject response) {
                   // {"message":"User Information found.","user":{"username":"samsungtest","league_points":null,"team_id":"189","location":"GB","latest_steps":"0","user_type":"LEADER","nickname":"samsungtest"},"status":"success"}
                   //{"message":"User Information found.","user":{"username":"theo81developer@gmail.com","league_points":null,"team_id":"228","location":"GB","latest_steps":"5033","user_type":"LEADER","nickname":"Samsung User"},"status":"success"}

                    Log.d("TAG", response.toString());
                    try {
                        if (response.getString("status").equals("success")){

                            userTable(response);

                            localRanking(username,password,location);
                            globalRanking(username,password);
                        }

                    } catch (JSONException e) {
                        Log.e("TAG", e.toString());
                    }

                }
            }, new com.android.volley.Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            //VolleyLog.d("TAG", "Error: " + error.getMessage());

        }
    }) {

        @Override
        public String getBodyContentType() {
            return "application/json; charset=utf-8";
        }
    };
    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);

}

如果我从另一个类调用buildFitnessClient()和showUser(...),我怎样才能使它工作?我尝试了一些不同的方法,比如在内部使用buildFitnessClient()方法实现一个名为Fitness的类,但是我在View对象上获得了空指针异常。

1 个答案:

答案 0 :(得分:0)

您可以将方法实现为静态,以便可以从另一个类或活动中调用它们,并简单地传递它可能需要的所需参数(例如上下文,视图等)。只需将它们用作 Fitness.buildFitnessClient(&lt; variables&gt;)

之类的东西

OR

实施 singleton ,您可以在其中设置方法使用的变量,并执行您想要执行的操作。然而,这要复杂得多(至少对我而言

** 请注意内存泄漏 **

相关问题