我是android开发的初学者。我正在尝试使用适配器将数据从健身项目类型的ArrayList发送到MainActivity,但是我不太了解基本适配器。这是我的代码:

WorkoutActivity.java:

    import java.util.ArrayList;
    import java.util.List;

    import android.app.Activity;
    import android.app.FragmentManager;
    import android.content.Context;
    import android.content.Intent;
    import android.content.SharedPreferences;
    import android.content.SharedPreferences.Editor;
    import android.os.Bundle;
    import android.os.SystemClock;
    import android.preference.PreferenceManager;
    import android.view.LayoutInflater;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.BaseAdapter;
    import android.widget.Button;
    import android.widget.Chronometer;
    import android.widget.TextView;

    public class WorkoutActivity extends Activity {

    WorkoutItemAdapter workoutItemAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_workout);
    }




    public class WorkoutItemAdapter extends BaseAdapter{

        int rowCount = 1;
        List<WorkoutItem> workoutsList = getDataForListView();

        public WorkoutItem getWorkout(int position)
        {
            return workoutsList.get(position);
        }

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

            if(convertView == null){
                LayoutInflater inflater = (LayoutInflater) WorkoutActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = inflater.inflate(R.layout.workout_item, parent, false);
            }

            TextView workoutNum = (TextView) convertView.findViewById(R.id.workout_col);
            TextView workoutTime = (TextView) convertView.findViewById(R.id.time_col);

            WorkoutItem workout = workoutsList.get(position);

            workoutNum.setText(workout.workoutNum);
            workoutTime.setText(workout.time);

            return convertView;
        }

        @Override
        public int getCount() {
            return workoutsList.size();
            // TODO Auto-generated method stub
        }

        @Override
        public WorkoutItem getItem(int position) {
            // TODO Auto-generated method stub
            return workoutsList.get(position);
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }
        public void addRow() {
            rowCount++;
            notifyDataSetChanged();
        }
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.workout, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }


    @Override
    public void onBackPressed() {
        moveTaskToBack(true);
    }

    public List<WorkoutItem> getDataForListView()
    {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        String workoutTime = prefs.getString("Workout Time", "");

        List<WorkoutItem> workoutsList = new ArrayList<WorkoutItem>();

        for(int i = 0; i < (workoutsList.size() + 1); i++)
        {
            WorkoutItem workout = new WorkoutItem();
            workout.workoutNum = "Workout " + (i+1);
            workout.time = workoutTime;

            workoutsList.add(workout);
        }

        return workoutsList;
    }

    public void startAndStopTimer(View view)
    {
        long totalTime = 0;

        Button startAndStop = (Button) findViewById(R.id.button1);
        Chronometer c = (Chronometer) findViewById(R.id.chronometer1);
        if(startAndStop.getText().equals("Start"))
        {
            c.setBase(SystemClock.elapsedRealtime() + totalTime);
            c.start();
            startAndStop.setText("Pause");

        }
        else
        {
            totalTime = c.getBase() - SystemClock.elapsedRealtime();
            c.stop();
            startAndStop.setText("Start");
        }
    }

    public void save(View view)
    {
        // create broadcast receiver saying ...saved.

        // Add ArrayList value to arrayList
        Chronometer timer = (Chronometer) findViewById(R.id.chronometer1);

        SharedPreferences timerSettings = PreferenceManager.getDefaultSharedPreferences(this);
        Editor editor = timerSettings.edit();
        editor.putString("Workout Time", timer.getText().toString());
        editor.commit();

        // go back to main activity.
        Intent intent = new Intent(WorkoutActivity.this, OverviewActivity.class);
        startActivity(intent);
        finish();
    }

    public void cancel(View view)
    {
        // go back to main activity
        Intent intent = new Intent(WorkoutActivity.this, OverviewActivity.class);
        startActivity(intent);
        finish();
    }
    }


OverviewActivity.java:

    import edu.uark.csce.razorrunner.WorkoutActivity.WorkoutItemAdapter;
    import android.app.Activity;
    import android.content.Intent;
    import android.content.SharedPreferences;
    import android.os.Bundle;
    import android.preference.PreferenceManager;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.View;
    import android.widget.ListView;
    import android.widget.TextView;


    public class OverviewActivity extends Activity{

    WorkoutItemAdapter workoutAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_overview);
        LoadPreferences();
        LoadListView();
    }
    private void LoadListView() {
        // TODO Auto-generated method stub
        ListView workoutList = (ListView) findViewById(R.id.workout_list);
        workoutList.setAdapter(workoutAdapter);
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.overview, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void LoadPreferences()
    {
            SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
            String Name = sharedPreferences.getString("Name", "");

            TextView textView = (TextView) findViewById(R.id.textView2);
            textView.setText(Name);
    }

    public void openWorkoutActivity(View view)
    {
        Intent intent = new Intent(OverviewActivity.this, WorkoutActivity.class);
        startActivity(intent);
        finish();
    }
    public void openProfileActivity(View view)
    {
        Intent intent = new Intent(OverviewActivity.this, ProfileActivity.class);
        startActivity(intent);
        finish();
    }
    public void openHistoryActivity(View view)
    {
        Intent intent = new Intent(OverviewActivity.this, HistoryActivity.class);
        startActivity(intent);
        finish();
    }
    }


activity_overview.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="edu.uark.csce.razorrunner.OverviewActivity" >

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <Button
            android:id="@+id/profileButton"
            android:layout_width="80dp"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_alignParentTop="true"
            android:onClick="openProfileActivity"
            android:text="Profile" />

        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true"
            android:text="Name"
            android:textAppearance="?android:attr/textAppearanceLarge" />
    </RelativeLayout>

    <ListView
        android:id="@+id/workout_list"
        android:layout_width="wrap_content"
        android:layout_height="195dp"
        android:layout_weight="0.19" >

    </ListView>

    <Button
        android:id="@+id/startNewWorkout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0"
        android:onClick="openWorkoutActivity"
        android:text="Start New Workout!"
        android:typeface="sans" />

</LinearLayout>


activity_workout.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="edu.uark.csce.razorrunner.WorkoutActivity" >

    <Button
        android:id="@+id/Button01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/button2"
        android:layout_alignBottom="@+id/button2"
        android:layout_alignRight="@+id/button1"
        android:text="Cancel"
        android:onClick="cancel" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_toLeftOf="@+id/Button01"
        android:text="Save"
        android:onClick="save" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/Button01"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_marginRight="22dp"
        android:text="Start"
        android:onClick="startAndStopTimer" />

    <TextView
        android:id="@+id/time_col"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView2"
        android:layout_alignParentTop="true"
        android:text="New Workout"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/time_col"
        android:layout_marginTop="18dp"
        android:text="Calories Burned"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/TextView01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView2"
        android:layout_below="@+id/textView2"
        android:layout_marginTop="14dp"
        android:text="Duration"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/TextView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/textView2"
        android:layout_alignBottom="@+id/textView2"
        android:layout_alignRight="@+id/button1"
        android:layout_toRightOf="@+id/button2"
        android:ems="10"
        android:text="0"
        android:textAppearance="?android:attr/textAppearanceLarge">

        <requestFocus />
    </TextView>

    <Chronometer
        android:id="@+id/chronometer1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/TextView01"
        android:layout_alignLeft="@+id/TextView1"
        android:layout_alignRight="@+id/TextView1"
        android:text="Chronometer" />

</RelativeLayout>


每次单击“保存”时,我想显示每个列表项目的锻炼次数和持续时间,但是目前,每次单击“保存”时,我得到的只是一个空白的ListView。关于此主题的任何帮助和/或其他资源都将很有用。

最佳答案

我希望你犯了两个错误。

 public List<WorkoutItem> getDataForListView()
{
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    String workoutTime = prefs.getString("Workout Time", "");

    List<WorkoutItem> workoutsList = new ArrayList<WorkoutItem>();

    for(int i = 0; i < (workoutsList.size() + 1); i++)
    {
        WorkoutItem workout = new WorkoutItem();
        workout.workoutNum = "Workout " + (i+1);
        workout.time = workoutTime;

        workoutsList.add(workout);
    }

    return workoutsList;
}


我猜您正在尝试将数据添加到列表视图。由于您正在使用创建新列表

 List<WorkoutItem> workoutsList = new ArrayList<WorkoutItem>();


ExercisesList.size()将返回零。您的循环将迭代直到列表大小为+1。 (只有一次 )

那么您需要将列表从WorkoutActivity传递给OverviewActivity。

更改WorkoutActivity插入以下代码

public class WorkoutActivity extends Activity {

WorkoutItemAdapter workoutItemAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_workout);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.workout, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

@Override
public void onBackPressed() {
    moveTaskToBack(true);
}

public List<WorkoutItem> getDataForListView() {
    SharedPreferences prefs = PreferenceManager
            .getDefaultSharedPreferences(this);
    String workoutTime = prefs.getString("Workout Time", "");

    List<WorkoutItem> workoutsList = new ArrayList<WorkoutItem>();

    for (int i = 0; i < (10+ 1); i++) {
        WorkoutItem workout = new WorkoutItem();
        workout.workoutNum = "Workout " + (i + 1);
        workout.time = workoutTime;

        workoutsList.add(workout);
    }

    return workoutsList;
}

public void startAndStopTimer(View view) {
    long totalTime = 0;

    Button startAndStop = (Button) findViewById(R.id.button1);
    Chronometer c = (Chronometer) findViewById(R.id.chronometer1);
    if (startAndStop.getText().equals("Start")) {
        c.setBase(SystemClock.elapsedRealtime() + totalTime);
        c.start();
        startAndStop.setText("Pause");

    } else {
        totalTime = c.getBase() - SystemClock.elapsedRealtime();
        c.stop();
        startAndStop.setText("Start");
    }
}

public void save(View view) {
    // create broadcast receiver saying ...saved.

    // Add ArrayList value to arrayList
    Chronometer timer = (Chronometer) findViewById(R.id.chronometer1);

    SharedPreferences timerSettings = PreferenceManager
            .getDefaultSharedPreferences(this);
    Editor editor = timerSettings.edit();
    editor.putString("Workout Time", timer.getText().toString());
    editor.commit();

    // go back to main activity.
    Intent intent = new Intent(WorkoutActivity.this, OverviewActivity.class);
    intent.putStringArrayListExtra("stock_list", getDataForListView());
    startActivity(intent);
    finish();
}

public void cancel(View view) {
    // go back to main activity
    Intent intent = new Intent(WorkoutActivity.this, OverviewActivity.class);
    intent.putStringArrayListExtra("stock_list", getDataForListView());
    startActivity(intent);

    finish();
}

}


和概述活动

public class OverviewActivity extends Activity{


List<WorkoutItem> workList;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_overview);
    Intent i = getIntent();
    workList = i.getStringArrayListExtra("stock_list");
    LoadPreferences();
    LoadListView();
}
private void LoadListView() {
    // TODO Auto-generated method stub
    ListView workoutList = (ListView) findViewById(R.id.workout_list);

    WorkoutItemAdapter workoutAdapter= new WorkoutItemAdapter(workList);
    workoutList.setAdapter(workoutAdapter);
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.overview, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

private void LoadPreferences()
{
        SharedPreferences sharedPreferences =     PreferenceManager.getDefaultSharedPreferences(this);
        String Name = sharedPreferences.getString("Name", "");

        TextView textView = (TextView) findViewById(R.id.textView2);
        textView.setText(Name);
}

public void openWorkoutActivity(View view)
{
    Intent intent = new Intent(OverviewActivity.this, WorkoutActivity.class);
    startActivity(intent);
    finish();
}
public void openProfileActivity(View view)
{
    Intent intent = new Intent(OverviewActivity.this, ProfileActivity.class);
    startActivity(intent);
    finish();
}
public void openHistoryActivity(View view)
{
    Intent intent = new Intent(OverviewActivity.this, HistoryActivity.class);
    startActivity(intent);
    finish();
}

public class WorkoutItemAdapter extends BaseAdapter{

    int rowCount = 1;
    List<WorkoutItem> workoutsList ;

  public  WorkoutItemAdapter( List<WorkoutItem> list) {
  workoutsList=list;
}

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

        if(convertView == null){
            LayoutInflater inflater = (LayoutInflater) WorkoutActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.workout_item, parent, false);
        }

        TextView workoutNum = (TextView) convertView.findViewById(R.id.workout_col);
        TextView workoutTime = (TextView) convertView.findViewById(R.id.time_col);

        WorkoutItem workout = workoutsList.get(position);

        workoutNum.setText(workout.workoutNum);
        workoutTime.setText(workout.time);

        return convertView;
    }

    @Override
    public int getCount() {
        return workoutsList.size();
        // TODO Auto-generated method stub
    }

    @Override
    public WorkoutItem getItem(int position) {
        // TODO Auto-generated method stub
        return workoutsList.get(position);
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }
    public void addRow() {
        rowCount++;
        notifyDataSetChanged();
    }
}
}


试试这些代码。我还没有尝试过,希望一切正常。

08-06 05:54