2012-12-01 58 views
1

我有一個創建連接的新實例的活動。像這樣:引發空異常的HTTP請求

public class myActivity extends Activity { 

TextView tv; 
ProgressDialog dialog = null; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.daily_news); 

    gestureDetector = new GestureDetector(new SwipeGestureDetector()); 
    tv = (TextView) findViewById(R.id.tx); 
    dialog = ProgressDialog.show(myActivity.this, "","Validating user...", true); 
    connection con = new connection(dialog); 
    final String str =con.connect_to_db("http://10.0.2.2:8000/daily/my.php"); 

    runOnUiThread(new Runnable() { 
     public void run() { 
      tv.setText(str); 
      dialog.dismiss(); 
     } 
    });   
} 

}

在連接類

我有一個返回null一個HttpResponse。像這樣:

public class connection { 

private HttpPost httppost; 
private HttpClient httpclient; 
private HttpResponse response; 
private ProgressDialog dialog = null; 
private String result; 

public connection(ProgressDialog di){ 
    dialog = di; 
} 
public String connect_to_db(String url){ 

    try{    
     httpclient=new DefaultHttpClient(); 
     httppost= new HttpPost(url); 
     response=httpclient.execute(httppost); 
     ResponseHandler<String> responseHandler = new BasicResponseHandler(); 
     result = httpclient.execute(httppost, responseHandler); 
    }catch(Exception e){ 
     dialog.dismiss(); 
     System.out.println("Exception : " + e.getMessage()); 
    } 
    return result; 
} 

}

爲什麼 「結果」 的連接類中的值爲null?

+0

檢查主機,端口以及服務器是否在手機上可見(給出的ip可能不是)。同時驗證對這個url路徑的請求是否真的是post請求。 –

+0

請遵循java中的一般命名約定:以caps,方法和變量開頭的類以駱駝爲基礎。 –

+0

您是否在Manifest中設置了Internet權限?還請檢查是否響應,se也是null –

回答

1

這條線:

final String str =con.connect_to_db("http://10.0.2.2:8000/daily/my.php"); 

不應寫在OnCreate,而是在一個單獨的線程=> NetworkOnMainThreadException

爲了您的空指針,請告訴我們,如果你有在清單中的Internet權限並且如果迴應爲空或不是。

+0

當我檢查我的代碼時,它會運行到 「httppost = new HttpPost(url);」之後,進入例外。 – sahar

+0

我也有互聯網permision清單。 – sahar

+0

拋出哪個異常?什麼是堆棧跟蹤或消息? – joel

0

可能是因爲您在onCreate方法中進行網絡操作。如果你使用的是android2.2,它不會產生任何問題,但如果它是HoneyComb,那麼很有可能它會導致一些異常,最後你會得到空值。將代碼移動到onResume()方法。

爲簡單起見使用

的HttpResponse響應= httpclient.execute(httppost);

String valueString = EntityUtils.toString(response.getEntity()); 
int statusCode = response.getStatusLine().getStatusCode(); 

打印這些值,並看到了把。