如何向ArrayList添加元素

时间:2013-04-29 15:57:07

标签: android for-loop arraylist

我正在尝试将从数据库检索到的几个事件添加到ArrayList,以便填充列表视图。我已经创建了一个事件类,并且我已经设置了所有方法。

EventsFunctions eventsFunctions;
JSONParser jParser = new JSONParser();
JSONArray events = null;
ArrayList<Torneo> tornei;

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

    tornei= new ArrayList<Torneo>();
    LoadAllEvents eventsLoader = new LoadAllEvents();
    [...]
 }

/**
 * Background Async Task to Load all product by making HTTP Request
 * */
public class LoadAllEvents extends AsyncTask<String, Integer, JSONObject> 
{
    LoadAllEvents()
    {
        eventsFunctions = new EventsFunctions();
    }

    @Override
    protected void onPreExecute() 
    {
      [...]
    }

    protected JSONObject doInBackground(String... params) 
        {   
            String a = "code1";
            // getting JSON string from URL
            return eventsFunctions.eventList(a);
        }

        protected void onPostExecute(JSONObject json) 
        {

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

            try 
            {
                // Checking for SUCCESS TAG
                String success = json.getString(TAG_SUCCESS);
                if (success != null) 
                {
                    if (Integer.parseInt(json.getString(TAG_SUCCESS)) != 0)
                    {
                        // events found
                        // Getting Array of Events
                       events = json.getJSONArray(TAG_EVENTS);
                       Log.e("AllEventsActivity"," "+ Integer.toString(events.length())+ " events received from the database");

这是代码的相关部分

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

                                // Storing each json item in variable
                                String id   = c.getString(TAG_UID);
                                String name     = c.getString(TAG_NAME);


                                Torneo torneo = new Torneo();
                                torneo.setName(name);

                                Log.e("AllEventsActivity", "Tournament name: " + torneo.getName());

                                tornei.add(i,torneo); //Or just tornei.add(torneo);


                            }

                            for (int j=0; j<tornei.size() ;j++ )
                            {
                                Log.e("AllEvents Reporter", "Torneo numero: "+ j + " Nome: " + tornei.get(j).getName());
                            }

                    }

AsyncTask实现的结束:

    else if (Integer.parseInt(json.getString(TAG_SUCCESS)) != 0)
            {
                Log.d("Events Report: ", "NO events scheduled");

            }
        }
    } catch (JSONException e) 
    {
        e.printStackTrace();
    }
    // updating UI from Background Thread
    [...]

}

这是输出:

E/AllEventsActivity(10785):  4 events received from the database
E/AllEventsActivity(10785): Tournament name: One way
E/AllEventsActivity(10785): Tournament name: Super 5
E/AllEventsActivity(10785): Tournament name: Main Event 2013
E/AllEventsActivity(10785): Tournament name: First step
E/AllEvents Reporter(10785): Torneo numero: 0 Nome: First step
E/AllEvents Reporter(10785): Torneo numero: 1 Nome: First step
E/AllEvents Reporter(10785): Torneo numero: 2 Nome: First step
E/AllEvents Reporter(10785): Torneo numero: 3 Nome: First step
I/MemoryCache(10785): MemoryCache will use up to 16.0MB
D/dalvikvm(10785): GC_FOR_ALLOC freed 153K, 7% free 12544K/13383K, paused 22ms, total 22ms
I/dalvikvm-heap(10785): Grow heap (frag case) to 12.958MB for 262160-byte allocation

似乎存储在Arraylist中的唯一事件是for循环中添加的最后一个元素。

日志应该是这样的:

E/AllEvents Reporter(10785): Torneo numero: 0 Nome: One way
E/AllEvents Reporter(10785): Torneo numero: 1 Nome: Super 5
E/AllEvents Reporter(10785): Torneo numero: 2 Nome: Main Event 2013
E/AllEvents Reporter(10785): Torneo numero: 3 Nome: First step

这是解析的json字符串:

  

{ “错误”:0, “成功”:1, “事件”:[{ “UID”: “Event_51796139b113d8.73834778”, “ID”: “58”, “姓名”: “一},{” UID “:” Event_5179625c988f60.49787125" , “ID”: “59”, “名”:“超级   5 “},{” UID “:” Event_517969f6ac59d3.04395373" , “ID”: “60”, “姓名”:“主   事件   2013" ,},{ “UID”: “Event_517ab1f1bb91c0.03505404”, “ID”: “61”, “姓名”,“首先   step“}],”tag“:”listimage“}

你有什么建议吗?

1 个答案:

答案 0 :(得分:0)

您是否复制并粘贴了代码,或者重新输入了代码?看起来您的日志输出可能是因为您在上面显示的行:

  

Log.e(&#34; AllEvents Reporter&#34;,&#34; Torneo numero:&#34; + j +&#34; Nome:&#34; + tornei.get(j).getName ());

实际上是

  

Log.e(&#34; AllEvents Reporter&#34;,&#34; Torneo numero:&#34; + j +&#34; Nome:&#34; + tornei.get(i).getName ());

其中tornei.get(i).getName()只会输出数据集中的最后一个,这就是您所看到的,但这只是猜测。正如比尔所说,你的代码似乎很好