繁体   English   中英

无法使用api将数据插入到android中的数据库

[英]Unable to Insert data to database in android using api

我是android的初学者。 我有下面的PHP代码,它为注册过程创建了api

<?php
include_once("../includes/connect.php");
define('USE_AUTHENTICATION', 1);
define('USERNAME', 'user');
define('PASSWORD', '123');
error_reporting (E_ALL ^ E_NOTICE);
ini_set( "display_errors", 0);
error_reporting(E_ERROR | E_PARSE);

if ( USE_AUTHENTICATION == 1 ) 
{
    $jsoncnt="";
    $jsoncnt = file_get_contents('php://input');
    if($jsoncnt!="")
    {
        $json_obj_str = stripslashes($jsoncnt);
        $json_obj = json_decode($json_obj_str, true); 
        $name=$json_obj['name'];
        $mobile_no=$json_obj['mobile_no'];
        $gender=$json_obj['gender'];
        $db_check_email=mysql_query("SELECT * FROM `tbl_register` WHERE `name`='".$name."'");
        $count_check_email=mysql_num_rows($db_check_email);
        if($count_check_email>0)
        {
            $jsn['sTATUS']="ERROR";
            $jsn['mSG']="Name already Exist";
        }
        else
        {


            $db_insert=mysql_query("INSERT INTO `tbl_register`(`name`, `mobile`, `gender`) VALUES ('".$name."','".$mobile_no."','".$gender."')");
            $customer_id=mysql_insert_id();
            if(mysql_affected_rows()==1) 
            {
                $jsn['sTATUS']="SUCCESS";
                $jsn['mSG']="Successfully register";
                $jsn['customer_id']="".$customer_id;

            }
        }        
    }
    else
    {
        $jsn['sTATUS']="ERROR";
        $jsn['mSG']="Server Error - data not set properly";
        $jsn['dATA']['customer_id']="";
    }
    $output= json_encode($jsn);
    echo $output;
 } 
 ?>

下图显示了我的数据库表

数据库表模型

我无法使用上面的PHP代码将我的数据插入数据库。 我被困在这个部分。 我尝试了使用namevalue对的http以及volley。 数据传递空值。

谢谢你的回复,我终于得到了答案。

如果我们使用httpClient。 代码就像

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by ARJUN on 12/15/2016.
 */

public class MainActivity extends Activity implements OnClickListener {
EditText e1,e2,e3,e4;
String name,mobile_no,gender;
ImageView im;
Button b1;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    setContentView(R.layout.activity_main);
    b1=(Button)findViewById(R.id.submit);
    b1.setOnClickListener(this);

}
@Override
public void onClick(View arg0) {
    // TODO Auto-generated method stub
    name="arjun";
    mobile_no="8891834226";
    gender="male";
    login lo=new login();
    lo.execute();
}
class login extends AsyncTask<Void, Void, Void>
{
    @Override
    protected Void doInBackground(Void... params) {
        // TODO Auto-generated method stub
        InputStream inputStream = null;
        String result = "";
        String url = "http://192.168.137.113/insert/register_api.php";

        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            String json1 = "";
            JSONObject jsonObject = new JSONObject();
            jsonObject.accumulate("name", name);
            jsonObject.accumulate("mobile_no",mobile_no);
            jsonObject.accumulate("gender",gender);
            json1 = jsonObject.toString();
            StringEntity se = new StringEntity(json1);
            httpPost.setEntity(se);
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Content-type", "application/json");
            HttpResponse httpResponse = httpclient.execute(httpPost);
            inputStream = httpResponse.getEntity().getContent();

            // 10. convert inputstream to string
            if (inputStream != null) {
                result = convertInputStreamToString(inputStream);
                String myJSON = result;
                Toast.makeText(getBaseContext(),myJSON, Toast.LENGTH_SHORT).show();

            } else {
                result = "Did not work!";
            }
        } catch (Exception e) {
            Log.d("InputStream", e.getLocalizedMessage());
        }

        return null;
    }
    @Override
    protected void onPostExecute(Void result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
        //Toast.makeText(getBaseContext(),response, Toast.LENGTH_SHORT).show();
    }
}

private static String convertInputStreamToString(InputStream inputStream) throws IOException {
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
    String line = "";
    String result3 = "";
    while ((line = bufferedReader.readLine()) != null)
        result3 += line;

    inputStream.close();
    return result3;
}
}

如果我们使用凌空,代码将如下所示

/**
  * Created by Arjun on 3/16/2017.
*/

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import static com.android.volley.VolleyLog.*;

public class VolleyInsert extends AppCompatActivity implements     View.OnClickListener {

private static final String INSERT_URI = "http://192.168.137.113/insert/register_api.php";

public static final String KEY_NAME = "name";
public static final String KEY_MOBILE = "mobile_no";
public static final String KEY_GENDER = "gender";

private Button buttonInsert;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    buttonInsert = (Button) findViewById(R.id.submit);

    buttonInsert.setOnClickListener(this);
}

private void registerUser(){
    RequestQueue rq= Volley.newRequestQueue(this);
    JSONObject jsonBody;
    try {
        jsonBody = new JSONObject();
        jsonBody.put(KEY_NAME, "Arjun");
        jsonBody.put(KEY_MOBILE, "8891834226");
        jsonBody.put(KEY_GENDER, "male");
        final String mRequestBody = jsonBody.toString();

        StringRequest stringRequest = new StringRequest(Request.Method.POST, INSERT_URI, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Toast.makeText(getBaseContext(),response, Toast.LENGTH_SHORT).show();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getBaseContext(),error.toString(), Toast.LENGTH_SHORT).show();
            }
        }) {
            @Override
            public String getBodyContentType() {
                return "application/json; charset=utf-8";
            }

            @Override
            public byte[] getBody() throws AuthFailureError {
                try {
                    return mRequestBody == null ? null : mRequestBody.getBytes("utf-8");
                } catch (UnsupportedEncodingException uee) {
                    wtf("Unsupported Encoding while trying to get the bytes of %s using %s",
                            mRequestBody, "utf-8");
                    return null;
                }
            }
        };
        rq.add(stringRequest);
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

@Override
public void onClick(View v) {
    if(v == buttonInsert){
        registerUser();
    }
}
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM