gpt4 book ai didi

java - 异步任务 : class should be static or leaks might occur

转载 作者:行者123 更新时间:2023-11-30 12:03:16 25 4
gpt4 key购买 nike

我正在尝试创建一个从 http 请求返回 json(使用 org.json 依赖项)的函数。要在 Android Java 中执行此操作,必须创建一个 AsyncTask

public class MainActivity extends AppCompatActivity {

TextView resultQuery;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

resultQuery = findViewById(R.id.resultQuery);
try {
new sendUrl().execute();

} catch (Exception e) {
e.printStackTrace();
resultQuery.setText("Erro: " + e);
Toast.makeText(this, "Erro" + e, Toast.LENGTH_SHORT).show();
}
}

private class sendUrl extends AsyncTask<String, Void, String> {

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

try {
call_me();
} catch (Exception e) {
e.printStackTrace();
}
return "";
}

@Override
protected void onPostExecute(String message){
Toast.makeText(MainActivity.this, "PostExecute", Toast.LENGTH_SHORT).show();
}
}

public void call_me() throws Exception {
String url = "https://api.github.com/users/leonanml";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
//add request header
con.setRequestProperty("User-Agent", "Mozilla/5.0");
int responseCode = con.getResponseCode();
//System.out.println("\nSending 'GET' request to URL : " + url);
Toast.makeText(this, "Response Code : " + responseCode, Toast.LENGTH_SHORT).show();
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print in String
//System.out.println(response.toString());
//Read JSON response and print
JSONObject myResponse = new JSONObject(response.toString());
//System.out.println("result after Reading JSON Response");
//System.out.println("id: "+myResponse.getString("login"));
resultQuery.setText(response.toString());
}}

目前我的“sendUrl”类发出警告:

This AsyncTask class should be static or leaks might occur (com.muller.httprequest.MainActivity.sendUrl) Inspection info:A static field will leak contexts.

最佳答案

当你使用一个非静态的内部类时,它不能被垃圾收集器收集,所以它会继续使用内存,简单的解决方法是将内部类设为静态或使其脱离 Activity 类。

关于java - 异步任务 : class should be static or leaks might occur,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57879587/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com