2015-12-17 91 views
0

我使用AsyncHttpClient庫向數據庫插入文本字段值。這是我的代碼。但它不會將數據插入到數據庫base.it返回日誌值[0]和Toast failAndroid AsyncHttpClient使用Json將數據插入數據庫

AsyncHttpClient client=new AsyncHttpClient(); 
     RequestParams params=new RequestParams(); 
     params.put("loc_latitude", mLat.getText().toString()); 
     params.put("loc_longitude", mLon.getText().toString()); 
     params.put("loc_altitude", mAlt.getText().toString()); 

     client.post(SERVICE_URL, params, new JsonHttpResponseHandler(){ 
      public void onSuccess(int statusCode, Header[] headers, JSONObject json) { 

       try { 
        String value = json.getString("posts"); 
        Log.e("val",value.toString()); 
        if(value.equals("[0]")) 
        { 
         Toast.makeText(SCS.this,"Fail",Toast.LENGTH_SHORT).show(); 
        }else{ 
         Toast.makeText(SCS.this,"success",Toast.LENGTH_SHORT).show(); 

        } 

       } catch (JSONException e) { 
        e.printStackTrace(); 
       } 



      } 

這是我的服務端PHP腳本。

include('connection.php'); 
$json = file_get_contents('php://input'); 
$obj = json_decode($json); 
$post = 0; 
$posts = array(); 
$location_info_id         = null; 
$loc_latitude          = isset($obj->{'loc_latitude'}) ? $obj->{'loc_latitude'} : null; 
$loc_longitude          = isset($obj->{'loc_longitude'}) ? $obj->{'loc_longitude'} : null; 
$loc_altitude          = isset($obj->{'loc_altitude'}) ? $obj->{'loc_altitude'} : null; 
if (!empty($loc_latitude) && !empty($loc_longitude)) { 



$sql = "INSERT INTO test_location (location_info_id, loc_latitude, loc_longitude, loc_altitude) VALUES ('". $location_info_id."','". $loc_latitude."','". $loc_longitude."','". $loc_altitude."')"; 

    if ($conn->query($sql) == TRUE) { 

     $last_id = $conn->insert_id; 
     $post = $last_id; 

    } else { 
     $post = 0; 
    } 



} 

$posts = array($post); 

header('Content-type: application/json'); 
print json_encode(array('posts' => $posts)); 

$conn->close(); 
+0

你可以顯示服務器端代碼? –

+0

哪個數據庫?請提供您的數據庫插入代碼。 –

+0

@MustanserIqbal我有我添加服務器端代碼,請您及時檢查 – Yash

回答

0

使用MYSQL數據庫,你可以使用PHP來做到這一點。

那麼這就是你需要添加到插入數據庫中的一個新的記錄代碼:

public class NewProductActivity extends Activity { 

// Progress Dialog 
private ProgressDialog pDialog; 

JSONParser jsonParser = new JSONParser(); 
EditText inputName; 
EditText inputPrice; 
EditText inputDesc; 

// url to create new product 
private static String url_create_product = "http://api.androidhive.info/android_connect/create_product.php"; 

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

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

    // Edit Text 
    inputName = (EditText) findViewById(R.id.inputName); 
    inputPrice = (EditText) findViewById(R.id.inputPrice); 
    inputDesc = (EditText) findViewById(R.id.inputDesc); 

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

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

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

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

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

    /** 
    * Creating product 
    * */ 
    protected String doInBackground(String... args) { 
     String name = inputName.getText().toString(); 
     String price = inputPrice.getText().toString(); 
     String description = inputDesc.getText().toString(); 

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

     // getting JSON Object 
     // Note that create product url accepts POST method 
     JSONObject json = jsonParser.makeHttpRequest(url_create_product, 
       "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(), AllProductsActivity.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(); 
    } 

} 

不要忘了你還需要添加JSON解析器類:

public class JSONParser { 

static InputStream is = null; 
static JSONObject jObj = null; 
static String json = ""; 

// constructor 
public JSONParser() { 

} 

// function get json from url 
// by making HTTP POST or GET mehtod 
public 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; 

} 

最後,您需要添加PHP腳本以將行插入表中。

希望這有助於:)

+0

感謝you.but我想要去AsyncHttpClient庫 – Yash

+0

不是上述AsyncHttp客戶端? –