2015-08-09 2 views
0

im new для программирования на Android, iv пытался подключиться к удаленному серверу и отправить данные в базу данных mysql, мой код работает нормально, но когда я нажимаю кнопку для публикации в базе данных, приложение выходит из строя и дает ошибку «к сожалению, приложение перестало работать», но когда я проверяю db, данные были вставлены. может кто-то посмотреть код и рассказать мне, почему приложение терпит крах и, возможно, исправить его.Ошибка при отправке в mysql от android

мой XML-код

<!-- Name Label --> 
    <TextView android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:text="Product Name" 
     android:paddingLeft="10dip" 
     android:paddingRight="10dip" 
     android:paddingTop="10dip" 
     android:textSize="17dip"/> 

    <!-- Input Name --> 
    <EditText android:id="@+id/inputName" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:layout_margin="5dip" 
     android:layout_marginBottom="15dip" 
     android:singleLine="true"/> 

    <!-- Price Label --> 
    <TextView android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:text="Price" 
     android:paddingLeft="10dip" 
     android:paddingRight="10dip" 
     android:paddingTop="10dip" 
     android:textSize="17dip"/> 

    <!-- Input Price --> 
    <EditText android:id="@+id/inputPrice" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:layout_margin="5dip" 
     android:layout_marginBottom="15dip" 
     android:singleLine="true" 
     android:inputType="numberDecimal"/> 

    <!-- Description Label --> 
    <TextView android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:text="Description" 
     android:paddingLeft="10dip" 
     android:paddingRight="10dip" 
     android:paddingTop="10dip" 
     android:textSize="17dip"/> 

    <!-- Input description --> 
    <EditText android:id="@+id/inputDesc" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:layout_margin="5dip" 
     android:layout_marginBottom="15dip" 
     android:lines="4" 
     android:gravity="top"/> 

    <!-- Button Create Product --> 
     <Button android:id="@+id/btnCreateProduct" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:text="Create Product"/> 

</LinearLayout> 

мой ява файл

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; 
import android.widget.Toast; 

public class NewProduct extends Activity { 

    // Progress Dialog 
    private ProgressDialog pDialog; 

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


    private static String url_create_product = "http:////bsa.co.ke/androidconnect/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.activity_new_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(NewProduct.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 from response 
      Log.d("Create Response", json.toString()); 

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

       if (success == 1) { 
        // successfully created product 
        Toast.makeText(NewProduct.this, 
          "Success", Toast.LENGTH_LONG) 
          .show(); 


        // 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

Java наверняка, Дэвид добавить свой журнал чтобы увидеть, какую ошибку вы получаете. –

+0

, но этот финиш на успех закрывает эту активность, а на кассе выполняет pDialog.dismiss(), похоже, что у вас есть ошибка. Попытка закрыть диалог прогресса, которого нет в памяти, потому что вы уже закончили. –

ответ

0

Проблема заключается в вашей Toast линии.

AyncTask создает поток, и вы пытаетесь вызвать Toast из этого потока. Но, внутренне, когда называется Toast, он в свою очередь вызывает другой поток, который является потоком пользовательского интерфейса. Вы не можете вызвать поток пользовательского интерфейса из фонового потока. Я sugges вы двигаетесь, что Тост к другой части (как postExecute), но если вы действительно хотите, где вы можете сделать это с runOnUiThread Это будет выглядеть следующим образом:

runOnUiThread(new Runnable() { 
public void run() { 

    Toast.makeText(NewProduct.this, "success", Toast.LENGTH_LONG).show(); 
    } 
}); 
Смежные вопросы