我正在學習android。我開始使用android進行網絡連接。我面臨的問題是,在try語句下,httpclient.execute(request)行不起作用。相反,catch子句每次都執行。我搜查了很長時間,但我沒有得到有關問題的答案。我很樂意從你方獲得任何幫助。httpclient無法執行httpget對象
這裏是主要的活動
package com.example.androidaspect;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Context context = getApplicationContext();
String url = "http://www.google.com";
TextView tv = (TextView) findViewById(R.id.tvres);
AsyncTaskRunner runner = new AsyncTaskRunner();
runner.execute(url, context, tv);
}
}
這裏是Asynctaskrunner
package com.example.androidaspect;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.TextView;
import android.widget.Toast;
public class AsyncTaskRunner extends AsyncTask<String, String, String>{
Context context;
TextView tv;
String url;
String result="";
public void execute(String url, Context context, TextView tv) {
// TODO Auto-generated method stub
this.tv= tv;
this.context = context;
this.url = url;
}
@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try{
publishProgress("Loading");
HttpClient hc = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
HttpResponse res = hc.execute(request);
BufferedReader rd = new BufferedReader(new InputStreamReader(res.getEntity().getContent()));
String line="";
while((line=rd.readLine())!=null){
result.concat(line);
}
}catch(Exception e){
e.printStackTrace();
}
return result;
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
tv.setText(result);
}
@Override
protected void onProgressUpdate(String... values) {
// TODO Auto-generated method stub
Toast.makeText(context, values[0], Toast.LENGTH_SHORT).show();
}
}
我已經加入了互聯網的權限。我有我的XML這是從網站得到的響應textview。但是當我在模擬器上運行應用程序時,它會運行,但textview不會加載數據。
bcoz你在主界面上運行的網絡操作應該崩潰thrad – Raghunandan
它運行良好。我在網上看到了代碼。他們也在主要用戶界面上做了它。 – Tyagi
這是錯的,你不應該這樣做。它會崩潰發佈蜂窩 – Raghunandan