java - 在android中使用mysql、json将数据插入在线服务器。

标签 java php android mysql json

我用了this example 将数据插入在线服务器的我的表中。可能这篇文章是重复的,但我无法 找出我的代码出了什么问题。我在这里看到了很多帖子并相应地修改了我的 但仍然错误。请帮助我。

inser.php

      <?php
    $response = array();
    $connect = mysqli_connect(" "," "," "," ");

    if(mysqli_connect_errno($connect))
  {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
   }
else
{
echo "success";
}

   $Make = isset($_POST['Make']) ? $_POST['Make'] : '';
   $Model = isset($_POST['Model']) ? $_POST['Model'] : '';

  $RegNo=isset($_POST['RegNo']) ? $_POST['RegNo'] : '';
  $Engine=isset($_POST['Engine']) ? $_POST['Engine']: '';
  $Chasis=isset($_POST['Chasis']) ? $_POST['Chasis']: '';
  $query = mysqli_query($connect, "insert into car (Make, Model,RegNo,Engine,Chasis) values
 ('$Make','$Model','$RegNo','$Engine','$Chasis') ");
 //$query = mysqli_query($connect, "insert into car (Make, Model,RegNo,Engine,Chasis) 
 values('Maruthi' ,'Ma22','434','42343','32423') ");
 // check if row inserted or not
 if ($query) {
    // successfully inserted into database
    $response["success"] = 1;
    $response["message"] = "Product successfully created.";

    // echoing JSON response
    echo json_encode($response);
 } else {
    // failed to insert row
    $response["success"] = 0;
    $response["message"] = "Oops! An error occurred.";

    // echoing JSON response
    echo json_encode($response);
}


mysqli_close($connect);
?>

MainActivity.java

     import org.json.JSONArray;
     import org.json.JSONException;
     import com.example.cardetails.CustomHttpClient;
     public class MainActivity extends Activity {
CustomHttpClient jsonParser = new CustomHttpClient();
 private ProgressDialog pDialog;
String[] make1 = {"general motors","audi","ford","maruthi suzuki","toyota","travelz"};
public EditText chasis;
public EditText engno;
public EditText regno;
public EditText model;
public EditText textView;
public JSONObject json;

  private static final String TAG_SUCCESS = "success";

   protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_main);
      model=(EditText)findViewById(R.id.model);
      regno=(EditText)findViewById(R.id.Registerno);
      engno=(EditText)findViewById(R.id.engine);
          chasis=(EditText)findViewById(R.id.chasis);       
      ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_dropdown_item_1line,make1);
final   AutoCompleteTextView textView= (AutoCompleteTextView)findViewById(R.id.ap);

textView.setThreshold(1);
textView.setAdapter(adapter);
    Button save=(Button)findViewById(R.id.save);
    Button cancel=(Button)findViewById(R.id.cancel);
     save.setOnClickListener(new View.OnClickListener() {
             public void onClick(View v) {
                  new CreateNewProduct().execute();
                    }
             });}
   class CreateNewProduct extends AsyncTask<String, String, String> {

    protected void onPreExecute() {
   super.onPreExecute();
   ProgressDialog pDialog = new ProgressDialog(MainActivity.this);
   pDialog.setMessage("Adding details..");
   pDialog.setIndeterminate(false);
   pDialog.setCancelable(true);
   pDialog.show();
  }

 protected String doInBackground(String... args) {

 String Make = textView.getText().toString();
 String Model = model.getText().toString();
 String RegNo= regno.getText().toString();
 String Engine=engno.getText().toString();
 String Chasis=chasis.getText().toString();
   // Building Parameters
   List<NameValuePair> params = new ArrayList<NameValuePair>();
  params.add(new BasicNameValuePair("Make",Make ));
   params.add(new BasicNameValuePair("Model",Model));
   params.add(new BasicNameValuePair("RegNo",RegNo));
   params.add(new BasicNameValuePair("Engine",Engine));
   params.add(new BasicNameValuePair("Chasis",Chasis));
   // getting JSON Object
   // Note that create product url accepts POST method
   int success=0;
   JSONObject json = CustomHttpClient.makeHttpRequest( "http://***.com/DB/insert.php",
           "POST", params);


   Log.d("Create Response", json.toString());
   // check for success tag
   try {
       success = json.getInt(TAG_SUCCESS);

   } catch (JSONException e) {
       e.printStackTrace();
       success=0;
   }

   return ""+success;
   }

   protected void onPostExecute(String result) {

  pDialog.dismiss();
  if (Integer.parseInt(result) == 1) {

     Intent i = new Intent(
     MainActivity.this,CreateTripActivity.class);
   startActivity(i);
   finish();
  } else {
     //your task here
  }
 }
 }

}   

我的 logcat 是

03-24 03:51:16.124: D/(1451): HostConnection::get() New Host Connection established 0xb7569238,       
03-24 03:51:16.374: W/EGL_emulation(1451): eglSurfaceAttrib not implemented
03-24 03:51:16.404: D/OpenGLRenderer(1451): Enabling debug mode 0
03-24 03:51:20.374: D/dalvikvm(1451): GC_FOR_ALLOC freed 112K, 6% free 3153K/3348K, paused 57ms,     
03-24 03:51:20.494: D/dalvikvm(1451): GC_FOR_ALLOC freed 6K, 6% free 3202K/3404K, paused 112ms,   
03-24 03:51:20.494: I/dalvikvm-heap(1451): Grow heap (frag case) to 3.810MB for 635812-byte      
03-24 03:51:20.614: D/dalvikvm(1451): GC_FOR_ALLOC freed 2K, 6% free 3821K/4028K, paused 118ms, 
03-24 03:51:20.834: W/EGL_emulation(1451): eglSurfaceAttrib not implemented
03-24 03:51:28.834: W/dalvikvm(1451): threadid=12: thread exiting with uncaught exception   
(group=0xb3b08ba8)
03-24 03:51:28.874: E/AndroidRuntime(1451): FATAL EXCEPTION: AsyncTask #2
03-24 03:51:28.874: E/AndroidRuntime(1451): Process: com.example.cardetails, PID: 1451
03-24 03:51:28.874: E/AndroidRuntime(1451): java.lang.RuntimeException: An error occured while      

 executing doInBackground()
 03-24 03:51:28.874: E/AndroidRuntime(1451): at android.os.AsyncTask$3.done(AsyncTask.java:300)
 03-24 03:51:28.874: E/AndroidRuntime(1451):    at    

 java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
 03-24 03:51:28.874: E/AndroidRuntime(1451):    at 

 java.util.concurrent.FutureTask.setException(FutureTask.java:222)
 03-24 03:51:28.874: E/AndroidRuntime(1451):    at   

 java.util.concurrent.FutureTask.run(FutureTask.java:242)
 03-24 03:51:28.874: E/AndroidRuntime(1451):    at 

 android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
 03-24 03:51:28.874: E/AndroidRuntime(1451):    at 

 java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
 03-24 03:51:28.874: E/AndroidRuntime(1451):    at  

 java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
 03-24 03:51:28.874: E/AndroidRuntime(1451):    at java.lang.Thread.run(Thread.java:841)
 03-24 03:51:28.874: E/AndroidRuntime(1451): Caused by: java.lang.NullPointerException
 03-24 03:51:28.874: E/AndroidRuntime(1451):    at    

 com.example.cardetails.MainActivity$CreateNewProduct.doInBackground(MainActivity.java:73)
 03-24 03:51:28.874: E/AndroidRuntime(1451):    at   

com.example.cardetails.MainActivity$CreateNewProduct.doInBackground(MainActivity.java:1)
03-24 03:51:28.874: E/AndroidRuntime(1451): at android.os.AsyncTask$2.call(AsyncTask.java:288)
03-24 03:51:28.874: E/AndroidRuntime(1451): at     

java.util.concurrent.FutureTask.run(FutureTask.java:237)
03-24 03:51:28.874: E/AndroidRuntime(1451):     ... 4 more
03-24 03:51:28.914: W/EGL_emulation(1451): eglSurfaceAttrib not implemented
03-24 03:51:30.634: I/Choreographer(1451): Skipped 31 frames!  The application may be doing too    

 much work on its main thread.
 03-24 03:51:31.814: I/Process(1451): Sending signal. PID: 1451 SIG: 9

编辑: CustomHttpClient.java

       public class CustomHttpClient {
    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public CustomHttpClient() {

    }

    // function get json from url
    // by making HTTP POST or GET mehtod
    public static JSONObject makeHttpRequest(String url,String method, List<NameValuePair>  

      params) {

        // Making HTTP request
        try {

            // check for request method
            if(method == "POST"){
                // request method is POST
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();

            }else if(method == "GET"){
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
                HttpGet httpGet = new HttpGet(url);

                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }           

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        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");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}

最佳答案

你需要改变

if(method == "POST"){

if(method.equals("POST")){

GET 类似

改变

else if(method == "GET"){

else if(method.equals("GET")){

比较字符串时需要使用.equals.equlasIgnoreCase

编辑:

你得到的是一个字符串,因此不是一个 jsonobject

其次改变这个

protected void onPreExecute() {
super.onPreExecute();
ProgressDialog pDialog = new ProgressDialog(MainActivity.this);

protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);

关于java - 在android中使用mysql、json将数据插入在线服务器。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22603935/

相关文章:

php - 调用未定义函数 wp_mail

php - 对 ORDER BY FIELD 产生的记录组进行排序

java - 清除数据结构/重启Android应用程序

java - Android 在内部根目录中创建文件夹

android - 带有 api 16 和 Webview 的 MotionEvent (Android)

java - 尝试在 Java 中加载 json 文件时出现 NPE

php - ErrorException (E_ERROR) 类 'app\MyLib\MyClass' 未找到 - 类似的类工作正常

java - 行为类似于 boolean 值的自定义 Java 类型?

java - 在 Play 框架中使用 ElementCollection 时出现 LazyInitializationException

java - 获取 NoSuchMethodError :javax. servlet.ServletContext.getVirtualServerName()