gpt4 book ai didi

java - 安卓 : AsynkTask and HttpConnection errors

转载 作者:行者123 更新时间:2023-12-01 12:48:56 25 4
gpt4 key购买 nike

我是 java 和 android 编程新手,通过遵循一些教程,我尝试制作一个 Android 应用程序,该应用程序必须向 php 页面发出 Http 请求以读取输出字符串。我在 doInBackground 方法中收到以下错误:

Multiple markers at this line
- Exception MalformedURLException is not compatible with throws clause in
AsyncTask<Void,String,String>.doInBackground(Void[])
- Exception IOException is not compatible with throws clause in AsyncTask<Void,String,String>.doInBackground(Void[])
- Exception IOException is not compatible with throws clause in AsyncTask<Void,String,String>.doInBackground(Void[])
- implements android.os.AsyncTask<java.lang.Void,java.lang.String,java.lang.String>.doInBackground
- Exception MalformedURLException is not compatible with throws clause in
AsyncTask<Void,String,String>.doInBackground(Void[])

有什么想法吗?谢谢您

这是 MainActivity.java 代码:

public class MainActivity extends Activity {

Button button;
TextView finalResult;

public class ConnessioneAsyncTask extends AsyncTask<Void,String,String>{

@Override
public String doInBackground(Void... v) throws IOException, MalformedURLException{


try{
URL url = new URL("http://myUrl");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
BufferedReader read = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line = read.readLine();
String html = "";
while (line != null){
html += line;
line = read.readLine();
}
return html;
}
catch(MalformedURLException ex){
System.out.println(ex.getMessage());
}
catch(Exception ee){
System.out.println(ee.getMessage());
}
}
@Override
public void onPreExecute(){
}
@Override
public void onPostExecute(String result){
finalResult.setText(result);
}
}

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

button = (Button) findViewById(R.id.asynkButton);
finalResult = (TextView) findViewById(R.id.textView1);
button.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
ConnessioneAsyncTask runner = new ConnessioneAsyncTask();
runner.execute();
}
});
}
}

最佳答案

doInBackground 方法未声明任何 throws 子句,并且您正在尝试添加 throws 声明。您只需在代码中处理所有异常,而不是使用 throws 子句声明它。这是 doInBackground 的 javadoc方法。因此,简而言之,您需要删除 throws 子句才能使其有效。

关于java - 安卓 : AsynkTask and HttpConnection errors,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24405968/

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