java.lang.RuntimeException:执行doInBackground()时发生错误

时间:2015-07-27 15:15:53

标签: java php android

使用Restful Web服务将数据从Android应用程序发送到PHP时遇到问题。我得到" java.lang.RuntimeException:执行doInBackground()"时发生错误错误。请告诉我该怎么做。感谢。

这是MainActivity.java类

package com.example.contactexchange;

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.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;  
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;

public class MainActivity extends Activity {
EditText lastnameBox, firstnameBox, phonenoBox, addressBox;
Spinner salutationBox;
ImageView imageview;
Button addPhone, saveBox;
String lastname, firstname, phoneno, address, salutation;
JSONParser jsonParser = new JSONParser();
GetIPAddress getIPaddress = new GetIPAddress();
ProgressDialog pDialog;
private static String save_contact;
private static final String TAG_SUCCESS = "success";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    save_contact = getIPaddress.getIP()+"register.php";

    lastnameBox = (EditText)findViewById(R.id.lastnameBox);
    firstnameBox = (EditText)findViewById(R.id.firstnameBox);
    phonenoBox = (EditText)findViewById(R.id.phonenoBox);
    addressBox = (EditText)findViewById(R.id.addressBox);
    salutationBox = (Spinner)findViewById(R.id.spinner1);
    imageview = (ImageView)findViewById(R.id.imageView1);
    addPhone = (Button)findViewById(R.id.button1);
    saveBox = (Button)findViewById(R.id.saveBox);

    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getApplicationContext(),
            R.array.salutation, R.layout.custom_spinner_item);
    // Specify the layout to use when the list of choices appears
    adapter.setDropDownViewResource(R.layout.custom_spinner_dropdown_item);
    // Apply the adapter to the spinner
    salutationBox.setAdapter(adapter);

    salutationBox.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

         salutation = parent.getItemAtPosition(position).toString();

           }

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

        }});

    saveBox.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            /*lastname = lastnameBox.getText().toString();
            firstname = firstnameBox.getText().toString();
            phoneno = phonenoBox.getText().toString();
            address = addressBox.getText().toString();

            Toast.makeText(getApplicationContext(), salutation+" "+lastname+" "+firstname+" "+phoneno+" "+address, Toast.LENGTH_SHORT).show();
        */
        new SaveContact().execute();    
        }
    });
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}



class SaveContact extends AsyncTask<String, String, String> {

 /**
* Before starting background thread Show Progress Dialog
* */
boolean failure = false;

 @Override
 protected void onPreExecute() {
   super.onPreExecute();
//   pDialog = new ProgressDialog(MainActivity.this);
 //  pDialog.setMessage("Saving Contact...");
  // pDialog.setIndeterminate(false);
//   pDialog.setCancelable(true);
 //  pDialog.show();
}

@Override
protected String doInBackground(String... args) {
    // TODO Auto-generated method stub
     // Check for success tag
   int success;

   lastname = lastnameBox.getText().toString();
   firstname = firstnameBox.getText().toString();
   phoneno = phonenoBox.getText().toString();
   address = addressBox.getText().toString();

   // Building Parameters
   List<NameValuePair> params = new ArrayList<NameValuePair>(5);
   params.add(new BasicNameValuePair("salutation", salutation));
   params.add(new BasicNameValuePair("firstname", firstname));
   params.add(new BasicNameValuePair("lastname", lastname));
   params.add(new BasicNameValuePair("phoneno", phoneno)); 
   params.add(new BasicNameValuePair("address", address)); 

    // getting JSON Object
        // Note that create product url accepts POST method
        JSONObject json = jsonParser.makeHttpRequest(save_contact, "POST", params);

        Log.d("Datae" ,salutation+ " " + firstname+" "+lastname+" "+phoneno+" "+address);

        // check log cat fro response
        Log.d("Create Response", json.toString());

        // check for success tag

        try {
            success = json.getInt(TAG_SUCCESS);

            if (success == 1) {
                // successfully created product
                Intent i = new Intent(getApplicationContext(), MainActivity.class);
                startActivity(i);
                //Toast.makeText(getApplicationContext(), "Sussess", Toast.LENGTH_SHORT).show();

                // closing this screen
                finish();
            } else {
                Toast.makeText(getApplicationContext(), "Failc", Toast.LENGTH_SHORT).show();
                // 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();
    }
  }
}

这是register.php

<?php


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

// check for required fields
if (isset($_POST['salutation']) && isset($_POST['firstname']) &&    isset($_POST['lastname']) && isset($_POST['phoneno']) &&      isset($_POST['address'])) {

$salutation = $_POST['salutation'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$phoneno = $_POST['phoneno'];
$address = $_POST['address'];

// 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 contact_info(salutation, first_name, last_name, phone_no, address) VALUES('$salutation', '$firstname', '$lastname', '$phoneno', '$address')");

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

07-27 15:16:44.125: E/AndroidRuntime(455): FATAL EXCEPTION: AsyncTask #1
07-27 15:16:44.125: E/AndroidRuntime(455): java.lang.RuntimeException: An error occured while executing doInBackground()
07-27 15:16:44.125: E/AndroidRuntime(455):  at android.os.AsyncTask$3.done(AsyncTask.java:266)
07-27 15:16:44.125: E/AndroidRuntime(455):  at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
07-27 15:16:44.125: E/AndroidRuntime(455):  at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
07-27 15:16:44.125: E/AndroidRuntime(455):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
07-27 15:16:44.125: E/AndroidRuntime(455):  at java.util.concurrent.FutureTask.run(FutureTask.java:137)
07-27 15:16:44.125: E/AndroidRuntime(455):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1081)
07-27 15:16:44.125: E/AndroidRuntime(455):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:574)
07-27 15:16:44.125: E/AndroidRuntime(455):  at java.lang.Thread.run(Thread.java:1020)
07-27 15:16:44.125: E/AndroidRuntime(455): Caused by: java.lang.NullPointerException
07-27 15:16:44.125: E/AndroidRuntime(455):  at com.example.contactexchange.MainActivity$SaveContact.doInBackground(MainActivity.java:147)
07-27 15:16:44.125: E/AndroidRuntime(455):  at com.example.contactexchange.MainActivity$SaveContact.doInBackground(MainActivity.java:1)
07-27 15:16:44.125: E/AndroidRuntime(455):  at android.os.AsyncTask$2.call(AsyncTask.java:252)
07-27 15:16:44.125: E/AndroidRuntime(455):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
07-27 15:16:44.125: E/AndroidRuntime(455):  ... 4 more
07-27 15:16:44.295: W/IInputConnectionWrapper(455): showStatusIcon on inactive InputConnection
07-27 15:16:46.645: E/InputQueue-JNI(455): channel '40fefa40 PopupWindow:408fcb78 (client)' ~ Publisher closed input channel or an error occurred.  events=0x8

请告诉我该怎么做。感谢

1 个答案:

答案 0 :(得分:0)

我很确定您的问题是您在doInBackground上阅读的EditTexts:

EditText lastnameBox, firstnameBox, phonenoBox, addressBox;

我建议你在按钮点击监听器上获取这些editText字段的值,将这些值保存为字符串并将这些值作为参数发送到doInBackground。

你的doInBackground已经准备好接受一个String数组,所以你只需要将它们作为args值。