如何在Android中以编程方式设置JSON对视图的响应?

时间:2014-08-14 06:54:59

标签: android json

我创建了一个应用程序,我从服务器获取数据。所以,我在我的代码中使用了JSON解析。我成功地从服务器解析了我的JSON。

其实我想提出一个问题和选项基础测验应用程序。所以,我的数据库中有五个条目名为question_id,question_title,选项1,选项2,选项3,选项4.我想在运行时显示所有这些小部件。

我正在获得JSON响应。但我正在显示我的数据。

这是我的QuizActivity文件

package com.aquib.quiz;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class QuizActivity extends Activity {

    // Progress Dialog
    private ProgressDialog pDialog;


    // Creating JSON Parser object
    JSONParser jParser = new JSONParser();

    // url to get all products list
    private static String url_all_products = "http://labs.kamkazi.com/quiz/quiz.php";

    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_PRODUCTS = "quiz";
    private static final String TAG_QUESTIONID = "question_id";
    private static final String TAG_QUESTIONTITLE = "question_title";
    private static final String TAG_OPTION1 = "option1";
    private static final String TAG_OPTION2 = "option2";
    private static final String TAG_OPTION3 = "option3";
    private static final String TAG_OPTION4 = "option4";

    // products JSONArray
    JSONArray products = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.list_item);

        // Loading products in Background Thread
        new LoadAllProducts().execute();

    }

    /**
     * Background Async Task to Load all product by making HTTP Request
     * */
    class LoadAllProducts extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(QuizActivity.this);
            pDialog.setMessage("Loading products. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        /**
         * getting All products from url
         * */
        protected String doInBackground(String... args) {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            // getting JSON string from URL
            JSONObject json = jParser.makeHttpRequest(url_all_products, "GET",
                    params);

            // Check your log cat for JSON reponse
            Log.d("All Products: ", json.toString());

            try {
                // Checking for SUCCESS TAG
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    // products found
                    // Getting Array of Products
                    products = json.getJSONArray(TAG_PRODUCTS);

                    // looping through All Products
                    for (int i = 0; i < products.length(); i++) {
                        JSONObject c = products.getJSONObject(i);

                        // Storing each json item in variable
                        String questionTitle = c.getString(TAG_QUESTIONTITLE);
                        String option1 = c.optString(TAG_OPTION1);
                        String option2 = c.optString(TAG_OPTION2);
                        String option3 = c.optString(TAG_OPTION3);
                        String option4 = c.optString(TAG_OPTION4);
                        String questionid = c.optString(TAG_QUESTIONID);

                        // creating new HashMap
                        HashMap<String, String> map = new HashMap<String, String>();

                        // adding each child node to HashMap key => value

                        map.put(TAG_QUESTIONID, questionid);
                        map.put(TAG_QUESTIONTITLE, questionTitle);
                        map.put(TAG_OPTION1, option1);
                        map.put(TAG_OPTION2, option2);
                        map.put(TAG_OPTION3, option3);
                        map.put(TAG_OPTION4, option4);

                    }
                } else {
                    Toast myToast = Toast.makeText(getApplicationContext(),
                            "No quiz found", Toast.LENGTH_SHORT);
                    myToast.show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after getting all products
            pDialog.dismiss();

            /**
             * Updating parsed JSON data into ListView
             * */
            LinearLayout myLayout = new LinearLayout(getBaseContext());
            myLayout.setOrientation(LinearLayout.VERTICAL);


            TextView myView = new TextView(getBaseContext());
            myView.setText(TAG_QUESTIONTITLE);
            myView.setPadding(5, 10, 0, 0);

            myLayout.addView(myView);

        }

    }
}

还请帮我以编程方式创建单选按钮。

1 个答案:

答案 0 :(得分:0)

尝试此操作以创建复选框

LinearLayout my_layout = (LinearLayout) v.findViewById(R.id.checkgroup);
for (int i = 0; i < Array_Count; i++) {
    TableRow row = new TableRow(getActivity());
    row.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
    checkBox = new CheckBox(getActivity());

    checkBox.setId(i);
    noofcheckbox++;
    checkBox.setText(ans[i]);
    checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
            name();
        }
    });
    row.addView(checkBox);
    my_layout.addView(row);
}

尝试这个动态添加单选按钮。 ans(包含选项的数组)

RadioGroup rg = (RadioGroup) v.findViewById(R.id.radioGroup1);
for (int i = 0; i < ans.length; i++) {
    RadioButton radiobutton = new RadioButton(getActivity());
    radiobutton.setText(ans[i]);
    radiobutton.setId(150 + i);
    rg.addView(radiobutton);
}