Java 在 Android 中从 JSON 填充微调器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19922058/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 21:32:40  来源:igfitidea点击:

Populate the spinner from JSON in Android

javaandroidjson

提问by tazeenmulani

I have JSON data like this:

我有这样的 JSON 数据:

[{"id":"1",
"client_name":"Glasco Smith Klin",
"campaign_name":"Health Medicine Survay",
"question":"MODE OF COMPLAINT CAN BE GIVEN THROUGH __________________",
"option_A":"WRITTEN",
"option_B":"ORAL",
"option_C":"PHONE CALL",
"option_D":"ALL OF THE ABOVE",
"q_prefix":"GSKHMSQ"},

{"id":"2",
"client_name":"Glasco Smith Klin",
"campaign_name":"Health Medicine Survay",
"question":"ADDING NEW FIR CAN BE DONE FROM WHICH ROLE",
"option_A":"IO",
"option_B":"TRAFFIC",
"option_C":"SHO-CRIME",
"option_D":"ADMINISTRATOR",
"q_prefix":"GSKHMJD"}]

I want to retrieve all q_prefixcolumn into spinner. But in my spinner no data is displayed. When I run my app, I am getting an error: "Unable to start Activity" and Java.lang.NullPointerExceptionat this line: jsonArray = jSon.getJSONArray(TAG_CODE);.

我想将所有q_prefix列检索到微调器中。但是在我的微调器中没有显示数据。当我运行我的应用程序时,我收到一个错误:“无法启动活动”,Java.lang.NullPointerException在这一行:jsonArray = jSon.getJSONArray(TAG_CODE);

Here is my code:

这是我的代码:

public class SpinDemo extends Activity {

    private static String strUrl = "http://192.168.1.61/jyoti/android_app/all_questions.php";
    private static String TAG_ID = "id";
    private static String TAG_CODE = "q_prefix";
    JSONArray jsonArray = null;
    Spinner codeSpinner, spinner2;

    @SuppressWarnings("unused")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        codeSpinner = (Spinner) findViewById(R.id.spinner2);

        ArrayList<String> codeList = new ArrayList<String>();

        // creating instance of JSONPrser
        JSONParser jParser = new JSONParser();
        // getting JSON string from URL
        JSONObject jSon = jParser.getJSONFromUrl(strUrl);
        System.out.println("Hello ********************");

        try {
            // Getting Array of Code
            jsonArray = jSon.getJSONArray(TAG_CODE);
            final String[] items = new String[jsonArray.length()];
            // looping through All Contacts
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject c = jsonArray.getJSONObject(i);

                // Storing each json item in variable
                String strCode = c.getString(TAG_CODE);
                items[i] = c.getString(TAG_CODE);
                System.out.println("Hello events " + items);
            }

            ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                    android.R.layout.simple_spinner_item);
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            codeSpinner.setAdapter(adapter);
        } catch (JSONException je) {
            je.printStackTrace();

        }

    }

}

采纳答案by Mohammed Saleem

You can Check the following code to parse an json data with spinner in android App:

您可以检查以下代码以在 android 应用程序中使用微调器解析 json 数据:

public class ParseJsonAndroidExample extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_parse_json_android_example);


    final Spinner output = (Spinner) findViewById(R.id.output);
    final Button bparsejson      = (Button) findViewById(R.id.bparsejson);
    String OutputData ;
    ArrayList<String> outputDataList  = new ArrayList<String>();


    /************  Static JSON data ***********/
    final String strJson = "{ "Android" :[{"id":"1",
                                      "client_name":"Glasco Smith Klin",
                                      "campaign_name":"Health Medicine Survay",
                                      "question":"MODE OF COMPLAINT CAN BE GIVEN THROUGH __________________",
                                        "option_A":"WRITTEN",
                                         "option_B":"ORAL",
                                       "option_C":"PHONE CALL",
                                        "option_D":"ALL OF THE ABOVE",
                                        "q_prefix":"GSKHMSQ"},

                                         {"id":"2",
                                          "client_name":"Glasco Smith Klin",
                                           "campaign_name":"Health Medicine Survay",
                                           "question":"ADDING NEW FIR CAN BE DONE FROM WHICH ROLE",
                                            "option_A":"IO",
                                             "option_B":"TRAFFIC",
                                             "option_C":"SHO-CRIME",
                                             "option_D":"ADMINISTRATOR",
                                              "q_prefix":"GSKHMJD"}] }";


    /******** Listener for button click ********/
    bparsejson.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {

           String OutputData = "";
           JSONObject jsonResponse;

           try {

                /****** Creates a new JSONObject with name/value mappings from the JSON string. ********/
                jsonResponse = new JSONObject(strJson);

                /***** Returns the value mapped by name if it exists and is a JSONArray. ***/
                /*******  Returns null otherwise.  *******/
                JSONArray jsonMainNode = jsonResponse.optJSONArray("Android");

                /*********** Process each JSON Node ************/

                int lengthJsonArr = jsonMainNode.length();  

                for(int i=0; i < lengthJsonArr; i++) 
                {
                    /****** Get Object for each JSON node.***********/
                    JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);

                    /******* Fetch node values **********/
                    int id        = Integer.parseInt(jsonChildNode.optString("id").toString());
                    String client_name   = jsonChildNode.optString("client_name").toString();
                    String campaign_name=    jsonChildNode.optString("campaign_name").toString();
                   String question= jsonChildNode.optString("question").toString();
                   String option_A= jsonChildNode.optString("option_A").toString();

String option_B= jsonChildNode.optString("option_B").toString();
String option_C= jsonChildNode.optString("option_C").toString();
 String option_D= jsonChildNode.optString("option_D").toString(); 
String q_prefix= jsonChildNode.optString("q_prefix").toString();


                    OutputData += "Node : \n\n     "+ id +" | "
                                                        + client_name+" | "
                                                        + campaign_name+" 
                                                         + question+" | "
                                                         + option_A+" | "
                                                         + option_B+" | "
                                                         + option_C+" | "
                                                          + option_D+" | "
                                                          + q_prefix+" | " +"\n\n ";




               }
              outputDataList.add(OutputData);


                /************ Show Output on Spinner **********/

       ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_spinner_item ,outputDataList  );
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    codeSpinner.setAdapter(adapter);



            } catch (JSONException e) {

                e.printStackTrace();
            }

        }
    });
 }
}

回答by SHASHIDHAR MANCHUKONDA

 JSONObject jSon = jParser.getJSONFromUrl(strUrl);
your response is JsonArray not  JsonObject
if Response starts with [ it is an jsonarray
if starts with { it is an jsonObject.

Use

  public static int SDK_INT = android.os.Build.VERSION.SDK_INT;

 if (SDK_INT >= 10) {
        ThreadPolicy tp = ThreadPolicy.LAX;
        StrictMode.setThreadPolicy(tp);
        }

before parsing Json

在解析 Json 之前

or else use AsyncTask to get the Response

或者使用 AsyncTask 来获取响应

http://developer.android.com/reference/android/os/AsyncTask.html

http://developer.android.com/reference/android/os/AsyncTask.html

回答by ρяσ?ρ?я K

you are not passing itemsArray to ArrayAdapterconstructor do it as:

您没有将itemsArray传递给ArrayAdapter构造函数,请执行以下操作:

 ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                    android.R.layout.simple_spinner_item,items);

and instead of making webservice request from main thread use AsyncTaskfor doing operation in background and update UI elements when operation complete

而不是从主线程发出 webservice 请求,使用AsyncTask在后台执行操作并在操作完成时更新 UI 元素

回答by Paresh Mayani

Issues and solution:

问题及解决方法:

  1. Check your logcat, it should be having NetworkOnMainThreadException, reason being is you are calling web API directly on main thread, starting from Honeycomb its not possible to implement long running task on Main UI Thread directly.

    Solution is to implement threading mechanism, you can implement AsyncTaskin android which is known as Painless Threadingin Android.

  2. There are issues in JSON parsing, you need to learn and understand JSON Parsingproperly.

  1. 检查你的 logcat,它应该有NetworkOnMainThreadException,原因是你直接在主线程上调用 web API,从 Honeycomb 开始它不可能直接在主 UI 线程上实现长时间运行的任务。

    解决方案是实现线程机制,你可以在android中实现AsyncTask,在Android中称为Painless Threading

  2. JSON解析存在问题,需要正确学习和理解JSON解析

Issue example:

问题示例:

 JSONObject jSon = jParser.getJSONFromUrl(strUrl);
        System.out.println("Hello ********************");

        try {
            // Getting Array of Code
            jsonArray = jSon.getJSONArray(TAG_CODE);

             .....
             .....

By looking at response given in question, I can say you are getting JSONArray directly in response instead of JSONObject.

通过查看有问题的响应,我可以说您是直接在响应中获取 JSONArray 而不是 JSONObject。

2nd mistake in JSON Parsing is you are trying to getJSONArray(TAG_CODE) which is not required as you are already having JSONArray in response, you can just iterate through objects and can fetch whatever values you want.

JSON 解析中的第二个错误是您正在尝试 getJSONArray(TAG_CODE) 这不是必需的,因为您已经有了 JSONArray 作为响应,您可以遍历对象并获取您想要的任何值。

回答by Amit Gupta

Try like this, Use AsyncTaskto Network Operation

试试这样,AsyncTask用于网络操作

"Unable to start Activity" and Java.lang.NullPointerExceptionat the line of jsonArray = jSon.getJSONArray(TAG_CODE);

“无法启动活动”并Java.lang.NullPointerException在 j 行sonArray = jSon.getJSONArray(TAG_CODE);

First use this code for Parsing

首先使用此代码进行解析

jsonArray = new JSONArray(jSon.toString());
        final String[] items = new String[jsonArray.length()];
        // looping through All Contacts
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject c = jsonArray.getJSONObject(i);

            // Storing each json item in variable
            String strCode = c.getString(TAG_CODE);
            items[i] = c.getString(TAG_CODE);
            System.out.println("Hello events " + items);
        }

Then use item to ArrayAdapter

然后使用 item 来 ArrayAdapter

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                    android.R.layout.simple_spinner_item,items);