2013-11-22 4 views
0

У меня есть этот проект Android, который получает информацию из базы данных с помощью JSON. Теперь моя проблема в том, как я могу обновить существующие данные из базы данных (скажем, я хочу обновить столбец «status», который имеет значение «0», и я хочу сделать его «1»). Это возможно? Вот мой код:Обновление существующих данных в базе данных MySQL с помощью Android

newsfeed_liip_pallet_purchase_order_update.php

<?php 

//load and connect to MySQL database stuff 
require("config.inc.php"); 

if (!empty($_POST)) { 
    //initial query 
    $query = "UPDATE pims_liip_pallet_purchase_order (status) VALUES (:status) "; 

    //Update query 
    $query_params = array(
     ':status' => $_POST['status'], 

    ); 

    //execute query 
    try { 
     $stmt = $db->prepare($query); 
     $result = $stmt->execute($query_params); 
    } 
    catch (PDOException $ex) { 
     // For testing, you could use a die and message. 
     //die("Failed to run query: " . $ex->getMessage()); 

     //or just use this use this one: 
     $response["success"] = 0; 
     $response["message"] = "Database Error. Couldn't update post!"; 
     die(json_encode($response)); 
    } 

    $response["success"] = 1; 
    $response["message"] = "Successfully Updated!"; 
    echo json_encode($response); 

} else { 
?> 

    <?php 
} 

?> 

PalletPurchaseOrder_Clicked.java

package com.pallet.pts; 


public class PalletPurchaseOrder_Clicked extends Activity implements OnClickListener { 

    // Connection detector 
    ConnectionDetector cd; 

    // Alert dialog manager 
    AlertDialogManager alert = new AlertDialogManager(); 

    // Progress Dialog 
    private ProgressDialog pDialog; 

    private Button bApprove, bDisapprove; 

    // Creating JSON Parser object 
    JSONParser jsonParser = new JSONParser(); 

    // Newsfeed JSONArray 
    JSONArray mNewsfeed = null; 

    // Newsfeed id 
    String newsfeed_id = null; 


    // URL for data parsing 
    private static final String READ_COMMENTS_URL = "http://192.168.0.101/PMR_Drupal/sites/all/modules/eclipse/newsfeed_liip_pallet_purchase_order_update.php"; 

    private static final String TAG_SUCCESS = "success"; 
    private static final String TAG_MESSAGE = "message"; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     // TODO Auto-generated method stub 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.pallet_purchase_order_clicked); 
     getActionBar().setDisplayHomeAsUpEnabled(true); 

     cd = new ConnectionDetector(getApplicationContext()); 

      // Check if Internet present 
      if (!cd.isConnectingToInternet()) { 
       // Internet Connection is not present 
       alert.showAlertDialog(PalletPurchaseOrder_Clicked.this, "Internet Connection Error", 
         "Please connect to working Internet connection", false); 
       // stop executing code by return 
       return; 
      } 

      // Approve and Disapprove Buttons 
        bApprove = (Button)findViewById(R.id.btnApprove); 
      bApprove.setOnClickListener(this); 

      bDisapprove = (Button)findViewById(R.id.btnApprove); 
      bDisapprove.setOnClickListener(this); 

      // Actionbar 
      ActionBar ab = getActionBar(); //need import android.app.ActionBar; 
      ColorDrawable colorDrawable = new ColorDrawable(Color.parseColor("#0089fd"));  
         ab.setBackgroundDrawable(colorDrawable); 

      // Get intent from the other page 
      Intent in = getIntent(); 
      po_number = in.getStringExtra("po_number"); 
      date_created = in.getStringExtra("date_created"); 
      trans_name = in.getStringExtra("trans_name"); 
      supplier = in.getStringExtra("supplier"); 
      section_from = in.getStringExtra("section_from"); 
      term_name = in.getStringExtra("term_name"); 
      total_amount = in.getStringExtra("total_amount"); 
      delivery_date = in.getStringExtra("delivery_date"); 
      date_requested = in.getStringExtra("date_requested"); 
      requested_by = in.getStringExtra("requested_by"); 
      prepared_by = in.getStringExtra("prepared_by"); 
      product_code = in.getStringExtra("product_code"); 
      product_description = in.getStringExtra("product_description"); 
      date_prepared = in.getStringExtra("date_prepared"); 
      quantity = in.getStringExtra("quantity"); 
      unit_price = in.getStringExtra("unit_price"); 
      total_amount_paid = in.getStringExtra("total_amount_paid"); 
      qty_delivered = in.getStringExtra("qty_delivered"); 
      notes = in.getStringExtra("notes"); 

      status = in.getStringExtra("status"); 
      status_id = in.getStringExtra("status_id"); 

      // calling background thread 
      new LoadClicked().execute(); 
     } 


    @Override 
    public void onClick(View v) { 
     // TODO Auto-generated method stub 
     new LoadClicked().execute(); 
    } 

    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
     // TODO Auto-generated method stub 
     switch (item.getItemId()) { 
     // Respond to the action bar's Up/Home button 
     case android.R.id.home: 
      NavUtils.navigateUpFromSameTask(this); 
      return true; 
     } 
     return super.onOptionsItemSelected(item); 
    } 

    /** 
    * Background Async Task to get single song information 
    * */ 
    class LoadClicked extends AsyncTask<String, String, String> { 

     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
      pDialog = new ProgressDialog(PalletPurchaseOrder_Clicked.this); 
      pDialog.setMessage("Updating Content..."); 
      pDialog.setIndeterminate(false); 
      pDialog.setCancelable(true); 
      pDialog.show(); 
     } 

     /** 
     * getting song json and parsing 
     * */ 
     protected String doInBackground(String... args) { 
      // Building Parameters 
      List<NameValuePair> params = new ArrayList<NameValuePair>(); 

      // post id as GET parameters 
      params.add(new BasicNameValuePair("po_number", po_number)); 

      // getting JSON string from URL 
      JSONParser jParser = new JSONParser(); 

      JSONObject json = jParser.getJSONFromUrl(READ_COMMENTS_URL); 


      try { 
       JSONObject jObj = new JSONObject(); 
       if(jObj != null){ 

        date_created = jObj.getString(TAG_DATE_CREATED); 
        po_number = jObj.getString(TAG_PO); 
        trans_name = jObj.getString(TAG_TITLE); 
        supplier = jObj.getString(TAG_SUPPLIER); 
        section_from = jObj.getString(TAG_SECTION); 
        term_name = jObj.getString(TAG_TERM); 
        total_amount = jObj.getString(TAG_TOTAL_AMOUNT); 
        delivery_date = jObj.getString(TAG_DELIVERY_DATE); 
        date_requested = jObj.getString(TAG_DATE_REQUESTED); 
        requested_by = jObj.getString(TAG_REQUESTED_BY); 
        prepared_by = jObj.getString(TAG_PREPARED_BY); 
        product_code = jObj.getString(TAG_PRODUCT_CODE); 
        product_description = jObj.getString(TAG_PRODUCT_DESCRIPTION); 
        quantity = jObj.getString(TAG_QUANTITY); 
        unit_price = jObj.getString(TAG_UNIT_PRICE); 
        total_amount_paid = jObj.getString(TAG_TOTAL_AMOUNT_PAID); 
        qty_delivered = jObj.getString(TAG_QTY_DELIVERED); 
        notes = jObj.getString(TAG_NOTES); 

        status = jObj.getString(TAG_STATUS); 
        status_id = jObj.getString(TAG_STATUS_ID); 

       }   

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

      return null; 
     } 

     /** 
     * After completing background task Dismiss the progress dialog 
     * **/ 
     protected void onPostExecute(String file_url) { 
      // dismiss the dialog after getting song information 
      pDialog.dismiss(); 

      // updating UI from Background Thread 
      runOnUiThread(new Runnable() { 
       public void run() { 

        TextView txt_ref_number = (TextView) findViewById(R.id.tvPTRef); 
        TextView txt_po_number = (TextView) findViewById(R.id.tvPONumber); 
        TextView txt_trans_name = (TextView) findViewById(R.id.title); 
        TextView txt_date_created = (TextView) findViewById(R.id.tvDateCreated); 

        TextView txt_supplier = (TextView) findViewById(R.id.tvSupplier); 
        TextView txt_section = (TextView) findViewById(R.id.tvShipTo); 
        TextView txt_term_name = (TextView) findViewById(R.id.tvTerm); 
        TextView txt_total_amount = (TextView) findViewById(R.id.tvTotalAmount); 
        TextView txt_delivery_date = (TextView) findViewById(R.id.tvDeliveryDate); 
        TextView txt_date_requested = (TextView) findViewById(R.id.tvDateRequested); 
        TextView txt_requested_by = (TextView) findViewById(R.id.tvRequestedBy); 
        TextView txt_prepared_by = (TextView) findViewById(R.id.tvPreparedBy); 

        TextView txt_product_code = (TextView) findViewById(R.id.tvProductCode); 
        TextView txt_product_description = (TextView) findViewById(R.id.tvProductDescription); 
        TextView txt_quantity = (TextView) findViewById(R.id.tvQuantity); 
        TextView txt_unit_price = (TextView) findViewById(R.id.tvUnitPrice); 
        TextView txt_total_amount_paid = (TextView) findViewById(R.id.tvTotalAmountPaid); 

        TextView txt_qty_delivered = (TextView) findViewById(R.id.tvQtyDelivered); 
        TextView txt_notes = (TextView) findViewById(R.id.tvNotes); 

        TextView txt_status = (TextView) findViewById(R.id.tvStatus); 
        TextView txt_status_id = (TextView) findViewById(R.id.tvStatusID); 

        //displaying data in view 

        txt_ref_number.setText(ref_number); 
        txt_po_number.setText(po_number); 
        txt_trans_name.setText(trans_name); 
        txt_date_created.setText(date_created); 
        txt_supplier.setText(supplier); 
        txt_section.setText(section_from); 
        txt_term_name.setText(term_name); 
        txt_total_amount.setText(total_amount); 
        txt_delivery_date.setText(delivery_date); 
        txt_date_requested.setText(date_requested); 
        txt_requested_by.setText(requested_by); 
        txt_prepared_by.setText(prepared_by); 
        txt_product_code.setText(product_code); 
        txt_product_description.setText(product_description); 
        txt_quantity.setText(quantity); 
        txt_unit_price.setText(unit_price); 
        txt_total_amount_paid.setText(total_amount_paid); 
        txt_qty_delivered.setText(qty_delivered); 
        txt_notes.setText(notes); 

        txt_status.setText(status); 
        txt_status_id.setText(status_id); 

        // Condition for Status 
        if (status.equals("For Approval")){ 
         Button b1 = (Button) findViewById (R.id.btnApprove); 
         b1.setVisibility(View.VISIBLE); 
         Button b2 = (Button) findViewById (R.id.btnDisApprove); 
         b2.setVisibility(View.VISIBLE); 
        } else { 
         Button b1 = (Button) findViewById (R.id.btnApprove); 
         b1.setVisibility(View.GONE); 
         Button b2 = (Button) findViewById (R.id.btnDisApprove); 
         b2.setVisibility(View.GONE); 
        } 

        // Change Activity Title with preferred title 
        setTitle(po_number); 
       } 
      }); 

     } 

    } 

} 

Как я могу обновить статус? Надеюсь, вы можете мне помочь: D Спасибо заранее!

ответ

0

Вы можете отправить HTTP-запрос на веб-страницу (GET или POST, POST для конфиденциальных данных). Затем сервер будет анализировать данные так, как если бы они были получены из формы <html>.

В соответствии с этим (справедливо устаревшим) blog post, предпочтительный метод: HttpUrlConnection для android 2.3 и выше. Для более старых систем загляните в пакет org.apache.http или даже android.net.http.

Существует также аналогичный вопрос о SO, который использует HttpUrlConnection (PHP HTTP POST on Android device using HttpURLConnection).

Смежные вопросы