Android - 填充ListView

时间:2014-02-24 13:03:20

标签: java android arrays listview android-listview

CreateDatabse:

public void createDataBase() throws IOException
{
//If database not exists copy it from the assets

boolean mDataBaseExist = checkDataBase();
if(!mDataBaseExist)
{
    this.getReadableDatabase();
    this.close();
    try 
    {
        //Copy the database from assests
        copyDataBase();

    } 
    catch (IOException mIOException) 
    {
        throw new Error("ErrorCopyingDataBase");
    }
}
}

TestAdapter:

import java.io.IOException;
import java.util.ArrayList;



import android.view.View;
import android.view.ViewGroup;
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;


public class TestAdapter extends Activity 
{

ArrayList<Horario> array = new ArrayList<Horario>();
protected static final String TAG = "DataAdapter";

private final Context mContext;
private SQLiteDatabase mDb;
private DataBaseHelper mDbHelper;

public TestAdapter(Context context) 
{
    this.mContext = context;
    mDbHelper = new DataBaseHelper(mContext);
}

public TestAdapter createDatabase() throws SQLException 
{
    try 
    {
        mDbHelper.createDataBase();
    } 
    catch (IOException mIOException) 
    {
        Log.e(TAG, mIOException.toString() + "  UnableToCreateDatabase");
        throw new Error("UnableToCreateDatabase");
    }
    return this;
}

public TestAdapter open() throws SQLException 
{
    try 
    {
        mDbHelper.openDataBase();
        mDbHelper.close();
        mDb = mDbHelper.getReadableDatabase();
    } 
    catch (SQLException mSQLException) 
    {
        Log.e(TAG, "open >>"+ mSQLException.toString());
        throw mSQLException;
    }
    return this;
}

public void close() 
{
    mDbHelper.close();
}

 public Cursor getTestData()
 {
     try
     {
         String sql ="SELECT * FROM horarios";

         Cursor mCur = mDb.rawQuery(sql, null);
         if (mCur!=null)
         {
            mCur.moveToNext();
         }
         return mCur;
     }
     catch (SQLException mSQLException) 
     {
         Log.e(TAG, "getTestData >>"+ mSQLException.toString());
         throw mSQLException;
     }

 }
 public ArrayList<Horario> getorigem(){

    String query = "select origem, destino From horarios";
    Cursor cursor = mDb.rawQuery(query, new String[]{});

    ArrayList<Horario> array = new ArrayList<Horario>();

    while (cursor.moveToNext()) {
        String _origem = cursor.getString(cursor.getColumnIndex("origem"));
        String _destino = cursor.getString(cursor.getColumnIndex("destino"));
        array.add(new Horario(_origem, _destino));
    }
    return array;     

}

public void populateListView() {
    // TODO Auto-generated method stub

    MyListAdapter adapter = new MyListAdapter();       
    ListView list = (ListView) findViewById(R.id.list_view);
    list.setAdapter(adapter);

}

private class MyListAdapter extends ArrayAdapter<Horario>{
    public MyListAdapter() {
        super(TestAdapter.this, R.layout.item_view, array);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        //Make sure we have view to work with
        View itemView = convertView;
        if(itemView == null){
            itemView = getLayoutInflater().inflate(R.layout.item_view, parent, false);
        }

        //Find the car to work with.
        Horario currentHorario = array.get(position);

        //Fill the view

        // Origem:
        TextView makeText = (TextView) itemView.findViewById(R.id.view_origem);
        makeText.setText(currentHorario.getOrigem());

        // Destino:
        TextView ConditionText = (TextView) itemView.findViewById(R.id.view_destino);
        ConditionText.setText(currentHorario.getDestino());

        return itemView;

    }
}
}

我尝试填充像这样的ListView:

 public void populateListView() {
    // TODO Auto-generated method stub

    ArrayAdapter<Horario> adapter = new MyListAdapter();
    ListView list = (ListView) findViewById(R.id.list_view);
    list.setAdapter(adapter);

}

private class MyListAdapter extends ArrayAdapter<Horario>{
    public MyListAdapter() {
        super(TestAdapter.this, R.layout.item_view, array);
    }

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

        View itemView = convertView;
        if(itemView == null){
            itemView = getLayoutInflater().inflate(R.layout.item_view, parent, false);
        }


        Horario currentHorario = array.get(position);

        //Fill the view

        // Origem:
        TextView makeText = (TextView) itemView.findViewById(R.id.view_origem);
        makeText.setText(currentTime.getOrigem());

        // Destino:
        TextView makeText = (TextView) itemView.findViewById(R.id.view_destino);
        makeText.setText(currentTime.getDestino());

        return itemView;

    }
}

主要活动:

import android.os.Bundle;
import android.app.Activity;

import android.database.sqlite.SQLiteDatabase;
import android.view.View;

public class MainActivity extends Activity {

    SQLiteDatabase mDb;

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

        TestAdapter mDbHelper = new TestAdapter(getBaseContext());
        mDbHelper.createDatabase();

    }

    public void search(View v) {

        setContentView(R.layout.list_view);

        TestAdapter mDbHelper = new TestAdapter(getBaseContext());
        mDbHelper.open();

        mDbHelper.getorigem();
        mDbHelper.populateListView();
        mDbHelper.close();

    }
}

但是当我点击按钮时它会出错并关闭 logcat的

02-24 08:29:32.290: E/AndroidRuntime(1168): FATAL EXCEPTION: main
02-24 08:29:32.290: E/AndroidRuntime(1168): Process: arr.app, PID: 1168
02-24 08:29:32.290: E/AndroidRuntime(1168): java.lang.IllegalStateException: Could not execute method of the activity
02-24 08:29:32.290: E/AndroidRuntime(1168):     at android.view.View$1.onClick(View.java:3823)
02-24 08:29:32.290: E/AndroidRuntime(1168):     at android.view.View.performClick(View.java:4438)
02-24 08:29:32.290: E/AndroidRuntime(1168):     at android.view.View$PerformClick.run(View.java:18422)
02-24 08:29:32.290: E/AndroidRuntime(1168):     at android.os.Handler.handleCallback(Handler.java:733)
02-24 08:29:32.290: E/AndroidRuntime(1168):     at android.os.Handler.dispatchMessage(Handler.java:95)
02-24 08:29:32.290: E/AndroidRuntime(1168):     at android.os.Looper.loop(Looper.java:136)
02-24 08:29:32.290: E/AndroidRuntime(1168):     at android.app.ActivityThread.main(ActivityThread.java:5017)
02-24 08:29:32.290: E/AndroidRuntime(1168):     at java.lang.reflect.Method.invokeNative(Native Method)
02-24 08:29:32.290: E/AndroidRuntime(1168):     at java.lang.reflect.Method.invoke(Method.java:515)
02-24 08:29:32.290: E/AndroidRuntime(1168):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
02-24 08:29:32.290: E/AndroidRuntime(1168):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
02-24 08:29:32.290: E/AndroidRuntime(1168):     at dalvik.system.NativeStart.main(Native Method)
02-24 08:29:32.290: E/AndroidRuntime(1168): Caused by: java.lang.reflect.InvocationTargetException
02-24 08:29:32.290: E/AndroidRuntime(1168):     at java.lang.reflect.Method.invokeNative(Native Method)
02-24 08:29:32.290: E/AndroidRuntime(1168):     at java.lang.reflect.Method.invoke(Method.java:515)
02-24 08:29:32.290: E/AndroidRuntime(1168):     at android.view.View$1.onClick(View.java:3818)
02-24 08:29:32.290: E/AndroidRuntime(1168):     ... 11 more
02-24 08:29:32.290: E/AndroidRuntime(1168): Caused by: java.lang.IllegalStateException: System services not available to Activities before onCreate()
02-24 08:29:32.290: E/AndroidRuntime(1168):     at android.app.Activity.getSystemService(Activity.java:4532)
02-24 08:29:32.290: E/AndroidRuntime(1168):     at android.widget.ArrayAdapter.init(ArrayAdapter.java:310)
02-24 08:29:32.290: E/AndroidRuntime(1168):     at android.widget.ArrayAdapter.<init>(ArrayAdapter.java:153)
02-24 08:29:32.290: E/AndroidRuntime(1168):     at arr.app.TestAdapter$MyListAdapter.<init>(TestAdapter.java:119)
02-24 08:29:32.290: E/AndroidRuntime(1168):     at arr.app.TestAdapter.populateListView(TestAdapter.java:111)
02-24 08:29:32.290: E/AndroidRuntime(1168):     at arr.app.MainActivity.search(MainActivity.java:32)
02-24 08:29:32.290: E/AndroidRuntime(1168):     ... 14 more

activity_main.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: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=".MainActivity" >

<Button
    android:id="@+id/btnsearch"
    android:layout_width="150dp"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:onClick="search"
    android:text="Search" />

<TextView
    android:id="@+id/lbldestino"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/lblorigem"
    android:layout_below="@+id/lblorigem"
    android:layout_marginTop="54dp"
    android:text="Destino"
    android:textAppearance="?android:attr/textAppearanceMedium" />

<TextView
    android:id="@+id/lblorigem"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:layout_marginTop="18dp"
    android:text="Origem"
    android:textAppearance="?android:attr/textAppearanceMedium" />

<EditText
    android:id="@+id/txtorigem"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/lblorigem"
    android:layout_below="@+id/lblorigem"
    android:ems="10" >

    <requestFocus />
</EditText>

<EditText
    android:id="@+id/txtdestino"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/lbldestino"
    android:layout_below="@+id/lbldestino"
    android:ems="10" />

</RelativeLayout>

我开始编程到android大约1周,我在某些天试图解决这个问题 感谢任何帮助

1 个答案:

答案 0 :(得分:0)

问题是您的适配器正在扩展Activity而未在setContentView方法中实现onCreate,因此在调用findViewById(R.id.list_view);时失败。假设populateListView布局文件(R.layout.list_view)包含名为MainActivity的{​​{1}},您需要在list_view内使用ListView方法的内容(R.id.list_view)。

list_view

public void search(View v) { setContentView(R.layout.list_view); TestAdapter mDbHelper = new TestAdapter(getBaseContext()); mDbHelper.open(); ArrayAdapter<Horario> adapter = new MyListAdapter(mDbHelper.getorigem()); ListView list = (ListView) findViewById(R.id.list_view); list.setAdapter(adapter); mDbHelper.close(); } 修改构造函数:

MyListAdapter

要在单击按钮上调用搜索,请使用以下方法:

public MyListAdapter(ArrayList<Horario> arrayHorario) {
    array = arrayHorario;
    super(TestAdapter.this, R.layout.item_view, array);
}

希望它有所帮助!