【问题标题】:Parsing a string array from a JSON file into global variable, but when using it the array content is null将 JSON 文件中的字符串数组解析为全局变量,但使用时数组内容为空
【发布时间】:2019-08-30 18:15:18
【问题描述】:

我有一个包含不同字符串的 JSON 文件,我想创建一个替代对话框,但我的字符串数组不工作

我创建了一个私有字符串类别。在方法 getJobArray 中,我使用 for 循环解析字符串值到 String 类别。那里的 LogCat 输出告诉我数组被字符串值填充。但是,当我在 onCreateDialog 中使用类别字符串数组时,它告诉我这些值都是空的。我什至无法将长度打印到 LogCat

public class MultipleChoiceDialogFragment extends DialogFragment {

    private RequestQueue mRQ;
    private Context mContext;
    private RequestQueue mRequestQ;
    private static String TAG = "xd";
    private String[] category;


    public interface onMultiChoiceListener{
        void onPositiveClicked(String[] list,ArrayList<String> selectedItemList);
        void onNegativeButtonClicked();
    }

    onMultiChoiceListener mListener;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

        mRequestQ = Volley.newRequestQueue(context);
        getJobArray();

        try {
            mListener = (onMultiChoiceListener) context;
        }catch (Exception e){
            throw  new ClassCastException(getActivity() + "onMultiChoice not working error");
        }
    }



    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        final ArrayList<String> selectedItemList = new ArrayList<>();



        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());



        //not working don't understand why... here category is null
        final String[] list = category;

        builder.setTitle("Select one")
                .setMultiChoiceItems(list, null, new DialogInterface.OnMultiChoiceClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i, boolean b) {
                        if(b){
                            selectedItemList.add(list[i]);
                        }else{
                            selectedItemList.remove(list[i]);
                        }
                    }
                })
                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        mListener.onPositiveClicked(list,selectedItemList);

                    }
                })
                .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        mListener.onNegativeButtonClicked();
                    }
                });

        return builder.create();
    }



    private void getJobArray(){
        //todo here I can get array from json array

        String url = "http://api_staging.jab.poweredby.cnddts.at/mobile/metadata/categories?portal=1";
        JsonObjectRequest request = new JsonObjectRequest(com.android.volley.Request.Method.GET, url, null,
                new com.android.volley.Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {

                        try {
                            JSONArray jsonArray = response.getJSONArray("categories");

                            category = new String[jsonArray.length()];

                            Log.d(TAG, "onResponse: is getting array ready right now");
                            Log.d(TAG, "onResponse: jsonArray length" + jsonArray.length());
                            for(int i = 0; i < jsonArray.length(); i++){
                                JSONObject categories = jsonArray.getJSONObject(i);

                                category[i] = categories.getString("name");

                                Log.d(TAG, "onResponse: array input " + category[i]);

                            }


                        } catch (JSONException e) {
                            e.printStackTrace();
                            Log.d(TAG, "onResponse: catch caught...");
                        }

                    }
                }, new com.android.volley.Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        });

        mRequestQ.add(request);
    }
}

JSON 示例:

{ 
    "categories": [ 
    { 
        "uid": "1", 
        "name": "Arbeitsrecht/Sozialrecht" 
    },{ 
        "uid": "2", 
        "name": "Bankrecht/Kapitalmarktrecht"
    }
}

【问题讨论】:

  • 你能展示使用json的样本吗?
  • @KunLun 是的,我的 Json 有一小部分:{ "categories": [ { "uid": "1", "name": "Arbeitsrecht/Sozialrecht" }, { "uid" : "2", "name": "Bankrecht/Kapitalmarktrecht"
  • @KunLun 这是 LogCat 输出,当循环通过数组时,会正确生成... 2019-08-30 11:28:11.991 14065-14065/com.example.candidatisapp D/xd: onResponse: jsonArray length30 数组输入 Gesellschaftsrecht/Corporate/M&A 数组输入 Immaterialgüterrecht/Wettbewerbsrecht
  • 似乎是期望异步工作立即完成的经典案例。你应该先获取数据,等待它被获取,然后显示它。
  • @TimCastelijns 我怎样才能先获取?

标签: java android json checkbox android-alertdialog


【解决方案1】:

我可以看到这是因为API调用onAttach(Context context)方法。因此,当您调用 API 时,类别尚未初始化,onCreateDialog() 将具有 null 值,因为 API 调用发生在主线程之外,并且主线程不会等待 API 响应。

顺便说一句,在调用对话框时一直调用 API 并不是一个好主意。 API 调用应以最少的调用次数进行优化,以获得更好的应用程序性能。因此,一个好的解决方案是在可能在 Activity 或 Fragment 中调用的对话框之前调用 API。并且当调用对话框时,直接使用响应数据中的 json 值。

【讨论】:

  • 如果它满足您的要求,我希望它会是公认的答案。
【解决方案2】:
{ 
"categories": [ 
{ 
    "uid": "1", 
    "name": "Arbeitsrecht/Sozialrecht" 
},{ 
    "uid": "2", 
    "name": "Bankrecht/Kapitalmarktrecht"
}
}

这是您的示例,但这不是有效的 JSON 格式,您缺少“类别”数组的右方括号。

这是示例的正确 JSON 格式:

{
  "categories": [
    {
      "uid": "1",
      "name": "Arbeitsrecht/Sozialrecht"
    },
    {
      "uid": "2",
      "name": "Bankrecht/Kapitalmarktrecht"
    }
  ]
}

尝试从第二个字符串创建 JSONObject。

【讨论】:

  • 我只在最后展示了一个json文件的图片,它显然是关闭的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多