如何从JSONParser类中获取字符串变量的值?

时间:2016-05-31 11:42:48

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

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

现在我想获得返回值,这就是我使用PostAsync类调用来HttpRequestJSONParser方法的原因。

这些是代码:

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;
    }

}

2 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:0)

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

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);