Android程序将数据插入mysql数据库

Android程序将数据插入mysql数据库,android,Android,我是android新手,我想将数据插入mysql数据库,我正在使用wamp服务器连接mysql数据库。这段代码,但当我按下add按钮时,它显示Json错误。Plz帮助我解决这个问题。这是代码和我的错误日志 Insert.java package com.example.insert2; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.

我是android新手,我想将数据插入mysql数据库,我正在使用wamp服务器连接mysql数据库。这段代码,但当我按下add按钮时,它显示Json错误。Plz帮助我解决这个问题。这是代码和我的错误日志 Insert.java

package com.example.insert2;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
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 org.json.JSONException;
import org.json.JSONObject;


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class insert extends Activity
{


    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();



     public void onCreate(Bundle savedInstanceState)

     {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.insert);
            Button button = (Button) findViewById(R.id.button1);
            button.setOnClickListener(new View.OnClickListener()
            {
                   public void onClick(View view)
                     {

                        String result = null;
                        InputStream is = null;
                        EditText editText = (EditText)findViewById(R.id.e1);
                        String v1 = editText.getText().toString();
                        EditText editText1 = (EditText)findViewById(R.id.e2);
                        String v2 = editText1.getText().toString();
                        EditText editText2 = (EditText)findViewById(R.id.e3);
                        String v3 = editText2.getText().toString(); 
                        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

                        nameValuePairs.add(new BasicNameValuePair("f1",v1));
                        nameValuePairs.add(new BasicNameValuePair("f2",v2));
                        nameValuePairs.add(new BasicNameValuePair("f3",v3));

                        StrictMode.setThreadPolicy(policy); 


                //http post
                try{
                        HttpClient httpclient = new DefaultHttpClient();
                        HttpPost httppost = new HttpPost("http://192.168.43.159/insert.php");
                        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                        HttpResponse response = httpclient.execute(httppost); 
                        HttpEntity entity = response.getEntity();
                        is = entity.getContent();

                        Log.e("log_tag", "connection success ");
                        Toast.makeText(getApplicationContext(), "pass", Toast.LENGTH_SHORT).show();
                   }


                catch(Exception e)
                {
                        Log.e("log_tag", "Error in http connection "+e.toString());
                        Toast.makeText(getApplicationContext(), "Connection fail", Toast.LENGTH_SHORT).show();

                }
                //convert response to string
                try{
                        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
                        StringBuilder sb = new StringBuilder();
                        String line = null;
                        while ((line = reader.readLine()) != null) 
                        {
                                sb.append(line + "\n");
                                Intent i = new Intent(getBaseContext(),DatabaseActivity.class);
                                startActivity(i);
                        }
                        is.close();

                        result=sb.toString();
                }
                catch(Exception e)
                {
                       Log.e("log_tag", "Error converting result "+e.toString());
                }


                try{

                                JSONObject json_data = new JSONObject(result);

                                CharSequence w= (CharSequence) json_data.get("re");

                                Toast.makeText(getApplicationContext()," w", Toast.LENGTH_SHORT).show();

                     }
                catch(JSONException e)
                   {
                        Log.e("log_tag", "Error parsing data "+e.toString());
                        Toast.makeText(getApplicationContext(), "JsonArray fail", Toast.LENGTH_SHORT).show();
                    }   
           }
           });

    }
    }
package com.example.insert2;
导入java.io.BufferedReader;
导入java.io.InputStream;
导入java.io.InputStreamReader;
导入java.util.ArrayList;
导入org.apache.http.HttpEntity;
导入org.apache.http.HttpResponse;
导入org.apache.http.NameValuePair;
导入org.apache.http.client.HttpClient;
导入org.apache.http.client.entity.UrlEncodedFormEntity;
导入org.apache.http.client.methods.HttpPost;
导入org.apache.http.impl.client.DefaultHttpClient;
导入org.apache.http.message.BasicNameValuePair;
导入org.json.JSONException;
导入org.json.JSONObject;
导入android.app.Activity;
导入android.content.Intent;
导入android.os.Bundle;
导入android.os.StrictMode;
导入android.util.Log;
导入android.view.view;
导入android.widget.Button;
导入android.widget.EditText;
导入android.widget.Toast;
公共类插入扩展了活动
{
StrictMode.ThreadPolicy policy=新建StrictMode.ThreadPolicy.Builder().permitAll().build();
创建时的公共void(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.insert);
按钮按钮=(按钮)findViewById(R.id.button1);
setOnClickListener(新视图.OnClickListener()
{
公共void onClick(视图)
{
字符串结果=null;
InputStream=null;
EditText EditText=(EditText)findViewById(R.id.e1);
字符串v1=editText.getText().toString();
EditText editText1=(EditText)findViewById(R.id.e2);
字符串v2=editText1.getText().toString();
EditText editText2=(EditText)findViewById(R.id.e3);
字符串v3=editText2.getText().toString();
ArrayList nameValuePairs=新的ArrayList();
添加(新的BasicNameValuePair(“f1”,v1));
添加(新的BasicNameValuePair(“f2”,v2));
添加(新的BasicNameValuePair(“f3”,v3));
StrictMode.setThreadPolicy(策略);
//http post
试一试{
HttpClient HttpClient=新的DefaultHttpClient();
HttpPost HttpPost=新的HttpPost(“http://192.168.43.159/insert.php");
setEntity(新的UrlEncodedFormEntity(nameValuePairs));
HttpResponse response=httpclient.execute(httppost);
HttpEntity=response.getEntity();
is=entity.getContent();
Log.e(“Log_标签”,“连接成功”);
Toast.makeText(getApplicationContext(),“pass”,Toast.LENGTH\u SHORT.show();
}
捕获(例外e)
{
e(“Log_标记”,“http连接错误”+e.toString());
Toast.makeText(getApplicationContext(),“连接失败”,Toast.LENGTH\u SHORT.show();
}
//将响应转换为字符串
试一试{
BufferedReader reader=新的BufferedReader(新的InputStreamReader(is,“iso-8859-1”),8;
StringBuilder sb=新的StringBuilder();
字符串行=null;
而((line=reader.readLine())!=null)
{
sb.追加(第+行“\n”);
Intent i=新的Intent(getBaseContext(),DatabaseActivity.class);
星触觉(i);
}
is.close();
结果=sb.toString();
}
捕获(例外e)
{
Log.e(“Log_标记”,“错误转换结果”+e.toString());
}
试一试{
JSONObject json_data=新的JSONObject(结果);
CharSequence w=(CharSequence)json_data.get(“re”);
Toast.makeText(getApplicationContext(),“w”,Toast.LENGTH_SHORT.show();
}
捕获(JSONException e)
{
Log.e(“Log_标记”,“错误解析数据”+e.toString());
Toast.makeText(getApplicationContext(),“JsonArray失败”,Toast.LENGTH\u SHORT.show();
}   
}
});
}
}
我的php文件

insert.php

<?php
$con = mysql_connect("localhost", "root", "");
if (!$con) {
    die('Could not connect: ' . mysql_error());
}
mysql_select_db("ex1", $con);

$v1 = $_REQUEST['f1'];
$v2 = $_REQUEST['f2'];
$v3 = $_REQUEST['f3'];

if ($v1 == NULL || $v2 == NULL || $v3 == NULL) {

    $r["re"] = "Fill the all fields!!!";
    print(json_encode($r));
    die('Could not connect: ' . mysql_error());

}else {
    $i     = mysql_query("select * from t1 where f1=$v1", $con);
    $check = '';
    while ($row = mysql_fetch_array($i)) {

        $check = $row['f1'];

    }

    if ($check == NULL) {

        $q = "insert into t1 values('$v1','$v2','$v3')";
        $s = mysql_query($q);
        if (!$s) {
            $r["re"] = "Inserting problem in batabase";

            print(json_encode($r));
        } else {
            $r["re"] = "Record inserted successfully";
            // $r['0']="Record inserted successfully";

            print(json_encode($r));
        }
    } else {

        $r["re"] = "Record is repeated";
        print(json_encode($r));
        // die('Could not connect: ' . mysql_error());   
    }
}
mysql_close($con);
?>

put结果
print(json_encode($r))JSONObject json_data=new JSONObject(result)之前打印
result
?对不起,先生,我没有关于这个的任何信息写
Log.e(“Log\u tag”,“result:+result”)
before
JSONObject json_data=newjsonobject(结果)并在此处写入logCat结果。