如何使用onclickListener和MainActivity setAdapter扩展FragmenActivity

时间:2015-07-25 17:51:28

标签: android listview android-arrayadapter onclicklistener

我是android的新手,我正在尝试使用数组适配器,运行方法和多线程创建列表视图。该列表将数组列表中的所有数据显示为单行。如何从ArrayList获取项目以在列表视图中使用具有多行的ArrayAdapter显示。

我的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()
                      ...

        });
    }
}

public void updateResponse(final String message) {
        MainActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mButtonSubmit.setText(message);//Text not displayed without 


                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;
}
}

EDIT(数组适配器获取计数方法返回&#34; StorylineData数组为空&#34;):

 @Override
    public int getCount()
    {
        if (storylineData!=null)
        {
            return storylineData.size();
        }
        else
        {
            Log.e("Adapter", "StorylinData array is null");
            return 0;
        }
    }
}

这是我的解析器类:

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();


        /**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 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));

                }
            }

        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));



                }
            }
        }
        return storylineData;
    }
    return null;


}


}

ArrayAdapter items display in a single row

1 个答案:

答案 0 :(得分:1)

更改了MainActivity中的以下代码行,以便使用onClickListener设置适配器:

public class MainActivity extends FragmentActivity implements OnClickListener{
...

更改为:

    public class MainActivity extends FragmentActivity implements View.OnClickListener {
...

MainActivity updateResponse方法:

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);
    }
});
}

更改为:

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);
                }
            });
        }