class GetData extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
HttpURLConnection urlConnection = null;
String result = "";
try {
URL url = new URL("http://192.168.0.100/index.php?kod=1eba7936&mode=1");
urlConnection = (HttpURLConnection) url.openConnection();
int code = urlConnection.getResponseCode();
if(code==200){
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
if (in != null) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = bufferedReader.readLine()) != null)
result += line;
}
in.close();
}
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
urlConnection.disconnect();
}
return result;
}
@Override
protected void onPostExecute(String result) {
System.out.println(result);
super.onPostExecute(result);
}
}
我有这样的类,它的工作很棒,我无法捕获变量,因为它返回 void。结果是其单个整数值。System.out.println(result( 在控制台上显示适当的值。
我从主活动调用函数
new GetData().execute();
我的目标是将 GetData 的结果作为 MainActivity 中的整数变量。
我用公共字符串制作了新类
public class Data {
public static String data;
}
在onPostExecute中,我添加:
Data.data = result.toString();
现在我可以将 Data.data 用作我想要的字符串。