仅获取ListView中的Last Object名称

时间:2014-08-27 10:22:15

标签: android json

parsing这个 JSON

{
"technology" : [

{
"title" : "Android",
"images" : [
{
"name" : "Android - I"
},
{
"name" : "Android - II"
},
{
"name" : "Android - III"
}
]
}

]
}

我解析了technologyimages JSON数组,但每当我点击Android时只是在列表视图中获取最后一个对象名称,在这种情况下" Android - III" ?

所以我可能知道可能是什么原因......?

TechnologyActivity.java: -

    JSONObject jsonObject = new JSONObject(data);
    JSONArray techArray = jsonObject.getJSONArray("technology");
        for(int i=0; i<techArray.length(); i++)
        {
            JSONObject jObject = techArray.getJSONObject(i);
            Technology tech = new Technology();
            tech.setTitle(jObject.getString("title"));
            Log.d("technology-title:", jObject.getString("title"));

            JSONArray imagesArray = jObject.getJSONArray("images");
              for(int j=0; j<imagesArray.length(); j++)
              {
                JSONObject imagesObject = imagesArray.getJSONObject(j);
                SubTech images = new SubTech();
                images.setName(imagesObject.getString("name"));
                Log.d("technology-name", imagesObject.getString("name"));

                arrayListImages = new ArrayList<SubTech>();
                arrayListImages.add(images);
                }
            tech.setImages(arrayListImages);
            arrayList.add(tech);
        }

SubTechActivity.java: -

public class SubTechActivity extends Activity {

    ArrayList<Technology> arrayList;
    Technology tech;
    SubTechAdapter adapter;
    ArrayList<SubTech> arrayListSubTech;
    int currentPosition ;

    @SuppressWarnings("unchecked")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_technology);

        Bundle bundle = getIntent().getExtras();

        arrayList = (ArrayList<Technology>) bundle.getSerializable("data");
        currentPosition = bundle.getInt("current");

        tech = arrayList.get(currentPosition);

        arrayListSubTech = tech.getImages();

        ListView listview = (ListView)findViewById(R.id.list);
        adapter = new SubTechAdapter(SubTechActivity.this, R.layout.adapter_technology, arrayListSubTech);

        listview.setAdapter(adapter);

    }
}

1 个答案:

答案 0 :(得分:1)

这种情况正在发生,因为你每次都在for循环中创建一个arrayListImages = new ArrayList<SubTech>();的新实例,它应该只创建一次,并且在循环之外也是如此

    arrayListImages = new ArrayList<SubTech>();

    for(int j=0; j<imagesArray.length(); j++)
        {
            JSONObject imagesObject = imagesArray.getJSONObject(j);
            SubTech images = new SubTech();
            images.setName(imagesObject.getString("name"));
            Log.d("technology-name", imagesObject.getString("name"));

            arrayListImages.add(images);
        }