值小于,java.lang.String类型BR无法转换到的JSONObject [英] Value <br of type java.lang.String cannot be converted to JSONObject
问题描述
我一直在试图想出一个表单,实习生可以申请化妆的经验教训,当他们提交的数据将存储在数据库中。我是新来的Android编程,我也使用PHP来连接到数据库。
我不知道那里的codeS哪里出了问题。
这是我的错误:
08-01 14:04:42.808:E / JSON解析器(5907):错误解析数据org.json.JSONException:值小于; BR java.lang.String类型不了被转换成的JSONObject
08-01 14:18:03.149:I / tagconvertstr(5965):[空]
08-01 14:18:03.149:W / dalvikvm(5965):主题ID = 15:线程退出与未捕获的异常(组= 0x40a71930)
08-01 14:18:03.308:E / AndroidRuntime(5965):致命异常:AsyncTask的#5
08-01 14:18:03.308:E / AndroidRuntime(5965):java.lang.RuntimeException的:一个错误而执行doInBackground发生()
08-01 14:18:03.308:E / AndroidRuntime(5965):在android.os.AsyncTask $ 3.done(AsyncTask.java:299)
08-01 14:18:03.308:E / AndroidRuntime(5965):在java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
08-01 14:18:03.308:E / AndroidRuntime(5965):在java.util.concurrent.FutureTask.setException(FutureTask.java:219)
08-01 14:18:03.308:E / AndroidRuntime(5965):在java.util.concurrent.FutureTask.run(FutureTask.java:239)
08-01 14:18:03.308:E / AndroidRuntime(5965):在android.os.AsyncTask $ SerialExecutor $ 1.运行(AsyncTask.java:230)
08-01 14:18:03.308:E / AndroidRuntime(5965):在java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
08-01 14:18:03.308:E / AndroidRuntime(5965):在java.util.concurrent.ThreadPoolExecutor中的$ Worker.run(ThreadPoolExecutor.java:573)
08-01 14:18:03.308:E / AndroidRuntime(5965):在java.lang.Thread.run(Thread.java:856)
08-01 14:18:03.308:E / AndroidRuntime(5965):由:显示java.lang.NullPointerException
08-01 14:18:03.308:E / AndroidRuntime(5965):在com.example.testmakeup.Makeup $ CreateMakeup.doInBackground(Makeup.java:288)
08-01 14:18:03.308:E / AndroidRuntime(5965):在com.example.testmakeup.Makeup $ CreateMakeup.doInBackground(Makeup.java:1)
08-01 14:18:03.308:E / AndroidRuntime(5965):在android.os.AsyncTask $ 2.call(AsyncTask.java:287)
08-01 14:18:03.308:E / AndroidRuntime(5965):在java.util.concurrent.FutureTask.run(FutureTask.java:234)
08-01 14:18:03.308:E / AndroidRuntime(5965):4 ...更多
我的Android codeS:
进口android.app.Activity;
进口android.widget.AdapterView;
进口android.widget.ArrayAdapter;
进口android.app.DatePickerDialog;
进口android.app.Dialog;
进口android.app.ProgressDialog;
进口android.app.TimePickerDialog;
进口android.os.AsyncTask;
进口android.os.Bundle;
进口android.util.Log;
进口android.view.View;
进口android.view.View.OnClickListener;
进口android.widget.AdapterView.OnItemSelectedListener;
进口android.widget.Button;
进口android.widget.EditText;
进口android.widget.Spinner;
进口android.widget.TabHost;
进口android.widget.TimePicker;
进口的java.util.ArrayList;
进口的java.util.Calendar;
进口的java.util.List;
进口org.apache.http.NameValuePair;
进口org.apache.http.message.BasicNameValuePair;
进口org.json.JSONException;
进口org.json.JSONObject;
进口android.widget.DatePicker;
公共类化妆延伸活动{
按钮AbsentDate;
按钮MakeupDate;
按钮MakeupTime;
按钮提交;
私人诠释一年;
私人诠释一个月;
私人诠释天;
私人诠释小时;
私人诠释分钟;
静态最终诠释DATE_DIALOG_ID = 999;
静态最终诠释DATE_DIALOG_ID_1 = 1;
静态最终诠释TIME_DIALOG_ID = 2;
私人的EditText名称,trainee_id,BATCH_ID,MODULE_NAME,究其原因,言论;
私人字符串部;
私人字符串makeuptime;
私人字符串makeupdate;
私人字符串absentdate;
私有静态字符串Makeup_URL =http://10.0.2.2/MajorProject/TestMakeup/NewMakeUp.php;
私有静态最后弦乐TAG_SUCCESS =成功;
私有静态最后弦乐TAG_MESSAGE =消息;
// JSON解析器类
私人ProgressDialog pDialog;
JSONParser jsonParser =新JSONParser();
公共无效的onCreate(包savedInstanceState){
super.onCreate(savedInstanceState);
的setContentView(R.layout.makeup);
TabHost标签=(TabHost)findViewById(R.id.tabhost);
tabs.setup();
TabHost.TabSpec规格= tabs.newTabSpec(标签1);
spec.setContent(R.id.tab1);
spec.setIndicator(化妆表);
tabs.addTab(规范);
规格= tabs.newTabSpec(标签2);
spec.setContent(R.id.tab2);
spec.setIndicator(考试要求);
tabs.addTab(规范);
tabs.setCurrentTab(0);
setCurrentDateOnView();
addListenerOnButton();
setCurrentTimeOnView();
名称=(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);
原因=(EditText上)findViewById(R.id.Reason);
备注=(EditText上)findViewById(R.id.Remarks);
微调旋转=(微调)findViewById(R.id.spinner1);
ArrayAdapter&LT; CharSequence的&GT;适配器= ArrayAdapter.createFromResource(这一点,
R.array.DeptName,android.R.layout.simple_spinner_item);
//应用适配器微调
Spin.setAdapter(适配器);
Spin.setOnItemSelectedListener(新MyOnItemSelectedListener());
}
公共类MyOnItemSelectedListener实现OnItemSelectedListener {
公共无效onItemSelected(适配器视图&LT;&GT;母公司视图中查看,INT POS,长ID){
部门= parent.getItemAtPosition(POS)的ToString();
}
公共无效onNothingSelected(适配器视图父){
// 没做什么。
}
}
公共无效setCurrentDateOnView(){
AbsentDate =(按钮)findViewById(R.id.AbsentDate);
MakeupDate =(按钮)findViewById(R.id.MakeupDate);
最后的日历C = Calendar.getInstance();
年= c.get(Calendar.YEAR);
月= c.get(Calendar.MONTH);
天= c.get(Calendar.DAY_OF_MONTH);
//将当前日期到按钮
AbsentDate.setText(新的StringBuilder()
//月第一个值为0,只需添加1
.append(天).append( - )。追加(月+ 1).append( - )
.append(年).append());
//将当前日期到按钮
MakeupDate.setText(新的StringBuilder()
//月第一个值为0,只需添加1
.append(天).append( - )。追加(月+ 1).append( - )
.append(年).append());
}
公共无效setCurrentTimeOnView(){
MakeupTime =(按钮)findViewById(R.id.MakeupTime);
最后的日历C = Calendar.getInstance();
小时= c.get(Calendar.HOUR_OF_DAY);
分钟= c.get(Calendar.MINUTE);
//将当前时间到的TextView
MakeupTime.setText(新的StringBuilder()。追加(垫(小时))
.append(:)。追加(PAD(分钟)));
}
公共无效addListenerOnButton(){
AbsentDate =(按钮)findViewById(R.id.AbsentDate);
AbsentDate.setOnClickListener(新View.OnClickListener(){
@覆盖
公共无效的onClick(视图v){
的ShowDialog(DATE_DIALOG_ID);
}
});
MakeupDate =(按钮)findViewById(R.id.MakeupDate);
MakeupDate.setOnClickListener(新View.OnClickListener(){
@覆盖
公共无效的onClick(视图v){
的ShowDialog(DATE_DIALOG_ID_1);
}
});
MakeupTime =(按钮)findViewById(R.id.MakeupTime);
MakeupTime.setOnClickListener(新View.OnClickListener(){
@覆盖
公共无效的onClick(视图v){
的ShowDialog(TIME_DIALOG_ID);
}
});
提交=(按钮)findViewById(R.id.Submit);
Submit.setOnClickListener(新OnClickListener(){
公共无效的onClick(视图v){
新CreateMakeup()执行();
}
});
}
@覆盖
受保护的对话框onCreateDialog(INT ID){
开关(ID){
案例DATE_DIALOG_ID:
//设置日期选取器为当前日期
返回新DatePickerDialog(这一点,datePickerListener,
年,月,日);
案例DATE_DIALOG_ID_1:
//设置日期选取器为当前日期
返回新DatePickerDialog(这一点,datePickerListener1,
年,月,日);
案例TIME_DIALOG_ID:
//设置时间选择器为当前时间
返回新TimePickerDialog(这一点,
timePickerListener,小时,分钟,FALSE);
}
返回null;
}
私人DatePickerDialog.OnDateSetListener datePickerListener =新DatePickerDialog.OnDateSetListener(){
//当关闭对话框,如下方法将被调用。
公共无效onDateSet(DatePicker的观点,诠释selectedYear,
INT selectedMonth,诠释selectedDay){
年= selectedYear;
月= selectedMonth;
天= selectedDay;
//设置选定的日期到的TextView
AbsentDate.setText(新的StringBuilder()。追加(月+ 1)
.append( - )。追加(天).append( - )。追加(年)
。附加( ));
absentdate = AbsentDate.toString();
}
};
私人DatePickerDialog.OnDateSetListener datePickerListener1 =新DatePickerDialog.OnDateSetListener(){
//当关闭对话框,如下方法将被调用。
公共无效onDateSet(DatePicker的观点,诠释selectedYear,
INT selectedMonth,诠释selectedDay){
年= selectedYear;
月= selectedMonth;
天= selectedDay;
//设置选定的日期到的TextView
MakeupDate.setText(新的StringBuilder()。追加(月+ 1)
.append( - )。追加(天).append( - )。追加(年)
。附加( ));
makeupdate = MakeupDate.toString();
}
};
私人TimePickerDialog.OnTimeSetListener timePickerListener =
新TimePickerDialog.OnTimeSetListener(){
公共无效onTimeSet(TimePicker观点,诠释selectedHour,
INT selectedMinute){
小时= selectedHour;
分钟= selectedMinute;
//将当前时间为timebutton
MakeupTime.setText(新的StringBuilder()。追加(垫(小时))
.append(:)。追加(PAD(分钟)));
makeuptime = MakeupTime.toString();
}
};
私有静态字符串垫(INT C){
如果(c取代; = 10)
返回将String.valueOf(C);
其他
回到0+将String.valueOf(C);
}
类CreateMakeup扩展的AsyncTask&LT;字符串,字符串,字符串&GT; {
布尔故障= FALSE;
私人字符串的结果;
@覆盖
在preExecute保护无效(){
super.on preExecute();
pDialog =新ProgressDialog(Makeup.this);
pDialog.setMessage(Submiting ......);
pDialog.setIndeterminate(假);
pDialog.setCancelable(真正的);
pDialog.show();
}
@覆盖
保护字符串doInBackground(字符串参数... args){
// TODO自动生成方法存根
//检查成功标签
诠释成功;
字符串名称= name.getText()的toString()。
字符串部=部门;
。字符串Trainee_id = trainee_id.getText()的toString();
字符串BATCH_ID = batch_id.getText()的toString()。
字符串Absent_date = absentdate;
字符串MODULE_NAME = module_name.getText()的toString()。
字符串Absentreason = reason.getText()的toString()。
字符串Makeup_date = makeupdate;
字符串Makeup_time = makeuptime;
字符串备注= remarks.getText()的toString()。
尝试 {
//大厦参数
名单&LT;的NameValuePair&GT; PARAMS =新的ArrayList&LT;的NameValuePair&GT;();
params.add(新BasicNameValuePair(姓名,名称));
params.add(新BasicNameValuePair(部,部门));
params.add(新BasicNameValuePair(trainee_id,Trainee_id));
params.add(新BasicNameValuePair(BATCH_ID,BATCH_ID));
params.add(新BasicNameValuePair(absentdate,Absent_date));
params.add(新BasicNameValuePair(MODULE_NAME,MODULE_NAME));
params.add(新BasicNameValuePair(理,Absentreason));
params.add(新BasicNameValuePair(makeupdate,Makeup_date));
params.add(新BasicNameValuePair(makeuptime,Makeup_time));
params.add(新BasicNameValuePair(备注,备注));
Log.d(!要求,出发);
JSONObject的JSON = jsonParser.makeHtt prequest(
Makeup_URL,POST,则params);
//异步JSON的成功标签
成功= json.getInt(TAG_SUCCESS);
如果(成功== 1){
Log.d(已提交,json.toString());
完();
返回json.getString(TAG_MESSAGE);
} 其他 {
Log.d(未提交!,json.getString(TAG_MESSAGE));
返回json.getString(TAG_MESSAGE);
}
}赶上(JSONException E){
e.printStackTrace();
}
返回null;
}
}
}
和我的PHP文件:
&LT; PHP
$响应=阵列();
//其中包括DB连接类
require_once __DIR__。 /db_connect.php;
//连接到数据库
$ DB =新DB_CONNECT();
//从产品表中的所有产品
如果(!空($ _ POST)){
//初始查询
$查询=INSERT INTO补(Trainnee_Name系,Trainnee_ID,BATCH_ID,Absent_Date,MODULE_NAME,Reason_For_Absent,Makeup_Date,Makeup_Time,备注)
VALUES(:Trainnee_Name,:部:Trainnee_ID,:BATCH_ID,:Absent_Date,:MODULE_NAME,:Reason_For_Absent,:Makeup_Date,:Makeup_Time,:备注);
//更新查询
$ query_params =阵列(
:Trainnee_Name'=&GT; $ _ POST ['名称'],
:系'=&GT; $ _ POST ['pepartment'],
:Trainnee_ID'=&GT; $ _ POST ['trainnee_id']
:BATCH_ID'=&GT; $ _ POST ['BATCH_ID']
:Absent_Date'=&GT; $ _ POST ['absentdate']
:MODULE_NAME'=&GT; $ _ POST ['MODULE_NAME']
:Reason_For_Absent'=&GT; $ _ POST ['理由']
:Makeup_Date'=&GT; $ _ POST ['Makeupdate']
:Makeup_Time'=&GT; $ _ POST ['Makeuptime']
:备注'=&GT; $ _ POST ['言论']
);
//执行查询
尝试 {
$语句= $ DB-&GT; prepare($查询);
$结果= $ stmt-&GT;执行($ query_params);
}
赶上(PDOException $前){
//为了测试,你可以使用一个模具和消息。
//模具(无法运行的问题:$ EX-&GT;的getMessage());
//或者只是使用这种使用这一个:
$响应[成功] = 0;
$响应[信息] =数据库错误无法添加后!;
死亡(json_en code($响应));
}
$响应[成功] = 1;
$响应[信息] =后添加成功!;
回声json_en code($响应);
}
?&GT;
JSONParser.java部分
公开的JSONObject makeHtt prequest(URL字符串,字符串的方法,
名单&LT;的NameValuePair&GT; PARAMS){
如果(方法==POST){
//请求方法是POST
// defaultHttpClient
DefaultHttpClient的HttpClient =新DefaultHttpClient();
HttpPost httpPost =新HttpPost(URL);
httpPost.setEntity(新UrlEn codedFormEntity(PARAMS));
HTT presponse HTT presponse = httpClient.execute(httpPost);
HttpEntity httpEntity = HTT presponse.getEntity();
是= httpEntity.getContent();
尝试 {
的BufferedReader读卡器=新的BufferedReader(新的InputStreamReader(
是,ISO-8859-1),8);
StringBuilder的SB =新的StringBuilder();
串线= NULL;
而((行= reader.readLine())!= NULL){
sb.append(行+\ N);
}
is.close();
JSON = sb.toString();
}赶上(例外五){
Log.e(缓冲区错误,转换的结果错误+ e.toString());
}
//尝试解析字符串到一个JSON对象
尝试 {
jObj =新的JSONObject(JSON);
}赶上(JSONException E){
Log.e(JSON解析器,错误分析数据+ e.toString());
}
//返回JSON字符串
返回jObj;
}
我觉得行的JSONObject JSON = jsonParser.makeHtt prequest(Makeup_URL,POST,则params);
返回无效的Json
。按照错误日志中的反应是&LT; BR&GT;
或开始与&LT; BR&GT;
。在分析这是越来越失败。这样一来你的JSON对象是空
。它给空指针异常
在 288行
。
请你检查为什么它不返回JSON。你必须要格外确保反应应该是JSON。
i have been trying to come up with a form where trainee can apply for makeup lessons and when they submit the data will be stored in a database. I am new to android programming and I am also using the php to connect to the database.
i have no idea where the codes went wrong
This is my error:
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
My Android Codes:
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;
}
}
}
and my php file:
<?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);
}
?>
Part of 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;
}
I think on line JSONObject json = jsonParser.makeHttpRequest(Makeup_URL, "POST", params);
returns invalid Json
. As per the error log the response is <br>
or starts with <br>
. Which is getting failed while parsing. As a result your json object is Null
. And it gives Null Pointer Exception
on Line 288
.
Will you please check why its not returning JSON. You will have to be extra sure that the response should be JSON.
这篇关于值小于,java.lang.String类型BR无法转换到的JSONObject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!