使用Android Async Http处理成功请求返回

时间:2016-01-11 11:11:41

标签: java android android-asynctask android-async-http

我是Android新手,来自iOS我对Java及其所有功能知之甚少。我正在尝试构建一个用户需要在启动时登录的应用程序。我正在使用我使用的私有API: https://apiUrl.com/login?login=login&password=password 它返回一个JSon对象:

{
token: "qqdpo9i7qo3m8lldksin6cq714"
}

所以我在代码中所做的很简单:

MainActivity.java:

Button button = (Button) findViewById(R.id.loginButton);

        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                String login = (String) ((EditText) findViewById (R.id.userName)).getText().toString();
                String password = (String) ((EditText) findViewById (R.id.password)).getText().toString();

                if (login != "" && password != "")
                {
                    HashMap<String, String> postElements = new HashMap<String, String>();
                    postElements.put("login", login);
                    try {
                        postElements.put("password", URLEncoder.encode(password, "utf-8"));
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    Button button = (Button) findViewById(R.id.loginButton);
                    button.setText("Login in ...");

                    String queryLogin = "https://apiUrl.com/login?";

                    String urlString = "";
                    try {
                        urlString = "login=";
                        urlString += URLEncoder.encode(login, "UTF-8");
                        urlString += "&password=";
                        urlString += URLEncoder.encode(password, "UTF-8");
                    } catch (UnsupportedEncodingException e) {

                        // if this fails for some reason, let the user know why
                        e.printStackTrace();
                        Toast.makeText(getApplicationContext(), "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
                    }

                    apiQuery.loginQuery(queryLogin, urlString);
}

apiQuery的类型为APIQuery:

public void loginQuery(String url, String urlString) {

  // Prepare your search string to be put in a URL
  // It might have reserved characters or something
  // Create a client to perform networking
  AsyncHttpClient client = new AsyncHttpClient();

  // Have the client get a JSONArray of data
  // and define how to respond
  client.get(url + urlString,
        new JsonHttpResponseHandler() {
              @Override
              public void onSuccess(JSONObject jsonObject) {
                    String token = "";

                    if (jsonObject.has("token")) {
                    /*Toast.makeText(_mainContext, "Login Success!", Toast.LENGTH_LONG).show();*/
                    token = jsonObject.optString("token");
                    // 8. For now, just log results
                    Log.d("APIQuery Success", jsonObject.toString());
                     }
              }

              @Override
              public void onFailure(int statusCode, Throwable throwable, JSONObject error) {
                     // Display a "Toast" message
                     // to announce the failure
                     Toast.makeText(_mainContext, "Error: " + statusCode + " " + throwable.getMessage(), Toast.LENGTH_LONG).show();

                      // Log error message
                      // to help solve any problems
                      Log.e("APIQuery Failure", statusCode + " " + throwable.getMessage());
              }
        });
  }

我的实现工作正常,我有一个ToastMessage,它出现在屏幕上,显示“登录成功”(当然,当它失败时出现“登录错误”)

但我不知道如何处理成功,以便传递给我创建的其他活动。

我想做这样的事情:

if (apiQuery.loginQuery(...)) 
   show(activityLogged); // Where activityLogged is another activity

更新

我添加了这些内容:

if (jsonObject.has("token")) 
{
    /*Toast.makeText(_mainContext, "Login Success!",     Toast.LENGTH_LONG).show();*/
    token = jsonObject.optString("token");
    // 8. For now, just log results
    Log.d("APIQuery Success", jsonObject.toString());
    Intent i = new Intent(_mainContext, MainActivityLogged.class);
    _mainContext.startActivity(i);
}

我的清单文件如下:

                                          

            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />
            <!-- ATTENTION: This data URL was auto-generated. We recommend that you use the HTTP scheme.
              TODO: Change the host or pathPrefix as necessary. -->
            <data
                android:host="epidroid.charvoz.example.com"
                android:pathPrefix="/mainactivitylogged"
                android:scheme="http" />
        </intent-filters>

2 个答案:

答案 0 :(得分:1)

您可以简单地编写一个Intent来移动到onSuccess回调中的下一个活动

 @Override
              public void onSuccess(JSONObject jsonObject) {
                    String token = "";

                    if (jsonObject.has("token")) {
                    /*Toast.makeText(_mainContext, "Login Success!", Toast.LENGTH_LONG).show();*/
                    token = jsonObject.optString("token");
                    Intent i = new Intent(context,LoggedActivity.class);
                    context.startActivity(i);
                     }
              }

在上面的代码中

  Intent i = new Intent(context,LoggedActivity.class);
                    startActivity(i);

这用于导航到下一页。还要确保在清单文件中声明活动。

答案 1 :(得分:0)

您也可以通过意图将一些数据传递给下一个活动,如下所示:

@Override
public void onSuccess(JSONObject jsonObject) {
    String token = "";
    if (jsonObject.has("token")) {
        /*Toast.makeText(_mainContext, "Login Success!", Toast.LENGTH_LONG).show();*/
        token = jsonObject.optString("token");
        Intent i = new Intent(context,LoggedActivity.class);
        i.putExtra("token", token);
        startActivity(i);
    }
}

然后从下一个活动(在onCreate()内部)中检索令牌,如下所示:

String token = getIntent().getStringExtra("token");