0

我一直在尝试想出一个表格,学员可以在其中申请化妆课程,并且当他们提交时,数据将存储在数据库中。我是 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

我的安卓代码:

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;

}

无法弄清楚如何使用 $parsers 和 $formatters 创建指令

我想创建一个指令,允许用户以多种格式输入日期。当底层模型发生变化时(无论是通过直接用户输入还是以编程方式),我希望它以标准化格式显示日期。

这种“在野外”的一个例子是谷歌航班上的出发和返回日期输入。

这是我的代码(根本不起作用)。

看法

<input type="text" ng-model="params.departDate" 
  date-input display-format="{Weekday} {d} {Month}, {yyyy}">

控制器

app.controller('MainCtrl', function($scope) {
  $scope.params = {
      departDate: new Date()
  };
  $scope.isDate = function() {
      return $scope.params.departDate instanceof Date;
  }
});

指示

app.directive("dateInput", function() {
    return {
        require: 'ngModel',
        scope: {
            displayFormat: '@'
        },
        link: function (scope, element, attrs, ngModel) {

            ngModel.$parsers.push(function (viewVal) {
                if (viewVal) {
                    // Using sugar.js for date parsing
                    var parsedValue = Date.create(viewVal);
                    if (parsedValue.isValid()) {
                        ngModel.$setValidity("date", true);
                        return parsedValue;
                    }
                }
                ngModel.$setValidity("date", false);
                return viewVal;
            });

            ngModel.$formatters.unshift(function (modelVal) {
                if (modelVal){
                    // Using sugar.js for date formatting
                    var date = Date.create(modelVal);
                    if (date.isValid()) {
                        return date.format(scope.displayFormat || '{Weekday} {d} {Month}, {yyyy}')
                    }
                }
                return modelVal;
            });
        }
    };
})

这甚至不像我预期的那样工作。我究竟做错了什么?

这是一个 PLUNKR:http ://plnkr.co/edit/583yOD6aRhRD8Y2bA5gU?p=preview

4

1 回答 1

3

我认为在线JSONObject json = jsonParser.makeHttpRequest(Makeup_URL, "POST", params);返回无效Json。根据错误日志,响应是<br>或以<br>. 解析时失败。结果,您的 json 对象是Null. 它放弃Null Pointer ExceptionLine 288

请您检查它为什么不返回 JSON。您必须特别确定响应应该是 JSON。

于 2013-08-01T16:33:40.860 回答