我想将2个文本变量发送到php服务器并将它们存储在数据库中,这就是代码
但我在捕获中得到了吐司(错误)的地方
问题出在哪里?
Android Side
public class MainActivity extends Activity{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("name","android"));
nameValuePairs.add(new BasicNameValuePair("mob","203040"));
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://apptest.ir/test/recive.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
Toast.makeText(this,"Data Send !",Toast.LENGTH_SHORT).show();
}
catch(Exception e)
{
Toast.makeText(this,"Error !",Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
}
这是PHP文件
<?php
$name = isset($_POST['name']) ? $_POST['name'] : '';
$mob = isset($_POST['mob']) ? $_POST['mob'] : '';
$ins = "INSERT INTO table1 (name,mob) VALUES ('$name','$mob')";
$link = mysql_connect('localhost', 'user1', 'pass1');
if (!$link) {die('Not Conected');}
echo 'Conected';
$db_selected = mysql_select_db('test', $link);
if (!$db_selected) {die ('Can\'t use table1 : ' );}
echo 'Database is Selected'.'<br />';
$saved=mysql_query($ins);
if($saved){echo "Data STORED";}
?>
答案 0 :(得分:0)
如果没有堆栈跟踪,我们很难看到问题所在。但我想这个问题是因为你正在从onCreate做“网络”的东西。从版本3.0到更新的这些网络内容你应该在Thread或AsyncTask中运行。但是你可以试着通过将下一行放在onCreate(...)
中来避免这种情况 if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy =
new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}