ArrayAdapter 从未使用过 ArrayList null 并且所有项目都出现在单行中

Posted

技术标签:

【中文标题】ArrayAdapter 从未使用过 ArrayList null 并且所有项目都出现在单行中【英文标题】:ArrayAdapter never used ArrayList null and all items appear in single row 【发布时间】:2015-10-09 15:26:32 【问题描述】:

我是 android 新手,我正在尝试使用数组适配器、运行方法和多线程创建列表视图。该列表将数组列表中的所有数据显示为一行。

我的 MainActivity 如下所示:

    public class MainActivity extends FragmentActivity implements OnClickListener

..
    ArrayList<StorylineData> storylineData;

    ArrayList<SummaryData> summary;

    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mSpinnerAPI = (Spinner) findViewById(R.id.spinnerAPI);
        mButtonSubmit = (Button) findViewById(R.id.buttonSubmit);
        mEditTextResponse = (ListView) findViewById(R.id.editResponse);
        mProgressRequest = (ProgressBar) findViewById(R.id.progressRequest);

        mButtonSubmit.setOnClickListener(this);

  ...

    @Override
    public void onClick(View v) 
        toggleProgress(true);
        switch (mSpinnerAPI.getSelectedItemPosition()) 
            case 0: // Authenticate
              ...
            case 4: // Get Summary Day
                MovesAPI.getSummary_SingleDay(summaryHandler, "20150418", null);//Date changed to "20150117"
                break;
          ...
            case 10: // Get Storyline Day
                MovesAPI.getStoryline_SingleDay(storylineHandler, "20150418", "20140714T073812Z", false);//Date changed to "20150418" "null changed to"20140714T073812Z"
                break;
          ...
                toggleProgress(false);
                break;
        

    

   ...

    private MovesHandler<ArrayList<StorylineData>> storylineHandler = new MovesHandler<ArrayList<StorylineData>>() 

        @Override
        public void onSuccess(ArrayList<StorylineData> result) 
            toggleProgress(false);
                 updateResponse(
                           "Date:\t" + result.get(0).getDate() + "\n"
                           + "-----------Activity 1 Summary--------\t" + "\n"
                           + "Activity:\t" + result.get(0).getActivity().toString() + "\n"//returns 1587 with .getCaloriesIdle()
                      ...
                           + "-----------Activity 2 Summary---------\t" + "\n"
                           + "Activity:\t" + result.get(0).getSummary().get(0).getActivity() + "\n"//returns 1587 with .getCaloriesIdle()
 ...


 + "-----------Segments---------\t" + "\n"
                           + "Type:\t" + result.get(0).getSegments().get(0).getType() + "\n"//returns 1587 with .getCaloriesIdle()

...
        

    public void updateResponse(final String message) 
        MainActivity.this.runOnUiThread(new Runnable() 

            @Override
            public void run() 
                mButtonSubmit.setText(message);

                StorylineAdapter adapter = new StorylineAdapter(MainActivity.this, R.layout.item_storyline, storylineData);
                mEditTextResponse.setAdapter(adapter);

            
        );
    

我的 ArrayAdapter 类如下所示:

public class StorylineAdapter extends ArrayAdapter<SummaryData>
    private Context context;
    private Runnable runnable;
private ArrayList<StorylineData> storylineData;

public StorylineAdapter(Context context, int resource, ArrayList<SummaryData> objects) 
    super(context, resource, objects);
    this.context = context;
    this.runnable = runnable;
    this.summary = objects;



@Override
public View getView(int position, View convertView, ViewGroup parent)

LayoutInflater inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.item_storyline, parent, false);

//Display in the TextView widget
SummaryData summary1 = summary.get(position);
TextView tv = (TextView) view.findViewById(R.id.textView1);
tv.setText(summary1.getActivity());

return view;


这是我的解析器类:

public class StorylineData extends ArrayList<StorylineData> 

...Getters/Setters...

/**
 * Parse a @link org.json.JSONObject from storyline @link org.json.JSONArray, then return the corresponding @link StorylineData object.
 *
 * @param jsonObject : the storyline JSON object received from server
 * @return corresponding @link StorylineData
 */
public static StorylineData parse(JSONObject jsonObject) throws JSONException 
    if (jsonObject != null) 

        StorylineData storylineData = new StorylineData();


        storylineData.date = jsonObject.optString("date");
        storylineData.caloriesIdle = jsonObject.optInt("caloriesIdle");
        storylineData.lastUpdate = jsonObject.optString("lastUpdate");
        storylineData.summary = new ArrayList<SummaryData>();
        storylineData.segments = new ArrayList<SegmentData>();



        /**Get the data associated with the array named summary **To get a specific JSONArray: Summary*/
        JSONArray summariesJsonArray = jsonObject.optJSONArray("summary");

        if (summariesJsonArray != null)
        for (int i = 0; i < summariesJsonArray.length(); i++) 


            /**each time through array will need to get a reference of current object*/
            JSONObject summaryJsonObject = summariesJsonArray.optJSONObject(i);

                    if (summaryJsonObject != null) 
                    /**===============Translate data from json to Java=================*/
                        /**Create a new OBJECT OF ARRAY STORYLINE/SUMMARY*/
                        ArrayList<SummaryData> summary = new ArrayList<SummaryData>(); // initialisation must be outside the loop
                        storylineData.setSummary(summary);

                        /**Get summary from json into java*/
                        summariesJsonArray.getJSONObject(i).getString("distance");

                        /**Get date from json into java*/
                        String date = summaryJsonObject.optString("date");
                        storylineData.setDate(date);

                        /**Get group from json into java*/
                        String group = summaryJsonObject.optString("group");//Get name using key e.g. date
                        storylineData.setGroup(group);

               ...


                        storylineData.summary.add(SummaryData.parse(summaryJsonObject));
                        Log.d("StorylineDataCls \t sJo", summaryJsonObject.toString() + "Log\n");
                        System.out.println("print distance" + summariesJsonArray.getJSONObject(i).getString("distance"));
                        System.out.println("print summary" + summaryJsonObject);


                
            

        JSONArray segmentsJsonArray = jsonObject.optJSONArray("segments");
        if (segmentsJsonArray != null) 

            for (int i = 0; i < segmentsJsonArray.length(); i++) 
                JSONObject segment = segmentsJsonArray.optJSONObject(i);

                if (segment != null) 

                    ArrayList<SegmentData> segments = new ArrayList<SegmentData>(); // initialisation must be outside the loop
                    storylineData.setSegments(segments);

                    String type = segment.optString("type");
                    storylineData.setType(type);

                  ...

                    storylineData.segments.add(SegmentData.parse(segment));


                    Log.d("StorylineDataCls \t sSo", segment.toString());

                
            
        
        return storylineData;
    
    return null;






我想知道项目出现在单行中的原因是否可能是因为布局文件中的问题?

主布局。

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout"
    android:layout_
    android:layout_>

<Spinner
        android:id="@+id/spinnerAPI"
        android:layout_
        android:layout_
        android:entries="@array/API_Names"
    android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true" />

<Button
    android:id="@+id/buttonSubmit"
    android:layout_
    android:layout_
    android:text="Get Data"
    android:layout_below="@+id/spinnerAPI"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true" />

<ProgressBar
    android:id="@+id/progressRequest"
    android:layout_
    android:layout_
    android:visibility="gone"
    android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true" />



<ListView
    android:layout_
    android:layout_
    android:id="@+id/editResponse"
    android:layout_below="@+id/spinnerAPI"
    android:layout_alignLeft="@+id/progressRequest"
    android:layout_alignStart="@+id/progressRequest" />


</RelativeLayout>

项目布局:

<?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_
        android:layout_>
        <TextView
            android:id="@+id/textView1"
            android:layout_
            android:layout_
            android:layout_marginLeft="10dp"
            android:layout_centerVertical="true"
            android:text="@string/flower_name_placeholder"
            android:textAppearance="?android:attr/textAppearanceLarge" />

    </RelativeLayout>

【问题讨论】:

您可以添加显示给您的列表的屏幕截图吗? 是的,添加屏幕截图以便更好地理解问题。 您确定它们是不同的行吗?如果您按下一个列表项,整个列表显示为已选中?也许边距没有显示,适配器代码似乎正确。 是的,如果我按下一个列表项,整个列表就会显示为选中状态。此外,数组适配器也从未使用过,因为如果我注释掉所有 ArrayAdapter 代码,所有项目仍会显示在一行中。 首先删除id 之前的+ 符号,无论您在哪里引用已经创建的idandroid:layout_below="@+id/spinnerAPI" 变为 android:layout_below="@id/spinnerAPI" 仅在第一次创建 id 时使用 @+id/ 【参考方案1】:

更改 MainActivity 以实现 View.OnClickListener:

public class MainActivity extends FragmentActivity implements View.OnClickListener 

删除了 ArrayAdapter 并将 updateResponse 方法替换为:

public void updateResponse(final String message) 
            runOnUiThread(new Runnable() 

                //MainActivity.this.runOnUiThread(new Runnable() 

            @Override
            public void run() 

                ListView mListView = (ListView) findViewById(R.id.list_view);

                String[] stringArray = message.split("\n");

                // This is the array adapter, it takes the context of the activity as a
                // first parameter, the type of list view as a second parameter and your
                // array as a third parameter.
                ArrayAdapter<String> adapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1, stringArray);
                mListView.setAdapter(adapter);
            
        );
    

【讨论】:

如果您自己的答案解决了您的问题,请将其标记为解决方案:)

以上是关于ArrayAdapter 从未使用过 ArrayList null 并且所有项目都出现在单行中的主要内容,如果未能解决你的问题,请参考以下文章

Nuxt 常量被赋值但从未使用过

我如何知道代码中的哪些部分从未使用过?

警告:值已定义但从未使用过;考虑用布尔测试替换

从未使用过捕获自我

onButtonClick 从未在源代码中使用过?

为啥我会收到“从未使用过的参数 [E0392]”?