我是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();
}
});
}
}
答案 0 :(得分:1)
doInBackground
方法不会声明任何throws clause
并且您正在尝试添加throws声明。您需要在代码中处理所有异常,而不是使用throws子句声明它。这是doInBackground方法的javadoc。因此,简而言之,您需要删除throws子句才能使其有效。