gpt4 book ai didi

java - Android - 单击按钮时使用 AsyncTask 发送 HTTP 请求 |委托(delegate)问题

转载 作者:行者123 更新时间:2023-12-01 09:33:08 26 4
gpt4 key购买 nike

我即将编写一个小应用程序。单击按钮后,我在自定义异步任务类中发送 http 请求。我想将此值写入 EditText 字段和 ListView 作为项目。我现在的问题是我想将请求的值返回到主线程以进一步处理它。我四处搜寻,发现了一个带有接口(interface)的方法。这是我的 asynctask 类:

    public class Request extends AsyncTask<String,Void,String> {
public AsyncResponse delegate=null;
private MainActivity mAct;
public Request(MainActivity mainActivity){
this.mAct = mainActivity;
}
@Override
protected String doInBackground(String... url){
String returnString = "";
try {
URL u = new URL(url[0]);
final HttpURLConnection connection = (HttpURLConnection)u.openConnection();
BufferedInputStream bis = new BufferedInputStream(connection.getInputStream());
byte[] content = new byte[1024];
int bytesRead = 0;
String strContent = "";
while((bytesRead = bis.read(content)) != -1){
strContent += new String(content,0,bytesRead);
}
returnString = strContent;
} catch (Exception e){

} finally {
return returnString;
}
}
protected void onPostExecute(String result){
delegate.processFinish(result);
}
}

这是我的主要 Activity :

    protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button btnSend = (Button)findViewById(R.id.btnSendMessage);
final ListView lv = (ListView)findViewById(R.id.treeView);
final EditText editText = (EditText)findViewById(R.id.txtReqID);

final MainActivity ma = this;
final ArrayList<String> arrList = new ArrayList<String>();
final ArrayAdapter<String> arrAdapter = new ArrayAdapter<String>(getApplicationContext(),R.layout.simple_list_item_1,arrList);

btnSend.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
String t = new String("http://myhttprequest");
Request r = new Request(ma);
public void onCreate(Bundle savedInstanceState){
r.delegate = this;
}

editText.setText(returnValue);
lv.setAdapter(arrAdapter);
arrList.add(returnValue);
arrAdapter.notifyDataSetChanged();
}
});
}
public interface AsyncResponse{
void processFinish(String output);
}

问题是我必须将每个变量声明为final,因为我在函数中访问它们。我现在对我的代码不太满意,我也不知道如何才能完成这项工作。非常感谢任何帮助。

致以诚挚的问候

最佳答案

试试这个方法:

 btnSend.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
String t = new String("http://myhttprequest");
Request r = new Request(ma){
protected void onPostExecute(String result){
editText.setText(result);
lv.setAdapter(result);
arrList.add(result);
arrAdapter.result();
}
};

}
});

关于java - Android - 单击按钮时使用 AsyncTask 发送 HTTP 请求 |委托(delegate)问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39231259/

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