如何在Android中显示服务器对应用程序响应的结果?

时间:2017-08-07 09:54:12

标签: android

我正在开发,我想要显示用户登录。以下是我的代码,它在Logcat中显示正确的响应,但未在应用程序端显示消息(即登录成功或登录失败消息)。我该怎么做呢? 我如何在此解析json数据? 请建议我!!

//以下是来自Logcat

内的服务器节目的回复
    {
       "login": [
           {
               "sessionid": 12973,
               "responsetypes": "success"
           }
       ]
    }

//以下是我的代码

    public class LoginActivity extends AppCompatActivity implements View.OnClickListener {

                private EditText usernameEditText;
                private EditText passwordEditText;
                private Button sendGetReqButton;
                TextView tv_forgot;
                Button register;
                Toolbar toolbar;
                private boolean loggedIn = false;

                /** Called when the activity is first created. */
                @Override
                public void onCreate(Bundle savedInstanceState) {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.activity_login);

                    tv_forgot= (TextView)findViewById(R.id.tv_forgot);
                    tv_forgot.setOnClickListener(this);

                    usernameEditText = (EditText) findViewById(R.id.ed_email);
                    passwordEditText = (EditText) findViewById(R.id.ed_passowrd);

                    register = (Button) findViewById(R.id.btn_reg);

                    sendGetReqButton = (Button) findViewById(R.id.btn_login);
                    sendGetReqButton.setOnClickListener(this);
                }

                @Override
                public void onClick(View v) {

                    if(v.getId() == R.id.btn_login){

                            // Get the values given in EditText fields
                            String userID = usernameEditText.getText().toString();
                            String password = passwordEditText.getText().toString();
                            System.out.println("Givennames is :" + userID + " Given password is :" + password);

                            // Pass those values to connectWithHttpGet() method
                            connectWithHttpGet(userID, password);

                        }
                        else {
                            Toast.makeText(LoginActivity.this, "Please Fill the fields", Toast.LENGTH_LONG).show();
                        }
                }

                private void connectWithHttpGet(String userID, String password) {

                    // Connect with a server is a time consuming process.
                    //Therefore we use AsyncTask to handle it
                    // From the three generic types;
                    //First type relate with the argument send in execute()
                    //Second type relate with onProgressUpdate method which I haven't use in this code
                    //Third type relate with the return type of the doInBackground method, which also the input type of the onPostExecute method

                    class HttpGetAsyncTask extends AsyncTask<String, Void, String> {

                        @Override
                        protected String doInBackground(String... params) {

                            // As you can see, doInBackground has taken an Array of Strings as the argument
                            //We need to specifically get the givenUsername and givenPassword

                            String paramUsername = params[0];
                            String paramPassword = params[1];
                            System.out.println("userID" + paramUsername + " password is :" + paramPassword);

                            // Create an intermediate to connect with the Internet
                            HttpClient httpClient = new DefaultHttpClient();

                            // Sending a GET request to the web page that we want
                            // Because of we are sending a GET request, we have to pass the values through the URL
                            HttpGet httpGet = new HttpGet("http://www.example.com/ypAndroid/api/doLogin?userID=" + paramUsername + "&password=" + paramPassword);

                            try {
                                // execute(); executes a request using the default context.
                                // Then we assign the execution result to HttpResponse
                                HttpResponse httpResponse = httpClient.execute(httpGet);
                                System.out.println("httpResponse// getEntity() ; obtains the message entity of this response");
                                // getContent() ; creates a new InputStream object of the entity.
                                // Now we need a readable source to read the byte stream that comes as the httpResponse
                                InputStream inputStream = httpResponse.getEntity().getContent();

                                // We have a byte stream. Next step is to convert it to a Character stream
                                InputStreamReader inputStreamReader = new InputStreamReader(inputStream);

                                // Then we have to wraps the existing reader (InputStreamReader) and buffer the input
                                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

                                // InputStreamReader contains a buffer of bytes read from the source stream and converts these into characters as needed.
                                //The buffer size is 8K
                                //Therefore we need a mechanism to append the separately coming chunks in to one String element
                                // We have to use a class that can handle modifiable sequence of characters for use in creating String
                                StringBuilder stringBuilder = new StringBuilder();

                                String bufferedStrChunk = null;

                                // There may be so many buffered chunks. We have to go through each and every chunk of characters
                                //and assign a each chunk to bufferedStrChunk String variable
                                //and append that value one by one to the stringBuilder
                                while((bufferedStrChunk = bufferedReader.readLine()) != null){
                                    stringBuilder.append(bufferedStrChunk);
                                }

                                // Now we have the whole response as a String value.
                                //We return that value then the onPostExecute() can handle the content
                                System.out.println("Returninge of doInBackground :" + stringBuilder.toString());

                                // If the Username and Password match, it will return "working" as response
                                // If the Username or Password wrong, it will return "invalid" as response
                                return stringBuilder.toString();

                            } catch (ClientProtocolException cpe) {
                                System.out.println("Exceptionrates caz of httpResponse :" + cpe);
                                cpe.printStackTrace();
                            } catch (IOException ioe) {
                                System.out.println("Secondption generates caz of httpResponse :" + ioe);
                                ioe.printStackTrace();
                            }

                            return null;
                        }

                        // Argument comes for this method according to the return type of the doInBackground() and
                        //it is the third generic type of the AsyncTask
                        @Override
                        protected void onPostExecute(String result) {
                            super.onPostExecute(result);

                            System.out.println("Post result :" + result);

                            if(result.equals("success"))
                                Toast.makeText(getApplicationContext(), "HTTP GET is working...", Toast.LENGTH_LONG).show();
                            else  {
                                Toast.makeText(getApplicationContext(), "Invalid...", Toast.LENGTH_LONG).show();
                            }

                        }
                    }

                    // Initialize the AsyncTask class
                    HttpGetAsyncTask httpGetAsyncTask = new HttpGetAsyncTask();
                    // Parameter we pass in the execute() method is relate to the first generic type of the AsyncTask
                    // We are passing the connectWithHttpGet() method arguments to that
                    httpGetAsyncTask.execute(userID, password);

                }
            }

3 个答案:

答案 0 :(得分:0)

例如方法获取错误响应使用volley。

private void getLogin() {

        JSONObject param = new JSONObject();
        try {
            param.put("username", username.getText().toString());
            param.put("password", password.getText().toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }

        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
                Request.Method.POST, url, param, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {

                try {
                    JSONArray jsonArray = response.getJSONArray("login");
                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject jsonObject = jsonArray.getJSONObject(i);
                        Log.d("sessionid>> ", jsonObject.getString("sessionid"));
                    }
                    dissmissPDialog();

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d("error >> ", error.toString());
                streror = error.toString();
                dissmissPDialog();
            }
        }
        );

        normal.add(jsonObjectRequest);
    }

答案 1 :(得分:0)

你可以这样做。

onPostExecute()方法

@Override
protected void onPostExecute(String result) {
    super.onPostExecute(result);

    System.out.println("Post result :" + result);
    try {
        JSONObject jsonObject = new JSONObject(result);
        JSONArray login = jsonObject.getJSONArray("login");
        JSONObject jsonObject1 = login.getJSONObject(0);
        // edited second, you response was responsetype, but I parsed was responsetypes,so you can have a look.
        String responsetypes = jsonObject1.optString("responsetypes");
        // edited
        String sessionid = jsonObject1.getString("sessionid");
        if (TextUtils.equals(responsetypes, "success")) {
            Toast.makeText(getApplicationContext(), "HTTP GET is working...", Toast.LENGTH_LONG).show();
        } else if (TextUtils.equals(responsetypes, "failure")) {
            // edited
            String message = jsonObject1.getString("message");
            Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

答案 2 :(得分:0)

像这样更新您的onPostExecute()方法。

@Override
protected void onPostExecute(String result) {
          super.onPostExecute(result);

       try {
        JSONObject jsonObject1 = new JSONObject(result);
        JSONArray jsonArray = jsonObject1.getJSONArray("login");
        JSONObject jsonObjectLogin = jsonArray.getJSONObject(0);

        String response = jsonObjectLogin.getString("responsetypes");

        Toast.makeText(getApplicationContext(), +response, Toast.LENGTH_LONG).show();

    } catch (JSONException e) {
        e.printStackTrace();
    }    
 }

让我知道这是否有效。