dongxiangxie8181 2015-04-08 08:36
浏览 55

= JSON数组到Arraylist(Android)

Can anybody tell me what's wrong with my code? I've been trying to retrieve a data from a PHP file that returns a json array. My android application crashes.

My PHP Code

<?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));
 }

?>

Here is my JSONParser Class:

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 + "
");
        }

        // 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 + "
");
        }
        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;

}

}`

Here is my Activity Code that Retrieves The Data:

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();

    }

}

}

Here is my Question Class:

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;
}



}

And when I tried to run my questions.php file, I get the following data:

{"success":1,"message":"Post Available!","posts":[{"questionid":"1","description":"Who is the father of Biology?","questiontype":"Identification","weight":"2","examid":"5"},{"questionid":"2","description":"Is it you?","questiontype":"TF","weight":"1","examid":"5"},{"questionid":"3","description":"Who is the leader of iKon?","questiontype":"MC","weight":"2","examid":"5"},{"questionid":"7","description":"What is the second letter of the alphabet?","questiontype":"Identification","weight":"2","examid":"5"},{"questionid":"8","description":"What is the name of this application?","questiontype":"Identification","weight":"3","examid":"5"}, {"questionid":"9","description":"Did you take your lunch?","questiontype":"TF","weight":"2","examid":"5"}]}

  • 写回答

1条回答 默认 最新

  • dreamfly2016 2015-04-08 09:20
    关注

    Your crash is because status.setText("Retrieved! :)");, you can only call this on UI thread, for example in onPostExecute(). And your mQuestions.length() mQuestionList.add(ques) get NullPointException. So the code should be:

    // 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();
    
        }
    
    }
    

    And be sure you have the internet permission in manifest:

    <uses-permission android:name="android.permission.INTERNET" />

    评论

报告相同问题?

悬赏问题

  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法