为什么它为数组的元素为空?

时间:2012-07-29 11:43:29

标签: java android

我的活动有以下变量

static CharSequence[] categories;

我正在使用JSON

接收数据
try
{
    Thread cThread = new Thread(new getStringContent("http://192.168.0.101/curltest/getcategories.php"));
    cThread.start();            
}
catch(Exception ex)
{
    Log.i("YGo", ex.toString());
}

public class getStringContent implements Runnable {
        String suri;
        public getStringContent(String uri)
        {
            suri = uri; 
        }
        @Override
        public void run() {         
            try {
                JSONArray jsonArray = new JSONArray(getPageContent(suri));
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONArray jsonSArray = jsonArray.getJSONArray(i);
                    categories = new CharSequence[jsonArray.length()];
                    categories[i] = jsonSArray.getString(0);
                    Log.i("YGo", categories[i].toString());
                }               
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                Log.e("YGo", e.toString());
            }
            dialog.dismiss();
        }       
    }

在GUI线程中,如果我点击按钮,我想显示收到的数据:

for(int i=0; i<categories.length; i++)
{
   Log.i("Ygo", String.valueOf(categories[i]));
   Log.i("Ygo", String.valueOf(selectedData[i]));
}
AlertDialog.Builder builder = new AlertDialog.Builder(PreferencesClass.this);
            builder.setTitle("Pick categories");

            builder.setMultiChoiceItems(categories, selectedData, onClickCatChooser);           
            builder.setPositiveButton("Ok", clickedOnClickCatOk);

            AlertDialog alert = builder.create();
            alert.show();

但是在categories变量中我有null,null,Data3,而不是Data1Data2我只有null。为什么呢?

2 个答案:

答案 0 :(得分:4)

该行

categories = new CharSequence[jsonArray.length()];

应该在for循环之外。您可以在循环中的每次迭代中重置数据,因此最后只剩下上一次操作的数据。

答案 1 :(得分:1)

可能是因为data1&amp; 2的路径未正确定义 try categories = new CharSequence [jsonArray.length()];外面的循环。