如何从 JSONParser class 获取字符串变量的值?
How do I get the value of a string variable from a JSONParser class?
我有一个登录网站 API returns 如果您已成功登录则为真,否则为假。
现在我想获取返回值,这就是为什么我使用此 PostAsync
Class 从 JSONParser
[=] 调用 HttpRequest
方法的原因28=].
这些是代码:
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;
}
}
您可以在 AsyncTask 中添加接口 class 以添加监听器,如下所示:
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);
您有以下解决方案:
使异步任务 doInBackground 方法 return 成为您想要的对象,并在 doInBackground 中解析您的 json 并在该对象中保存一些值。
然后在 onPostExecute 中,您获得对象并通过回调将其 return 发送给调用者(activity、片段等)。
解决方案二,只需 return 在 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;
}
我有一个登录网站 API returns 如果您已成功登录则为真,否则为假。
现在我想获取返回值,这就是为什么我使用此 PostAsync
Class 从 JSONParser
[=] 调用 HttpRequest
方法的原因28=].
这些是代码:
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;
}
}
您可以在 AsyncTask 中添加接口 class 以添加监听器,如下所示:
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);
您有以下解决方案:
使异步任务 doInBackground 方法 return 成为您想要的对象,并在 doInBackground 中解析您的 json 并在该对象中保存一些值。
然后在 onPostExecute 中,您获得对象并通过回调将其 return 发送给调用者(activity、片段等)。
解决方案二,只需 return 在 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;
}