将记录插入phpmyadmin时出现A​​synctask错误

时间:2016-06-17 05:01:28

标签: android android-asynctask phpmyadmin

我一直在尝试将值插入数据库,但点击按钮后应用程序崩溃了。我有两个asynctask类。是因为那个吗?任何帮助或教程链接都会很棒!代码在

之下
public class DataEntry extends Activity implements OnItemSelectedListener {
    EditText edt_name,edt_age;
    RadioGroup gendergroup;
    RadioButton radioGenderButton;
    Spinner spnr_currentAilment; 
    Spinner spnr_pastAilment;
    Spinner spnr_Place,spnr_Area;
    ArrayList<CurrentAilment> c_ailmentList;
    ArrayList<getArea> arealist;
    ArrayList<getPlace> placelist;
    Button btn_submit;
    String name,age,gender,current_ailment,past_ailment,place,area;
    ProgressDialog pDialog;

    // Url to get all the current ailments
    private String URL = "http://192.168.0.105/colg_project/health_project.php";
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.data_entry);
       /* ActionBar actionBar = getActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
*/
        edt_name = (EditText)findViewById(R.id.editName);
        edt_age = (EditText)findViewById(R.id.editAge); 
        gendergroup = (RadioGroup)findViewById(R.id.radioGroupGender);
        spnr_currentAilment = (Spinner)findViewById(R.id.spinnerCurrentAilment);
        spnr_pastAilment = (Spinner)findViewById(R.id.spinnerPastAilment);
        spnr_Place = (Spinner)findViewById(R.id.spinnerPlaceName);
        spnr_Area = (Spinner)findViewById(R.id.spinnerAreName);
        btn_submit = (Button)findViewById(R.id.btn_Submit);
            c_ailmentList = new ArrayList<CurrentAilment>();
        new GetInformation().execute();
        // spinner item select listener
        spnr_currentAilment.setOnItemSelectedListener(this);
        spnr_Place.setOnItemSelectedListener(new OnItemSelectedListener(){
            @Override
            public void onItemSelected(AdapterView<?> parent, View view,int position, long id) {
                // TODO Auto-generated method stub
                List<String> area_array = new ArrayList<String>();
                for(int j=0;j<arealist.size();j++){
                        if(placelist.get(position).getPlaceId().equals(arealist.get(j).getPlaceId())  ){
                            area_array.add(arealist.get(j).getAreaName());
                            //Log.e("","spiner1"+arealist.get(j).getAreaName());
                        }
                    }
                ArrayAdapter<String> adapter_area = new ArrayAdapter<String>(DataEntry.this, 
                android.R.layout.simple_spinner_item, area_array);
                adapter_area.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                // attaching data adapter to spinner
                spnr_Area.setAdapter(adapter_area);
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // TODO Auto-generated method stub
                    }
                });
        btn_submit.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                name = edt_name.getText().toString();
                age = edt_age.getText().toString();
                radioGenderButton = (RadioButton) findViewById(gendergroup.getCheckedRadioButtonId());
                gender = radioGenderButton.getText().toString();
            //  Log.e("","" + gender);
                Toast.makeText(getApplicationContext(), "" + gender, Toast.LENGTH_SHORT).show();
                current_ailment = spnr_currentAilment.getSelectedItem().toString();
                past_ailment = spnr_pastAilment.getSelectedItem().toString();
                place = spnr_Place.getSelectedItem().toString();
                area = spnr_Area.getSelectedItem().toString();
                insertToDatabase(name,age,gender,current_ailment,past_ailment,place,area);

            }
        });
    }
     private void populateSpinner() {
            List<String> ailments_array = new ArrayList<String>();
            for (int i = 0; i < c_ailmentList.size(); i++) {
                ailments_array.add(c_ailmentList.get(i).getCurrent_ailment());
            }
                // Creating adapter for spinner
         ArrayAdapter<String> adapter_ailment = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item, ailments_array);
           adapter_ailment.setDropDownViewResource(R.layout.spinner_item);
            spnr_currentAilment.setAdapter(adapter_ailment);
            spnr_pastAilment.setAdapter(adapter_ailment);

            //for places spinner 
            List<String> place_array = new ArrayList<String>();
            for(int i = 0;i < placelist.size();i++)
            {
                place_array.add(placelist.get(i).getPlaceName());
            }
            ArrayAdapter<String> adapter_places =  new ArrayAdapter<String>(this,
                    android.R.layout.simple_spinner_dropdown_item,place_array);
            adapter_places.setDropDownViewResource(R.layout.spinner_item);
            spnr_Place.setAdapter(adapter_places);

        }

     private class GetInformation extends AsyncTask<Void, Void, Void> {
                @Override
            protected void onPreExecute() {
                super.onPreExecute();
                pDialog = new ProgressDialog(DataEntry.this);
                pDialog.setMessage("loading..");
                pDialog.setCancelable(false);
                pDialog.show();
                }

            @Override
            protected Void doInBackground(Void... arg0) {
                ServiceHandler jsonParser = new ServiceHandler();
                String json = jsonParser.makeServiceCall(URL, ServiceHandler.GET);
                placelist = new ArrayList<getPlace>();
                arealist = new ArrayList<getArea>();
              //  Log.e("Response: ", "> " + json);
                if (json != null) {
                    try {
                        JSONObject jsonObj = new JSONObject(json);
                        if (jsonObj != null) {
                            JSONArray ailments = jsonObj.getJSONArray("ailments");
                            JSONArray places = jsonObj.getJSONArray("places");
                            JSONArray areas = jsonObj.getJSONArray("areas");

                                for (int i = 0; i < ailments.length(); i++) {
                                JSONObject c_ailObj = (JSONObject) ailments.get(i);
                                CurrentAilment ail = new CurrentAilment();
                                ail.setId(Integer.parseInt(c_ailObj.getString("id")));
                                ail.setCurrent_ailment(c_ailObj.getString("ca_name"));
                                c_ailmentList.add(ail);
                            }

                               for (int i = 0; i < places.length(); i++) {
                                    JSONObject place_obj = (JSONObject) places.get(i);
                                    getPlace get_place = new getPlace();
                                    get_place.setPlaceId(place_obj.getString("place_id"));
                                    get_place.setPlaceName(place_obj.getString("place_name"));
                                    placelist.add(get_place);
                                }

                              for (int i = 0; i < areas.length(); i++) {
                                    JSONObject area_obj = (JSONObject) areas.get(i);
                                   getArea get_area = new getArea();
                                    get_area.setAreaId(area_obj.getString("area_id"));
                                    get_area.setAreaName(area_obj.getString("area_name"));
                                    get_area.setPlaceId(area_obj.getString("place_id"));
                                    arealist.add(get_area);
                                }


                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    Log.e("JSON Data", "Didn't receive any data from server!");
                }
                    return null;
            }
                @Override
            protected void onPostExecute(Void result) {
                super.onPostExecute(result);
                if (pDialog.isShowing())
                    pDialog.dismiss();
              populateSpinner();
            }
            }

     private void insertToDatabase(String name, String age,String gender,String c_ailment,String p_ailment,String place,String area){
            class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
                @Override
                protected String doInBackground(String... params) {
                    String paramUsername = params[0];
                    String paramAddress = params[1];
                   String name = edt_name.getText().toString();
                    String age = edt_age.getText().toString();
                    radioGenderButton = (RadioButton) findViewById(gendergroup.getCheckedRadioButtonId());
                    String gender = radioGenderButton.getText().toString();
                //  Log.e("","" + gender);
                    Toast.makeText(getApplicationContext(), "" + gender, Toast.LENGTH_SHORT).show();
                    String c_ailment = spnr_currentAilment.getSelectedItem().toString();
                    String p_ailment = spnr_pastAilment.getSelectedItem().toString();
                    String place = spnr_Place.getSelectedItem().toString();
                    String area = spnr_Area.getSelectedItem().toString();

                    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                    nameValuePairs.add(new BasicNameValuePair("name", name));
                    nameValuePairs.add(new BasicNameValuePair("age", age));
                    nameValuePairs.add(new BasicNameValuePair("gender", gender));
                    nameValuePairs.add(new BasicNameValuePair("c_ailment", c_ailment));
                    nameValuePairs.add(new BasicNameValuePair("p_ailment", p_ailment));
                    nameValuePairs.add(new BasicNameValuePair("place", place));
                    nameValuePairs.add(new BasicNameValuePair("area", area));
                    try {
                        HttpClient httpClient = new DefaultHttpClient();
                        HttpPost httpPost = new HttpPost("192.168.0.105/insert_colg_dp.php");
                        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                        HttpResponse response = httpClient.execute(httpPost);
                        HttpEntity entity = response.getEntity();

                    } catch (ClientProtocolException e) {

                    } catch (IOException e) {

                    }
                    return "success";
                }

                @Override
                protected void onPostExecute(String result) {
                    super.onPostExecute(result);

                    Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();

                }
            }
            SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
            sendPostReqAsyncTask.execute(name, age, gender,c_ailment,p_ailment,place,area);
        }
     @Override
     public boolean onOptionsItemSelected(MenuItem item) {
         switch (item.getItemId()) {
         case android.R.id.home:
          finish();
             return true;
         default:
             return super.onOptionsItemSelected(item);
         }
     }

        @Override
        public void onItemSelected(AdapterView<?> parent, View view,
                int position, long id) {
            // TODO Auto-generated method stub
            /* ((TextView) parent.getChildAt(0)).setTextColor(Color.MAGENTA);
                ((TextView) parent.getChildAt(0)).setTextSize(12);*/

        }
        @Override
        public void onNothingSelected(AdapterView<?> parent) {
            // TODO Auto-generated method stub

        }
    }

我的PHP代码:

<?php


    $con = mysqli_connect("localhost","root","","college_project") or die("Error " . mysqli_error($connection));

        $name = $_POST['name'];
        $age = $_POST['age'];
        $gender = $_POST['gender'];
        $c_ailment = $_POST['c_ailment'];
        $p_ailment = $_POST['p_ailment'];
        $place = $_POST['place'];
        $area = $_POST['area'];



        //Creating an sql query2
        $sql = "INSERT INTO records (user_name,age,gender,current_ailment,past_ailment,place,area)
        VALUES ('$name','$age','$gender','$c_ailment','$p_ailment','$place','$area')";

        //Executing query to database
        if(mysqli_query($con,$sql)){
            echo 'Success';
        }
        else{
            echo 'Failure';
        }

        //Closing the database 
        mysqli_close($con);

?>

最后是log cat:

06-16 23:45:49.807: E/AndroidRuntime(615): FATAL EXCEPTION: AsyncTask #3
06-16 23:45:49.807: E/AndroidRuntime(615): java.lang.RuntimeException: An error occured while executing doInBackground()
06-16 23:45:49.807: E/AndroidRuntime(615):  at android.os.AsyncTask$3.done(AsyncTask.java:278)
06-16 23:45:49.807: E/AndroidRuntime(615):  at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
06-16 23:45:49.807: E/AndroidRuntime(615):  at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
06-16 23:45:49.807: E/AndroidRuntime(615):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
06-16 23:45:49.807: E/AndroidRuntime(615):  at java.util.concurrent.FutureTask.run(FutureTask.java:137)
06-16 23:45:49.807: E/AndroidRuntime(615):  at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
06-16 23:45:49.807: E/AndroidRuntime(615):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
06-16 23:45:49.807: E/AndroidRuntime(615):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
06-16 23:45:49.807: E/AndroidRuntime(615):  at java.lang.Thread.run(Thread.java:856)
06-16 23:45:49.807: E/AndroidRuntime(615): Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
06-16 23:45:49.807: E/AndroidRuntime(615):  at android.os.Handler.<init>(Handler.java:121)
06-16 23:45:49.807: E/AndroidRuntime(615):  at android.widget.Toast$TN.<init>(Toast.java:317)
06-16 23:45:49.807: E/AndroidRuntime(615):  at android.widget.Toast.<init>(Toast.java:91)
06-16 23:45:49.807: E/AndroidRuntime(615):  at android.widget.Toast.makeText(Toast.java:233)
06-16 23:45:49.807: E/AndroidRuntime(615):  at colg.project.healthapp.DataEntry$1SendPostReqAsyncTask.doInBackground(DataEntry.java:220)
06-16 23:45:49.807: E/AndroidRuntime(615):  at colg.project.healthapp.DataEntry$1SendPostReqAsyncTask.doInBackground(DataEntry.java:1)
06-16 23:45:49.807: E/AndroidRuntime(615):  at android.os.AsyncTask$2.call(AsyncTask.java:264)
06-16 23:45:49.807: E/AndroidRuntime(615):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
06-16 23:45:49.807: E/AndroidRuntime(615):  ... 5 more

1 个答案:

答案 0 :(得分:1)

似乎你试图从doInBackground()方法调用任何UI小部件,这是不可能直接实现的,因为AsyncTask是工作线程而不是UI线程。因此,您需要在runOnUiThread()方法中调用doInBackground()方法。

activity.runOnUiThread(new Runnable() {
    public void run() {
        Toast.makeText(activity, "Hello", Toast.LENGTH_SHORT).show();
    }
});