2013-03-29 1 views
0

Im новое для кодирования в android. Я не могу вставлять значения в свою базу данных, хотя лог-код показывает, что я вставил его, но база данных не может показать значения, которые я вставил. Прикрепление все коды при этом:Невозможно вставить значения в мою базу данных с помощью сервера XAMPP в приложении для Android.

AlertDialogManager.java

public class AlertDialogManager extends Activity { 

// Progress Dialog 
private ProgressDialog pDialog; 

JSONParser jsonParser = new JSONParser(); 
EditText inputQty; 
EditText inputPrice; 


// url to create new product 
private static String url_create_product = "http://10.0.2.2/Schemes_NAV/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.alert_dialog_text_date_entry); 

    // Edit Text 
    inputPrice = (EditText) findViewById(R.id.et_price); 
    inputQty = (EditText) findViewById(R.id.et_qty); 

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

    // 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(AlertDialogManager.this); 
     pDialog.setMessage("Creating.."); 
     pDialog.setIndeterminate(false); 
     pDialog.setCancelable(true); 
     pDialog.show(); 
    } 

    /** 
    * Creating product 
    * */ 
    protected String doInBackground(String... args) { 
     String Qty = inputQty.getText().toString(); 
     String price = inputPrice.getText().toString(); 


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


     // 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(), Nav.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(); 
    } 

} 

}

Следующая является его расположение т.е. alert_dialog_text_date_entry.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:orientation="vertical" 
    android:gravity="center" 
    > 

    <TextView 
     android:layout_width="248dp" 
     android:layout_height="wrap_content" 
     android:layout_marginLeft="20.0dip" 
     android:layout_marginRight="20.0dip" 
     android:gravity="left" 
     android:text="Qty" 
     android:textAppearance="?android:textAppearanceMedium" /> 

    <EditText 
     android:id="@+id/et_qty" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:layout_marginLeft="20.0dip" 
     android:layout_marginRight="20.0dip" 
     android:autoText="false" 
     android:capitalize="none" 
     android:digits="" 
     android:gravity="fill_horizontal" 
     android:imeActionLabel="Done" 
     android:imeOptions="actionDone" 
     android:inputType="phone" 
     android:numeric="decimal" 
     android:scrollHorizontally="true" 
     android:textAppearance="?android:textAppearanceMedium" /> 

    <TextView 
     android:layout_width="248dp" 
     android:layout_height="wrap_content" 
     android:layout_marginLeft="20.0dip" 
     android:layout_marginRight="20.0dip" 
     android:gravity="left" 
     android:text="Price" 
     android:textAppearance="?android:textAppearanceMedium" /> 

    <EditText 
     android:id="@+id/et_price" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:layout_marginLeft="20.0dip" 
     android:layout_marginRight="20.0dip" 
     android:autoText="false" 
     android:capitalize="none" 
     android:gravity="fill_horizontal" 
     android:imeActionLabel="Done" 
     android:imeOptions="actionDone" 
     android:numeric="decimal" 
     android:scrollHorizontally="true" 
     android:textAppearance="?android:textAppearanceMedium" 

    <TextView 
     android:layout_width="252dp" 
     android:layout_height="wrap_content" 
     android:layout_marginLeft="20.0dip" 
     android:layout_marginRight="20.0dip" 
     android:gravity="left" 
     android:text="Buy Date" 
     android:textAppearance="?android:textAppearanceMedium" /> 

    <DatePicker 
     android:id="@+id/et_datePicker" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" /> 

    <LinearLayout 
     android:id="@+id/linearLayout1" 
     android:layout_width="302dp" 
     android:layout_height="wrap_content" > 

    <Button 
    android:id="@+id/OkButton" 
    android:layout_width="130dp" 
    android:layout_height="wrap_content" 
    android:layout_alignParentRight="true" 
    android:layout_marginLeft="20.0dip" 
    android:text="OK" /> 

    <Button 
    android:id="@+id/cancelButton" 
    android:layout_width="130dp" 
    android:layout_height="wrap_content" 
    android:layout_marginRight="20.0dip" 
    android:text="Cancel" /> 

    </LinearLayout> 

    </LinearLayout> 

Далее, PHP файл create_product.php

<?php 

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

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

$Qty = $_POST['Qty']; 
$price = $_POST['price']; 


// 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 schemes(Qty, price) VALUES('$Qty', '$price')"); 


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

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

И, logcat, который действительно показывает, что он создал новый продукт.

D/dalvikvm(686): GC_FOR_MALLOC freed 6754 objects/755288 bytes in 236ms 
03-29 15:40:09.499: D/Create Response(686): {"message":"Product successfully created.","success":1} 

Пожалуйста, помогите. Спасибо.

+1

что это проблема? –

+0

В базе данных не отображаются значения, которые я пытаюсь вставить в таблицу «Схемы». – user1549124

+0

Создать статический URL-адрес и проверить браузер, независимо от его работы или нет? Таким образом, проблема с идеей может возникнуть в стороне Android или PHP –

ответ

0

Вам нужно перейти ниже двух инструкций от doInBackground к методу onPreExecute.

String Qty = inputQty.getText().toString(); 
String price = inputPrice.getText().toString(); 

doInBackground работает на другом потоке и, следовательно, не имеет доступ к вашей точке зрения деятельности в то время как onPreExecute и onPostExecute метода работает на ваш UI/основной поток и может получить доступ к Activity View.

Ваш код на стороне сервера не проверяет входные данные, которые он получает. В вашем коде doInBackground отправляет пустые значения для количества и цены, и при этих параметрах строка с пустыми значениями будет вставлена, если в этих полях нет ограничений базы данных.

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