2013-02-16 128 views
0

我已經上傳了一個代碼,用於開發android應用程序連接mysql和php來學習。從這裏開始:http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/ 我試圖做更多的理解相同的步驟。 我創建了一個相同的數據庫中的第二個表(測試)..和我寫的PHP代碼在(測試表)創建一個新的原始.. 這是PHP代碼:連接android應用程序與mysql

<?php 



// array for JSON response 
$response = array(); 

// check for required fields 
if (isset($_POST['name']) && isset($_POST['age'])){ 

    $name = $_POST['name']; 
    $age = $_POST['age']; 
    // include db connect class 
    require_once __DIR__ . '/db_connect.php'; 

    // connecting to db 
    $db = new DB_CONNECT(); 

    // mysql inserting a new row 
    $result = mysql_query("INSERT INTO test (name, age) VALUES('$name', '$age')"); 

    // check if row inserted or not 
    if ($result) { 
     // successfully inserted into database 
     $response["success"] = 1; 
     $response["message"] = "row 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); 
    } 
} else { 
    // required field is missing 
    $response["success"] = 0; 
    $response["message"] = "Required field(s) is missing"; 

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

從那以後,我在Eclipse項目中添加一個Java類,下面是代碼:

package com.example.androidhive; 



import java.util.ArrayList; 
import java.util.List; 

import org.apache.http.NameValuePair; 
import org.apache.http.message.BasicNameValuePair; 
import org.json.JSONException; 
import org.json.JSONObject; 

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

public class NewRowActivity extends Activity{ 

    // Progress Dialog 
     private ProgressDialog pDialog; 

     JSONParser jsonParser = new JSONParser(); 

     EditText inputName; 
     EditText inputAge; 

     // url to create new row 
     private static String url_create_raw = "http://10.0.2.2/test/create_row.php"; 

     // JSON Node names 
     private static final String TAG_SUCCESS = "success"; 

     @Override 
     public void onCreate(Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState); 
      setContentView(R.layout.add_raw); 

      // Edit Text 
      inputName = (EditText) findViewById(R.id.editTextName); 
      inputAge = (EditText) findViewById(R.id.editTextAge); 


      // Create button 
      Button btnAddRow = (Button) findViewById(R.id.buttonAdd); 

      // button click event 
      btnAddRow.setOnClickListener(new View.OnClickListener() { 

       @Override 
       public void onClick(View view) { 
        // creating new product in background thread 
        new CreateNewRow().execute(); 
       } 
      }); 
     } 


     /** 
     * Background Async Task to Create new product 
     * */ 
     class CreateNewRow extends AsyncTask<String, String, String> { 

      /** 
      * Before starting background thread Show Progress Dialog 
      * */ 
      @Override 
      protected void onPreExecute() { 
       super.onPreExecute(); 
       pDialog = new ProgressDialog(NewRowActivity.this); 
       pDialog.setMessage("Adding a raw .."); 
       pDialog.setIndeterminate(false); 
       pDialog.setCancelable(true); 
       pDialog.show(); 
      } 

      /** 
      * Adding raw 
      * */ 
      protected String doInBackground(String... args) { 
       String name = inputName.getText().toString(); 
       String age = inputAge.getText().toString(); 


       // Building Parameters 
       List<NameValuePair> params = new ArrayList<NameValuePair>(); 
       params.add(new BasicNameValuePair("name", name)); 
       params.add(new BasicNameValuePair("age", age)); 


       // getting JSON Object 
       // Note that create product url accepts POST method 
       JSONObject json = jsonParser.makeHttpRequest(url_create_raw, 
         "POST", params); 

       // check log cat fro response 
       Log.d("Create Response", json.toString()); 

       // check for success tag 
       try { 
        int success = json.getInt(TAG_SUCCESS); 

        if (success == 1) { 
         // successfully created product 
         Intent i = new Intent(getApplicationContext(), MainScreenActivity.class); 
         startActivity(i); 

         // closing this screen 
         finish(); 
        } else { 
         // failed to create product 
        } 
       } catch (JSONException e) { 
        e.printStackTrace(); 
       } 

       return null; 
      } 

      /** 
      * After completing background task Dismiss the progress dialog 
      * **/ 
      protected void onPostExecute(String file_url) { 
       // dismiss the dialog once done 
       pDialog.dismiss(); 
      } 

     } 
    } 

當應用程序在模擬器中運行它不工作!模擬器停止。

任何解決方案?

+0

當應用程序崩潰時也發佈日誌,並且將所有與UI相關的代碼從'doInBackground'移動到'onPostExecute' – 2013-02-16 15:20:35

回答

0

您是否爲此示例應用程序配置了Android Manifest,以便它具有訪問互聯網的權限?如果你還沒有這樣做的話,你需要INTERNET權限添加到您的清單文件:

<uses-permission android:name="android.permission.INTERNET" /> 

....某個應用程序標記之外的AndroidManifest.xml

+0

是的,我做到了!但仍然劑量工作 – Sara 2013-02-16 17:52:08

0

你的方法有點超出規範。爲什麼不建立一個類/方法來連接php腳本,然後你可以再調用它呢?這是一種更好的方法。

+0

這是我第一次爲android編程,我只是按照教程中的步驟鏈接..設置我的mysql數據庫,編碼我的php api,然後編碼我的android程序!其實我不明白你的意思:( – Sara 2013-02-16 17:52:32