谁能告诉我我的代码出了什么问题?我一直在尝试从返回 json 数组的 PHP 文件中检索数据。我的安卓应用程序崩溃了。
我的 PHP 代码
<?php
/*
Our "config.inc.php" file connects to database every time we include
or require
it within a php script. Since we want this script to add a new user
to our db,
we will be talking with our database, and therefore,
let's require the connection to happen:
*/
require("config.inc.php");
$query = "select * from view_examquestions where examid=5";
try{
$stmt = $db->prepare($query);
$result = $stmt->execute();
}catch (PDOException $e){
$response["success"] = 0;
$response["message"] = "Database Error!";
echo $e;
die(json_encode($response));
}
$rows = $stmt->fetchAll();
$num = rand(0, 4);
if ($rows) {
$response["success"] = 1;
$response["message"] = "Post Available!";
$response["posts"] = array();
$counter = 0;
foreach ($rows as $row) {
$post = array();
$post["questionid"] = $row["questionid"];
$post["description"] = $row["description"];
$post["questiontype"] = $row["questiontype"];
$post["weight"] = $row["weight"];
$post["examid"] = $row["examid"];
array_push($response["posts"], $post);
}
// echoing JSON response
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "There are no questions!!";
die(json_encode($response));
}
?>
这是我的 JSONParser 类:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(final String url) {
// Making HTTP request
try {
// Construct the client and the HTTP request.
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
// Execute the POST request and store the response locally.
HttpResponse httpResponse = httpClient.execute(httpPost);
// Extract data from the response.
HttpEntity httpEntity = httpResponse.getEntity();
// Open an inputStream with the data content.
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
// Create a BufferedReader to parse through the inputStream.
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
// Declare a string builder to help with the parsing.
StringBuilder sb = new StringBuilder();
// Declare a string to store the JSON object data in string form.
String line = null;
// Build the string until null.
while ((line = reader.readLine()) != null) {
sb.append(line + "'n");
}
// Close the input stream.
is.close();
// Convert the string builder data to an actual string.
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// Try to 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 the JSON Object.
return jObj;
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
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();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
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;
}
}`
这是我检索数据的活动代码:
public class ChooseOption extends Activity {
private Button mTakeExam;
private Button mPrevScore;
private TextView status;
private static final String READ_QUESTIONS_URL = "http://192.168.0.20:80/EMA/webservice/questions.php";
// JSON IDS:
private static final String TAG_QUESTIONID = "questionid";
private static final String TAG_DESCRIPTION = "description";
private static final String TAG_QUESTIONTYPE = "questiontype";
private static final String TAG_WEIGHT = "weight";
private static final String TAG_EXAMID = "examid";
private static final String TAG_POSTS = "posts";
private static final String TAG_SUCCESS= "success";
//private String done = "Questions loaded!";
private ProgressDialog pDialog;
private static JSONArray mQuestions = null;
public static ArrayList<Question> mQuestionList;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.chooseoption);
mTakeExam = (Button) findViewById(R.id.bTakeExam);
mPrevScore = (Button) findViewById(R.id.bPrevScore);
status = (TextView) findViewById(R.id.tSample);
mTakeExam.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
new LoadQuestions().execute();
}
});
}
private class LoadQuestions extends AsyncTask<String, String, String>
{
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pDialog = new ProgressDialog(ChooseOption.this);
pDialog.setMessage("Retrieving Questions");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
JSONParser jParser = new JSONParser();
//JSONObject json = jParser.getJSONFromUrl(READ_QUESTIONS_URL);
try {
JSONObject json = jParser.getJSONFromUrl(READ_QUESTIONS_URL);
mQuestions = json.getJSONArray(TAG_POSTS);
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
status.setText("Retrieved! :)");
}
for (int i = 0; i < mQuestions.length(); i++) {
JSONObject c = mQuestions.getJSONObject(i);
// gets the content of each tag
String questionid = c.getString(TAG_QUESTIONID);
String description = c.getString(TAG_DESCRIPTION);
String questiontype = c.getString(TAG_QUESTIONTYPE);
String weight = c.getString(TAG_WEIGHT);
String examid = c.getString(TAG_EXAMID);
Question ques = new Question();
ques.setDescription(description);
ques.setExamid(Integer.parseInt(examid));
ques.setQuestionid(Integer.parseInt(questionid));
ques.setQuestiontype(questiontype);
ques.setWeight(Integer.parseInt(weight));
mQuestionList.add(ques);
}
} catch (JSONException e) {
status.setText("No questions!");
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
pDialog.dismiss();
}
}
}
这是我的问题类:
public class Question {
private int questionid;
private String description;
private String questiontype;
private int weight;
private int examid;
public Question()
{
this.questionid = 0;
this.description = "";
this.questiontype = "";
this.weight = 0;
this.examid = 0;
}
public int getQuestionid() {
return questionid;
}
public void setQuestionid(int questionid) {
this.questionid = questionid;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getQuestiontype() {
return questiontype;
}
public void setQuestiontype(String questiontype) {
this.questiontype = questiontype;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
public int getExamid() {
return examid;
}
public void setExamid(int examid) {
this.examid = examid;
}
}
当我尝试运行我的问题.php文件时,我得到以下数据:
{"成功":1,"消息":"帖子可用!","帖子":[{"questionid":"1","description":"谁是生物学之父?","questiontype":"识别","权重":"2","examid":"5"},{"questionid":"2","description":"是你吗?","questiontype":"TF","weight":"1","examid":"5"},{"questionid":"3","description":"谁是iKon的领导者?","questiontype":"MC","weight":"2","examid":"5"},{"questionid":"7","description":"字母表的第二个字母是什么?"问题类型":"标识","权重":"2","examid":"5"},{"questionid":"8","description":"这个应用程序的名称是什么?","questiontype":"标识","权重":"3","examid":"5"}, {"questionid":"9","description":"你吃午饭了吗?","questiontype":"TF","weight":"2","examid":"5"}]}
您的崩溃是因为status.setText("Retrieved! :)");
,您只能在 UI 线程上调用它,例如在 onPostExecute()
中。你的mQuestions.length()
mQuestionList.add(ques)
得到NullPointException。所以代码应该是:
// FIX-1: init mQuestionList first.
public static ArrayList<Question> mQuestionList = new ArrayList<>();
// ********** //
private class LoadQuestions extends AsyncTask<String, String, String>
{
private int success = 0;
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Retrieving Questions");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
JSONParser jParser = new JSONParser();
//JSONObject json = jParser.getJSONFromUrl(READ_QUESTIONS_URL);
try {
JSONObject json = jParser.getJSONFromUrl(READ_QUESTIONS_URL);
// FIX-2: uncomment mQuestions line to avoid null point.
mQuestions = json.getJSONArray(TAG_POSTS);
success = json.getInt(TAG_SUCCESS);
for (int i = 0; i < mQuestions.length(); i++) {
JSONObject c = mQuestions.getJSONObject(i);
// gets the content of each tag
String questionid = c.getString(TAG_QUESTIONID);
String description = c.getString(TAG_DESCRIPTION);
String questiontype = c.getString(TAG_QUESTIONTYPE);
String weight = c.getString(TAG_WEIGHT);
String examid = c.getString(TAG_EXAMID);
Question ques = new Question();
ques.setDescription(description);
ques.setExamid(Integer.parseInt(examid));
ques.setQuestionid(Integer.parseInt(questionid));
ques.setQuestiontype(questiontype);
ques.setWeight(Integer.parseInt(weight));
mQuestionList.add(ques);
}
} catch (JSONException e) {
status.setText("No questions!");
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
// FIX-3: move setText to UI thread.
if (success == 1) {
status.setText("Retrieved! :)");
}
pDialog.dismiss();
}
}
并确保您在清单中具有互联网权限:
<uses-permission android:name="android.permission.INTERNET" />