时间:2013-08-01 14:56:22

标签: java android mysql json parsing

我一直试图想出一个表格,学员可以申请化妆课程,当他们提交数据时,将存储在数据库中。我是android编程新手,我也使用php连接数据库。

我不知道代码出错的地方

这是我的错误:

08-01 14:04:42.808: E/JSON Parser(5907): Error parsing data org.json.JSONException:      Value <br of type java.lang.String cannot be converted to JSONObject
08-01 14:18:03.149: I/tagconvertstr(5965): [null]
08-01 14:18:03.149: W/dalvikvm(5965): threadid=15: thread exiting with uncaught exception (group=0x40a71930)
08-01 14:18:03.308: E/AndroidRuntime(5965): FATAL EXCEPTION: AsyncTask #5
08-01 14:18:03.308: E/AndroidRuntime(5965): java.lang.RuntimeException: An error occured while executing doInBackground()
08-01 14:18:03.308: E/AndroidRuntime(5965):     at android.os.AsyncTask$3.done(AsyncTask.java:299)
08-01 14:18:03.308: E/AndroidRuntime(5965):     at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
08-01 14:18:03.308: E/AndroidRuntime(5965):     at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
08-01 14:18:03.308: E/AndroidRuntime(5965):     at java.util.concurrent.FutureTask.run(FutureTask.java:239)
08-01 14:18:03.308: E/AndroidRuntime(5965):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
08-01 14:18:03.308: E/AndroidRuntime(5965):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
08-01 14:18:03.308: E/AndroidRuntime(5965):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
08-01 14:18:03.308: E/AndroidRuntime(5965):     at java.lang.Thread.run(Thread.java:856)
08-01 14:18:03.308: E/AndroidRuntime(5965): Caused by: java.lang.NullPointerException
08-01 14:18:03.308: E/AndroidRuntime(5965):     at com.example.testmakeup.Makeup$CreateMakeup.doInBackground(Makeup.java:288)
08-01 14:18:03.308: E/AndroidRuntime(5965):     at com.example.testmakeup.Makeup$CreateMakeup.doInBackground(Makeup.java:1)
08-01 14:18:03.308: E/AndroidRuntime(5965):     at android.os.AsyncTask$2.call(AsyncTask.java:287)
08-01 14:18:03.308: E/AndroidRuntime(5965):     at java.util.concurrent.FutureTask.run(FutureTask.java:234)
08-01 14:18:03.308: E/AndroidRuntime(5965):     ... 4 more

我的Android代码:

import android.app.Activity;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.TimePickerDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TabHost;
import android.widget.TimePicker;
import java.util.ArrayList;
import java.util.Calendar;
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.widget.DatePicker;

public class Makeup extends Activity {
Button AbsentDate;
Button MakeupDate;
Button MakeupTime;
Button Submit;
private int year;
private int month;
private int day;
private int hour;
private int minute;
static final int DATE_DIALOG_ID = 999;
static final int DATE_DIALOG_ID_1 = 1;
static final int TIME_DIALOG_ID = 2;

private EditText name, trainee_id, batch_id, module_name, reason, remarks;
private String department;
private String makeuptime;
private String makeupdate;
private String absentdate;  

private static String Makeup_URL = "http://10.0.2.2/MajorProject/TestMakeup/NewMakeUp.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
// JSON parser class
private ProgressDialog pDialog; 
JSONParser jsonParser = new JSONParser();

public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

        setContentView(R.layout.makeup);            
        TabHost tabs=(TabHost)findViewById(R.id.tabhost); 
        tabs.setup(); 
        TabHost.TabSpec spec=tabs.newTabSpec("tag1"); 
        spec.setContent(R.id.tab1); 
        spec.setIndicator("Make Up Form");          
        tabs.addTab(spec); 
        spec=tabs.newTabSpec("tag2"); 
        spec.setContent(R.id.tab2); 
        spec.setIndicator("Exam Claims"); 
        tabs.addTab(spec);
        tabs.setCurrentTab(0);          
        setCurrentDateOnView();
        addListenerOnButton();
        setCurrentTimeOnView();

        name = (EditText)findViewById(R.id.Name);
        trainee_id =(EditText)findViewById(R.id.TranineeID);
        batch_id = (EditText)findViewById(R.id.BatchID);
        module_name = (EditText)findViewById(R.id.ModuleName);
        reason = (EditText)findViewById(R.id.Reason);
        remarks = (EditText)findViewById(R.id.Remarks); 

         Spinner Spin = (Spinner) findViewById(R.id.spinner1);

            ArrayAdapter<CharSequence> adapter =          ArrayAdapter.createFromResource(this,
                    R.array.DeptName, android.R.layout.simple_spinner_item);
         // Apply the adapter to the spinner
            Spin.setAdapter(adapter);           
            Spin.setOnItemSelectedListener(new MyOnItemSelectedListener());
} 

public class MyOnItemSelectedListener implements OnItemSelectedListener {

    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {

       department = parent.getItemAtPosition(pos).toString();
    }

    public void onNothingSelected(AdapterView parent) {
        // Do nothing.
    }
}

public void setCurrentDateOnView() { 

    AbsentDate = (Button)findViewById(R.id.AbsentDate);
    MakeupDate = (Button)findViewById(R.id.MakeupDate);     
    final Calendar c = Calendar.getInstance();
    year = c.get(Calendar.YEAR);
    month = c.get(Calendar.MONTH);
    day = c.get(Calendar.DAY_OF_MONTH); 
    // set current date into button
    AbsentDate.setText(new StringBuilder()
    // Month is 0 based, just add 1
    .append(day).append("-").append(month + 1).append("-")
    .append(year).append(" "));     
    // set current date into button
    MakeupDate.setText(new StringBuilder()
    // Month is 0 based, just add 1
    .append(day).append("-").append(month + 1).append("-")
    .append(year).append(" ")); 

}   

public void setCurrentTimeOnView(){ 

    MakeupTime = (Button) findViewById(R.id.MakeupTime);        
    final Calendar c = Calendar.getInstance();
    hour = c.get(Calendar.HOUR_OF_DAY);
    minute = c.get(Calendar.MINUTE); 
    // set current time into textview
    MakeupTime.setText(new StringBuilder().append(pad(hour))
    .append(":").append(pad(minute)));

} 

public void addListenerOnButton() {

    AbsentDate = (Button)findViewById(R.id.AbsentDate);

    AbsentDate.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showDialog(DATE_DIALOG_ID);
        }
    });     
    MakeupDate = (Button)findViewById(R.id.MakeupDate);

    MakeupDate.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showDialog(DATE_DIALOG_ID_1);
        }
    });     
    MakeupTime = (Button) findViewById(R.id.MakeupTime);         
    MakeupTime.setOnClickListener(new View.OnClickListener() { 
        @Override
        public void onClick(View v) { 
            showDialog(TIME_DIALOG_ID);
        }
    });     
    Submit =(Button)findViewById(R.id.Submit);
    Submit.setOnClickListener(new OnClickListener(){
        public void onClick(View v){
            new CreateMakeup().execute();
        }
    }); 
}

@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
    case DATE_DIALOG_ID:
       // set date picker as current date
       return new DatePickerDialog(this, datePickerListener, 
                     year, month,day);
    case DATE_DIALOG_ID_1:
           // set date picker as current date
           return new DatePickerDialog(this, datePickerListener1, 
                         year, month,day);
    case TIME_DIALOG_ID:
        // set time picker as current time
        return new TimePickerDialog(this, 
                                    timePickerListener, hour, minute,false);
    }   
    return null;
}  
private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
    // when dialog box is closed, below method will be called.
    public void onDateSet(DatePicker view, int selectedYear,
        int selectedMonth, int selectedDay) {
    year = selectedYear;
    month = selectedMonth;
    day = selectedDay;  
    // set selected date into textview
    AbsentDate.setText(new StringBuilder().append(month + 1)
       .append("-").append(day).append("-").append(year)
       .append(" "));   
    absentdate= AbsentDate.toString();
    }
}; 

private DatePickerDialog.OnDateSetListener datePickerListener1 = new DatePickerDialog.OnDateSetListener() {

    // when dialog box is closed, below method will be called.
    public void onDateSet(DatePicker view, int selectedYear,
        int selectedMonth, int selectedDay) {
    year = selectedYear;
    month = selectedMonth;
    day = selectedDay;  
    // set selected date into textview
    MakeupDate.setText(new StringBuilder().append(month + 1)
       .append("-").append(day).append("-").append(year)
       .append(" "));       
    makeupdate= MakeupDate.toString();      
    }
};

   private TimePickerDialog.OnTimeSetListener timePickerListener = 
        new TimePickerDialog.OnTimeSetListener() {
    public void onTimeSet(TimePicker view, int selectedHour,
            int selectedMinute) {
        hour = selectedHour;
        minute = selectedMinute;

        // set current time into timebutton
        MakeupTime.setText(new StringBuilder().append(pad(hour))
                .append(":").append(pad(minute)));

        makeuptime = MakeupTime.toString();         
    }
};
private static String pad(int c) {
    if (c >= 10)
       return String.valueOf(c);
    else
       return "0" + String.valueOf(c);
}   
 class CreateMakeup extends  AsyncTask<String, String, String> {          
     boolean failure = false;
    private String result;      
           @Override
     protected void onPreExecute() {
            super.onPreExecute();
           pDialog = new ProgressDialog(Makeup.this);
           pDialog.setMessage("Submiting...");
           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;
            String Name = name.getText().toString();
            String Department = department;
            String Trainee_id = trainee_id.getText().toString();
            String Batch_id = batch_id.getText().toString();
            String Absent_date = absentdate;
            String Module_name = module_name.getText().toString();
            String Absentreason = reason.getText().toString();
            String Makeup_date = makeupdate;
            String Makeup_time = makeuptime;
            String Remarks = remarks.getText().toString();                          
            try {
                // Building Parameters
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("name", Name));
                params.add(new BasicNameValuePair("department", Department));
                params.add(new BasicNameValuePair("trainee_id", Trainee_id));
                params.add(new BasicNameValuePair("batch_id", Batch_id));
                params.add(new BasicNameValuePair("absentdate",Absent_date));
                params.add(new BasicNameValuePair("module_name", Module_name));
                params.add(new BasicNameValuePair("reason", Absentreason));
                params.add(new BasicNameValuePair("makeupdate", Makeup_date));
                params.add(new BasicNameValuePair("makeuptime", Makeup_time));
                params.add(new BasicNameValuePair("remarks",  Remarks));    

               Log.d("request!", "starting");

                JSONObject json = jsonParser.makeHttpRequest(
                        Makeup_URL, "POST", params);

                            // Async json success tag
                            success = json.getInt(TAG_SUCCESS);
                            if (success == 1) {
                                Log.d("Submitted", json.toString());
                                finish();                                   
                                return json.getString(TAG_MESSAGE);
                            } else {
                                Log.d("Fail to Submit!", json.getString(TAG_MESSAGE));
                                return json.getString(TAG_MESSAGE);
                            }

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

            return null;
        }           
}
}

和我的php文件:

<?php
$response = array();

// include db connect class
require_once __DIR__ . '/db_connect.php';

// connecting to db
$db = new DB_CONNECT();

// get all products from products table
if (!empty($_POST)) {
//initial query
$query = "INSERT INTO make up ( Trainnee_Name, Department, Trainnee_ID, Batch_ID, Absent_Date, Module_Name, Reason_For_Absent, Makeup_Date, Makeup_Time, Remarks )
 VALUES ( :Trainnee_Name, :Department, :Trainnee_ID, :Batch_ID, :Absent_Date, :Module_Name, :Reason_For_Absent, :Makeup_Date, :Makeup_Time, :Remarks) ";

//Update query
$query_params = array(
    ':Trainnee_Name' => $_POST['name'],
    ':Department' => $_POST['pepartment'],
    ':Trainnee_ID' => $_POST['trainnee_id']
    ':Batch_ID' => $_POST['batch_id']
    ':Absent_Date' => $_POST['absentdate']
    ':Module_Name' => $_POST['module_name']
    ':Reason_For_Absent' => $_POST['reason']
    ':Makeup_Date' => $_POST['Makeupdate']
    ':Makeup_Time' => $_POST['Makeuptime']
    ':Remarks' => $_POST['remarks']
);

//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 add post!";
    die(json_encode($response));
}

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

} 

?>

JSONParser.java的一部分

public JSONObject makeHttpRequest(String url, String method,
        List<NameValuePair> params) { 

if(method == "POST"){
            // request method is POST
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

 try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e   ("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;

}

1 个答案:

答案 0 :(得分:3)

我认为第JSONObject json = jsonParser.makeHttpRequest(Makeup_URL, "POST", params);行会返回无效的Json。根据错误日志,响应为<br>或以<br>开头。解析时哪个失败了。因此,您的json对象为Null。它在Null Pointer Exception上提供Line 288

请问你为什么不返回JSON。你必须要确保响应应该是JSON。