Кто-нибудь может сказать мне, что не так с моим кодом? Я пытался извлечь данные из файла PHP, который возвращает массив JSON. У меня вылетает андроид приложение.
Мой код 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;
}}
И когда я попытался запустить свой файл questions.php, я получил следующие данные:
{«success»: 1, «message»: «Post Available!», «posts»: [{«questionid»: «1», «description»: «Кто является отцом биологии?», «questiontype»: » Идентификация «,» weight «:» 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»: «Что такое вторая буква алфавита?», «Questiontype»: «Identification», «weight»: «2», «examid»: «5»}, {«questionid»: «8», «description»: «Как называется это приложение?», «Questiontype»: «Identification», «weight»: » 3″ , «examid»: «5»},
{«questionid»: «9», «description»: «Вы пообедали?», «questiontype»: «TF», «weight»: «2», «examid»: «5»}]}
Ваше падение потому что status.setText("Retrieved! :)");
Вы можете вызвать это только в потоке пользовательского интерфейса, например, в 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" />
Других решений пока нет …