Android从另一个活动

时间:2016-05-01 09:25:51

标签: java android sqlite

我尽量保持这个简单。我有一个SQLite数据库,其中包含以下方法,该方法返回表中的所有名称:

public ArrayList<String> getAllPlacesNames() {
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor result = db.rawQuery("select placeName FROM " + DataTableName,null);
        ArrayList<String> companyNames = new ArrayList<String>();
        while(result.moveToNext()) {
            String places = result.getString(result.getColumnIndex("placeName"));
            companyNames.add(places);
        }
        return companyNames;
    }

我有一个MainActivity.java,我通过调用DataBaseHelper中的方法getAllPlacesNames()获取并返回名称的String数组:

public ArrayList<String> getAllPlacesNamesMain() {

        return summerJobDB.getAllPlacesNames();
    }

现在我的问题。我试图为列表视图创建自定义适配器以显示名称。但我不知道如何从我的适配器文件StringArrayAdapter.java获取getAllPlacesNamesMain()的返回值并将其转换为数组所以我可以在我的构造函数中使用它。以下是我到目前为止的情况:

public class StringArrayAdapter extends BaseAdapter {

    Context ctxt;
    LayoutInflater myInflator;
    DataBaseHelper summerJobDB;
    public ArrayList<String> getAllPlacesNamesMain() {return summerJobDB.getAllPlacesNames();}
    String[] places = new String [getAllPlacesNamesMain().size()];
    // convert places to Array
    places = getAllPlacesNamesMain().toArray(places);


    public StringArrayAdapter(String [] arr, Context c) {
        // here I need to set places to arr

    }

    @Override
    public int getCount() {
        return 0;
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // create a cell to be displayed inside listview (a view)
        return null;
    }
}

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

试试这个:

public class StringArrayAdapter extends BaseAdapter {

    Context ctxt;
    LayoutInflater myInflator;
    DataBaseHelper mSummerJobDB;
    private ArrayList<String> mAllPlacesNames;

    public StringArrayAdapter(DataBaseHelper summerJobDB, Context c) {
        // here I need to set places to arr
       this.ctxt = c;
       this.mSummerJobDB = summerJobDB;
       mAllPlacesNames = summerJobDB.getAllPlacesNames();

    }

    @Override
    public int getCount() {
        return mAllPlacesNames.size();
    }

    @Override
    public Object getItem(int position) {
        return mAllPlacesNames.get(position);
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // create a cell to be displayed inside listview (a view)
        return null;
    }
}

并在MainActivity上创建适配器,提供对DatabaseHelper的引用。