【问题标题】:Looping through a JSONArray to convert Strings into Objects循环通过 JSONArray 将字符串转换为对象
【发布时间】:2016-03-01 13:03:28
【问题描述】:

我目前有一个方法,它从用户输入创建 URL,发送 HTTP 请求以获取 JSONArray,然后将 JSONArray 转换为 ArrayList。由于某种原因,旨在添加每个 JSONObject 之一的循环仅复制相同的一个 10 次,尽管循环计数器没有告诉它这样做。显然我遗漏了一些东西,但这里是下面的代码:

主活动

public ArrayList<Eatery> fillArray(String url) {


    String line;
    Eatery eatery = new Eatery("null","null","null","null","null",
            "null","null","null","null","null");
    ArrayList<Eatery> eateryList = new ArrayList<>();

    if (getConnection() == true) {
        try {

            URL urlFinal = createURL(url);
            HttpURLConnection postcodeConnection = (HttpURLConnection) urlFinal.openConnection();
            InputStreamReader isr = new InputStreamReader(postcodeConnection.getInputStream());
            BufferedReader bf = new BufferedReader(isr);

            while ((line = bf.readLine()) != null) {
                JSONArray ja = new JSONArray(line);
                for (int i = 0; i < ja.length(); i++) {

                    JSONObject jo = ja.getJSONObject(i);
                    String id = jo.getString("id");
                    String businessName = jo.getString("BusinessName");
                    String addressLine1 = jo.getString("AddressLine1");
                    String addressLine2 = jo.getString("AddressLine2");
                    String addressLine3 = jo.getString("AddressLine3");
                    String postcode = jo.getString("PostCode");
                    String ratingValue = jo.getString("RatingValue");
                    String ratingDate = jo.getString("RatingDate");
                    String lati = jo.getString("Latitude");
                    String longi = jo.getString("Longitude");
                    eatery.setId(id);
                    eatery.setBusinessName(businessName);
                    eatery.setAddressLine1(addressLine1);
                    eatery.setAddressLine2(addressLine2);
                    eatery.setAddressLine3(addressLine3);
                    eatery.setPostcode(postcode);
                    eatery.setRatingValue(ratingValue);
                    eatery.setRatingDate(ratingDate);
                    eatery.setLati(lati);
                    eatery.setLati(longi);
                    eateryList.add(eatery);
                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }catch (IndexOutOfBoundsException e){
            Toast nameToast = Toast.makeText(getApplicationContext(), "Invalid search", Toast.LENGTH_LONG);
            nameToast.show();
        }
    } else {
        Toast nameToast = Toast.makeText(getApplicationContext(), "Error: No Active Connection", Toast.LENGTH_LONG);
        nameToast.show();
    }

    return (eateryList);
}

内部方法:

public boolean getConnection(){

    conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    networkInfo = conMgr.getActiveNetworkInfo();
    boolean connected;
    if(networkInfo != null && networkInfo.isConnected())
    {
        connected = true;
    }
    else
    {
        connected = false;
    }
    return connected;
}

public URL createURL(String searchType) {

    String URLstart = "http://sandbox.kriswelsh.com/hygieneapi/hygiene.php?op=";
    searchType = searchType.replace(" ", "%20");
    String finalURL = URLstart.concat(searchType);
    URL nameURL = null;
    try {
        nameURL = new URL(finalURL);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
    return nameURL;
}

以上内容在 ActivityMain 中,当前从一个片段调用,该片段从 EditText 框中获取用户输入,将其添加到 fillArray 方法,然后将结果返回到在片段上实例化的另一个 ArrayList。

片段代码如下:

public class NameFragment extends Fragment {

EditText enterName;
Button searchNameButton;
TableLayout nameTableLayout;
TextView testTextView, tv;
TableRow tr;
ArrayList<Eatery> nameEateryList;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.name_search_fragment, container, false);

    enterName = (EditText) rootView.findViewById(R.id.enterNameText);
    searchNameButton = (Button)rootView.findViewById(R.id.searchNameButton);
    testTextView = (TextView)rootView.findViewById(R.id.testTextView);
    nameTableLayout = (TableLayout)rootView.findViewById(R.id.NameTableLayout);

    searchNameButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            String nameSearch = enterName.getText().toString().trim();
            String nameURLKey = "s_name&name=";
            nameURLKey = nameURLKey.concat(nameSearch);

            //Grab ArrayList
            nameEateryList = ((MainActivity)getActivity()).fillArray(nameURLKey);

            for(int i = 0; i < nameEateryList.size(); i++) {

                tv = new TextView(getActivity().getApplicationContext());
                tr = new TableRow(getActivity().getApplicationContext());

                //Create Table Counter
                int turn = nameTableLayout.getChildCount();
                turn += 1;
                String turnString = turn + "";

                //Add TextView
                tv.setText(nameEateryList.get(i).eateryToString());
                tv.setPadding(15, 15, 15, 15);
                tr.setPadding(5,5,5,5);
                tv.setBackgroundColor(Color.parseColor("#557788"));
                tv.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_START);
                tr.addView(tv);
                nameTableLayout.addView(tr);
            }
        }
    });
    return rootView;
   }

由于某种原因,当循环遍历 ArrayList 并将结果复制到我的 Fragment 中时,所有结果都是相同的。代码运行并填充了 ArrayList,但似乎无法循环遍历 ArrayList。一直坚持这一点,但我无法弄清楚究竟是什么导致 ArrayList 重复复制同一个对象,而不是循环遍历所有结果。我希望这是有道理的。如果需要任何进一步的信息,那么我当然可以提供更多代码。这是一个非常具体的问题,我无法确定另一个有这个确切问题的线程,如果这个答案存在于其他地方,我深表歉意。

【问题讨论】:

    标签: android arrays loops arraylist fragment


    【解决方案1】:

    为 for 循环的每次迭代创建一个新的 Eatery 对象,如下所示:

    for (int i = 0; i < ja.length(); i++) {
        Eatery eatery = new Eatery("null","null","null","null","null",
            "null","null","null","null","null");
    
        JSONObject jo = ja.getJSONObject(i);
        String id = jo.getString("id");
        String businessName = jo.getString("BusinessName");
        String addressLine1 = jo.getString("AddressLine1");
        String addressLine2 = jo.getString("AddressLine2");
        String addressLine3 = jo.getString("AddressLine3");
        String postcode = jo.getString("PostCode");
        String ratingValue = jo.getString("RatingValue");
        String ratingDate = jo.getString("RatingDate");
        String lati = jo.getString("Latitude");
        String longi = jo.getString("Longitude");
        eatery.setId(id);
        eatery.setBusinessName(businessName);
        eatery.setAddressLine1(addressLine1);
        eatery.setAddressLine2(addressLine2);
        eatery.setAddressLine3(addressLine3);
        eatery.setPostcode(postcode);
        eatery.setRatingValue(ratingValue);
        eatery.setRatingDate(ratingDate);
        eatery.setLati(lati);
        eatery.setLati(longi);
        eateryList.add(eatery);
    }
    

    您面临的问题是,您在每次循环迭代时只向列表中添加一个对象,并且该对象的值将是您为 Eatery 对象设置的最后一个值。

    希望这会有所帮助!

    【讨论】:

    • 谢谢!我敢肯定,由于没有意识到问题,我遇到了一个彻头彻尾的白痴,但昨天我一直在寻找解决方案几个小时,但无济于事。非常简单的解决方案,非常感谢您的回复。祝你有美好的一天!
    猜你喜欢
    • 2015-11-10
    • 2015-02-16
    • 2017-08-11
    • 2023-03-21
    • 2013-03-30
    • 2011-09-21
    • 2012-04-28
    • 2017-03-14
    • 2013-05-08
    相关资源
    最近更新 更多