0

我想将 2 个文本变量发送到 php 服务器并将它们存储在数据库中,这是代码
,但我得到了那个 toast(错误)的地方,问题在哪里?

安卓端

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";} 
?>
4

1 回答 1

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);
    }
于 2013-07-06T12:56:59.090 回答