gpt4 book ai didi

java - 类型为 java.lang.String 的值
转载 作者:太空宇宙 更新时间:2023-11-03 12:25:13 24 4
gpt4 key购买 nike

我一直在努力想出一个表格,学员可以在其中申请化妆类(class),当他们提交数据时,数据将存储在数据库中。我是 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;

}

最佳答案

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

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

关于java - 类型为 java.lang.String 的值 <br 无法转换为 JSONObject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17997514/

24 4 0

Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com