以下是將數據發送到本地主機服務器中的MySQl數據庫的java代碼。使用的腳本語言是 是php。 Php代碼工作正常,當我通過瀏覽器使用它時,值會被插入。我覺得溝通有錯誤。但我無法 調試它。請幫忙。無法傳遞數據庫中的值
package com.example.databasetest1;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
Button Enter;
EditText tName;
String sName;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Enter = (Button) findViewById(R.id.bEnter);
tName =(EditText)findViewById(R.id.etName);
sName=tName.getText().toString();
Enter.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
HttpClient httpClient = new DefaultHttpClient();
List<NameValuePair> nameValuePair=new ArrayList<NameValuePair>(1);
nameValuePair.add(new BasicNameValuePair("Name",sName));
HttpPost httpPost = new HttpPost("http://192.168.173.1/try_database/name_insert.php");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
httpClient.execute(httpPost);
} catch (ClientProtocolException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
}
});
}
/*public void insert() throws ClientProtocolException, IOException
{
HttpClient httpClient = new DefaultHttpClient();
List<NameValuePair> nameValuePair=new ArrayList<NameValuePair>(1);
nameValuePair.add(new BasicNameValuePair("Name",sName));
HttpPost httpPost = new HttpPost("http://192.168.173.1/try_database/name_insert.php");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
httpClient.execute(httpPost);
}*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
使用的AsyncTask建立連接。 –
'我覺得在通信中有錯誤'。如果發生任何錯誤,請發佈錯誤,不要感到 –
我會將代碼移到異步並告訴ugus發生了什麼。謝謝 – nik