Arraylist在另一个函数中变空

时间:2017-06-27 10:31:51

标签: android arraylist

我有一个自定义的ArrayList,我正在添加从php / mysql数据库中检索的内容。现在当我添加那些东西时,arraylist被正确填充但是当我尝试在另一个函数中使用arraylist时,它会变为空。有什么问题?

public class SetTask extends Fragment {

ListView lv_task_chooser;
ArrayList<SetTaskModel> setTaskModelArrayList;
private SetTaskAdapter setTaskAdapter;
ArrayAdapter<String> scAdapter;
String url, category;
RequestQueue queue_fetch;
ConnectivityManager connMgr;
NetworkInfo networkInfo;
Context ctx;
LinearLayout taskLayout;
private String[] array;
private int[] sub_cat_id;
JSONArray jsonArray;

public SetTask() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View rootView = inflater.inflate(R.layout.fragment_set_task, container, false);

    ctx = getContext();

    lv_task_chooser = (ListView)rootView.findViewById(R.id.lv_task_chooser);
    taskLayout = (LinearLayout)rootView.findViewById(R.id.taskLayout);

    queue_fetch = Volley.newRequestQueue(ctx);

    setTaskModelArrayList = new ArrayList<>();

    fetchDB();

    Log.i("pointafterfetch", "reached");
    Log.i("numberofarrayentries", String.valueOf(setTaskModelArrayList.size()));

    for (int i = 0; i < setTaskModelArrayList.size(); i++){
        Log.i("arrayentriesfetch", setTaskModelArrayList.get(i).toString());
    }

    setTaskAdapter = new SetTaskAdapter(setTaskModelArrayList, ctx);
    lv_task_chooser.setAdapter(setTaskAdapter);

    lv_task_chooser.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            populateSpinner(position);
        }
    });

    return rootView;

}

private void fetchDB(){

    url = "http://nmstech.in/coach/categorys.php";

    connMgr = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
    networkInfo = connMgr.getActiveNetworkInfo();

    if (!(networkInfo != null && networkInfo.isConnected())) {
        final AlertDialog.Builder builder1 = new AlertDialog.Builder(ctx);
        builder1.setTitle(getString(R.string.network_no_t));
        builder1.setMessage(getString(R.string.network_no_m));
        builder1.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        builder1.create().show();
    }

    else{

        StringRequest strreq_fetch = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String Response) {
                        try {
                            jsonArray = new JSONArray(Response);

                            for(int i = 0; i < jsonArray.length(); i++){

                                setTaskModelArrayList.add(new SetTaskModel(jsonArray.getJSONObject(i)
                                        .getString("cat_name")));
                                Log.i("arraylistentries", setTaskModelArrayList.get(i).getCategory());
                                Log.i("noentries", String.valueOf(setTaskModelArrayList.size()));
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError e) {
                e.printStackTrace();
            }
        });

        Log.i("pointnotesfetch", "reached");
        queue_fetch.add(strreq_fetch);
    }
}

private void populateSpinner(int position){

    category = lv_task_chooser.getItemAtPosition(position).toString();

    final AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
    builder.setTitle("Subtopics");

    connMgr = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
    networkInfo = connMgr.getActiveNetworkInfo();

    try {
        for (int i = 0; i < jsonArray.getJSONArray(position).length(); i++){

            array[i] = jsonArray.getJSONArray(position).getJSONObject(i).getString("sub_cat_name");
            sub_cat_id[i] = jsonArray.getJSONArray(position).getJSONObject(i).getInt("sub_cat_id");
        }
    }
    catch (Exception e){
        e.printStackTrace();
    }

    builder.setItems(array, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();

            Bundle cat_args = new Bundle();
            cat_args.putInt("sub_cat_id", sub_cat_id[which]);
            cat_args.putString("sub_cat", array[which]);

            Fragment fragment = new Exercise();
            FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
            fragment.setArguments(cat_args);
            fragmentTransaction.replace(R.id.mainFrame, fragment);
            fragmentTransaction.commit();
        }
    });

    builder.show();
}
}

这是我的Android监视器输出: This is my Android monitor output:

3 个答案:

答案 0 :(得分:0)

在fecthDb获得响应之前,你要经过'setTaskModelArrayList'。

只有在收到回复后才能处理和检查数据。

例如,

@Override
public void onResponse(String Response) {
     /* your code */
     onListChanged();
}

public void onListChanged() {
         Log.i("numberofarrayentries", String.valueOf(setTaskModelArrayList.size()));

for (int i = 0; i < setTaskModelArrayList.size(); i++){
    Log.i("arrayentriesfetch", setTaskModelArrayList.get(i).toString());
}
}

答案 1 :(得分:0)

onResponse方法是异步调用的。 fetchDB函数在得到响应之前返回,因此arraylist为空,当你尝试打印它的大小时你会得到0。一旦基础列表发生了变化,就应该通知了。

setTaskAdapter.notigyDataSetChanged();

答案 2 :(得分:0)

截击请求的执行是异步的。因此,当您尝试打印时,基本上您的ArrayList是空的。

你能做的是做一个功能

void func()
{
   Log.i("pointafterfetch", "reached");
   Log.i("numberofarrayentries",String.valueOf(setTaskModelArrayList.size()));
   for (int i = 0; i < setTaskModelArrayList.size(); i++)
   {
        Log.i("arrayentriesfetch", setTaskModelArrayList.get(i).toString());
   }
   setTaskAdapter = new SetTaskAdapter(setTaskModelArrayList, ctx);
   lv_task_chooser.setAdapter(setTaskAdapter);
}

并在您fetchDb()

中调用此方法
private void fetchDB()
{
.
.

else
{
    StringRequest strreq_fetch = new StringRequest(Request.Method.GET, url,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String Response) {
                    try {
                        jsonArray = new JSONArray(Response);

                        for(int i = 0; i < jsonArray.length(); i++)
                        {
                            setTaskModelArrayList.add(newSetTaskModel(jsonArray.getJSONObject(i).getString("cat_name")));
                        }
                        func();
                  } catch (Exception e) {
                        e.printStackTrace();
                    }

}

反过来,您的oncreate将是:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View rootView = inflater.inflate(R.layout.fragment_set_task, container, false);

    ctx = getContext();

    lv_task_chooser = (ListView)rootView.findViewById(R.id.lv_task_chooser);
    taskLayout = (LinearLayout)rootView.findViewById(R.id.taskLayout);

    queue_fetch = Volley.newRequestQueue(ctx);

    setTaskModelArrayList = new ArrayList<>();

    fetchDB();

    lv_task_chooser.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            populateSpinner(position);
        }
    });

    return rootView;

}