2012-04-09 54 views
0

我想從Android手機應用程序發佈數據到PHP腳本。這是我正在使用的代碼。從Android應用程序發佈數據到PHP腳本

public class Upload extends Activity implements OnClickListener { 
EditText joke; 
Button upload; 
AlertDialog alertDialog = new AlertDialog.Builder(this).create(); 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    // TODO Auto-generated method stub 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.upload); 
} 
public void onClick(View v) { 
    // TODO Auto-generated method stub 
    switch (v.getId()) { 
    case R.id.bUpload: 
     uploadJoke(); 
     break; 
    } 

} 
private void uploadJoke() { 
    // Create a new HttpClient and Post Header 
    HttpClient httpclient = new DefaultHttpClient(); 
    HttpPost httppost = new HttpPost("http://xxxx/telejoke.php"); 

    try { 
     // Add your data 
     List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); 
     nameValuePairs.add(new BasicNameValuePair("username", "test")); 
     nameValuePairs.add(new BasicNameValuePair("joke", joke.getText().toString())); 
     httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

     // Execute HTTP Post Request 
     HttpResponse response = httpclient.execute(httppost); 

    } catch (ClientProtocolException e) { 
     alertDialog.setTitle("Client Protocol Exception"); 
    } catch (IOException e) { 
     alertDialog.setTitle("IOException"); 
    } 
} 

}

然而,當我嘗試我的Android手機上運行它,它只是出現意外錯誤崩潰。幫助與此表示讚賞。

+0

你好moesef,plz發佈你的錯誤日誌,所以,我可以建議的變化,thx – 2012-04-09 06:52:19

+0

你正在主線程運行網絡操作,我建議你移動你的網絡操作在新線程或AsyncTask, – 2012-04-09 06:53:22

+0

錯誤有東西與AlertDialog有關。當我在uploadJoke方法內部移動AlertDialog時,它將取出錯誤...但我仍然不認爲數據被髮布到我的PHP腳本中。 – moesef 2012-04-09 07:34:48

回答

0

UploadJoke方法中移動AlertDialog alertDialog = new AlertDialog.Builder(this).create();可修復此問題。

相關問題