【问题标题】:How do I get the value of a string variable from a JSONParser class?如何从 JSONParser 类中获取字符串变量的值?
【发布时间】:2016-06-01 17:19:17
【问题描述】:

我有一个登录 Web API,如果您成功登录,则返回 true,否则返回 false。

现在我想获取返回值,这就是为什么我使用这个 PostAsync 类调用来自 JSONParser 类的 HttpRequest 方法。

这些是代码:

public class Sign_inFragment extends Fragment {

    String email, password, logInResult;
    EditText ev, pv;
    Button bv;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.sign_in_fragment, container, false);

        bv = (Button) v.findViewById(R.id.signinButton);
        ev = (EditText) v.findViewById(R.id.emailTextView);
        pv = (EditText) v.findViewById(R.id.passwordTextView);

        bv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ev.getText() != null && pv.getText() != null) {
                    email = ev.getText().toString();
                    password = pv.getText().toString();

                    new PostAsync().execute(email, password);

                    //logInResult = //Get the value from the API which should return true or false
                }
            }
        });

        return v;
    }
}

public class PostAsync extends AsyncTask<String, String, JSONObject> {

    JSONParser jsonParser = new JSONParser();

    private ProgressDialog pDialog;

    private static final String LOGIN_URL = "http://my-api.mydoctorfinder.com/logger";

    private static final String TAG_SUCCESS = "success";
    private static final String TAG_MESSAGE = "message";


    /*@Override
    protected void onPreExecute() {
        pDialog = new ProgressDialog(MainActivity.this);
        pDialog.setMessage("Attempting login...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }*/

    @Override
    protected JSONObject doInBackground(String... args) {

        try {

            HashMap<String, String> params = new HashMap<>();
            params.put("email", args[0]);
            params.put("password", args[1]);

            Log.d("request", "starting");

            JSONObject json = jsonParser.makeHttpRequest(
                    LOGIN_URL, "POST", params);

            if (json != null) {
                Log.d("JSON result", json.toString());

                return json;
            }

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


        return null;
    }

    protected void onPostExecute(JSONObject json) {

        int success = 0;
        String message = "";

        if (pDialog != null && pDialog.isShowing()) {
            pDialog.dismiss();
        }

        if (json != null) {
            //Toast.makeText(MainActivity.this, json.toString(),
                    //Toast.LENGTH_LONG).show();

            try {
                success = json.getInt(TAG_SUCCESS);
                message = json.getString(TAG_MESSAGE);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        if (success == 1) {
            Log.d("Success!", message);
        }else{
            Log.d("Failure", message);
        }
    }

}

public class JSONParser {
    String charset = "UTF-8";
    HttpURLConnection conn;
    DataOutputStream wr;
    StringBuilder result;
    URL urlObj;
    JSONObject jObj = null;
    StringBuilder sbParams;
    String paramsString;
    String logInResult;

    public JSONObject makeHttpRequest(String url, String method, HashMap<String, String> params) {

        sbParams = new StringBuilder();
        int i = 0;
        for (String key : params.keySet()) {
            try {
                if (i != 0){
                    sbParams.append("&");
                }
                sbParams.append(key).append("=")
                        .append(URLEncoder.encode(params.get(key), charset));

            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            i++;
        }

        if (method.equals("POST")) {
            // request method is POST
            try {
                urlObj = new URL(url);

                conn = (HttpURLConnection) urlObj.openConnection();

                conn.setDoOutput(true);

                conn.setRequestMethod("POST");

                conn.setRequestProperty("Accept-Charset", charset);

                conn.setReadTimeout(10000);
                conn.setConnectTimeout(15000);

                conn.connect();

                paramsString = sbParams.toString();

                wr = new DataOutputStream(conn.getOutputStream());
                wr.writeBytes(paramsString);
                wr.flush();
                wr.close();

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        else if(method.equals("GET")){
            // request method is GET

            if (sbParams.length() != 0) {
                url += "?" + sbParams.toString();
            }

            try {
                urlObj = new URL(url);

                conn = (HttpURLConnection) urlObj.openConnection();

                conn.setDoOutput(false);

                conn.setRequestMethod("GET");

                conn.setRequestProperty("Accept-Charset", charset);

                conn.setConnectTimeout(15000);

                conn.connect();

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

        }

        try {
            //Receive the response from the server
            InputStream in = new BufferedInputStream(conn.getInputStream());
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            result = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                result.append(line);
            }

            Log.d("JSON Parser", "result: " + result.toString());

            logInResult = result.toString();//I want to get the value of this String variable.

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

        conn.disconnect();

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(result.toString());
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON Object
        return jObj;
    }

}

【问题讨论】:

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


    【解决方案1】:

    您有以下解决方案:
    使异步任务 doInBackground 方法返回您想要的对象,并在 doInBackground 中解析您的 json 并将一些值保存在该对象中。
    然后在 onPostExecute 中获取对象并通过回调将其返回给调用者(活动、片段等)。
    解决方案二,只需在 doInBackground 中返回所需的字符串并在 onPostExecute 中获取它,并按照我在第一个解决方案中所说的那样做。 对象示例(字符串也是如此):

     @Override
    protected CustomObject doInBackground(String... args) {
        CustomObject customObject = null;
        try {
    
            HashMap<String, String> params = new HashMap<>();
            params.put("email", args[0]);
            params.put("password", args[1]);
    
            Log.d("request", "starting");
    
            JSONObject json = jsonParser.makeHttpRequest(
                    LOGIN_URL, "POST", params);
    
            if (json != null) {
                Log.d("JSON result", json.toString());
    
               //parse your json;
               //for example:
               customObject = parseCustomObject(json);
            }
    
        } catch (Exception e) {
            e.printStackTrace();
        }
    
    
        return customObject;
    }
    

    【讨论】:

    • 您仍然必须使用接口将对象传递回调用类。我明白了……
    • 等等,你从哪里得到的 parseCustomObject 方法?
    • 你必须自己实现它。这是伪代码,不是工作代码。
    【解决方案2】:

    您可以在 AsyncTask 类中添加接口以添加监听器,如下所示:

    public interface AsyncTaskCompleteListener {
        public void asyncTaskComplted(String result);
    
    }
    

    在 onPostExecute 方法获得成功后,将结果字符串传递为:

    mAsyncTaskCompleteListener.asyncTaskComplted(message);
    

    您可以将侦听器对象传递给 Async 的构造函数。检查以下:

    public PostAsync(AsyncTaskCompleteListener  mAsyncTaskCompleteListener){
        this.mAsyncTaskCompleteListener=mAsyncTaskCompleteListener;
    }
    

    并在您的片段中调用它,例如:

    new PostAsync(new PostAsync.AsyncTaskCompleteListener() {
            @Override
            public void asyncTaskComplted(String result) {
                Log.print("Result string :  "+result);
            }
        }).execute(email, password);
    

    【讨论】:

    • 还有一件事,您如何将该消息放入它开始的 Fragment 类中?我很想看看如何处理该消息的示例代码。
    • @Chris 我已经更新了我的答案。我在您的代码中注意到的另一件事是,在错误响应的情况下,它会抛出 JSONException,即 Boolean 无法转换为 JSONObject。您需要在转换为 JSONObject 之前处理它。
    猜你喜欢
    • 2013-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-28
    • 2014-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多