0

我正在尝试为它从我的数据库返回的每一行创建一个如下所示的布局(将是最后 7 天)。任何帮助,将不胜感激。

我创建的 XML

    <QuickContactBadge
            android:id="@+id/image"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:scaleType="centerCrop"/>

        <TextView android:id="@+id/date"
                  android:layout_width="match_parent"
                  android:layout_height="wrap_content"
                  android:layout_toRightOf="@+id/image"
                  android:gravity="center_vertical"
                  android:layout_alignParentRight="true"
                  android:layout_alignParentTop="true"
                  android:text="date"/>

           <TextView
               android:id="@+id/temp"
               android:layout_width="150dp"
               android:layout_height="wrap_content"
               android:layout_alignLeft="@+id/date"
               android:layout_below="@+id/date"
               android:gravity="center_vertical"
               android:text="temp" />

           <TextView
                android:id="@+id/fertile"
                android:layout_width="150dp"
                android:layout_height="wrap_content"
                android:layout_above="@+id/notes"
                android:layout_toRightOf="@+id/temp"
                android:gravity="center_vertical"
                android:text="fertile" />

            <TextView
                android:id="@+id/notes"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignBottom="@+id/image"
                android:layout_alignLeft="@+id/temp"
                android:layout_below="@+id/temp"
                android:gravity="center_vertical"
                android:text="notes" />

    </RelativeLayout>

有人可以告诉我如何遍历 sql 以获得我想要的布局吗?

            public class HistoryFragment extends Fragment {

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState); 
        }       

         @Override
         public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {



            View view = inflater.inflate(R.layout.fragment_history, container, false);

            //Get data from SQL
            SQLHelper entry = new SQLHelper(getActivity());
            entry.open();
            Cursor results = entry.getAllData();
            entry.close();



            return view;
         }

    }

SQL

public class SQLHelper {
    //Database information
    private static final String DATABASE_NAME = "NFP";
    private static final int DATABASE_VERSION = 1;

    //Table Information
    private static final String DATABASE_TABLE = "charting";
    public static final String KEY_ROWID = "_id";
    public static final String KEY_NAME = "persons_name";
    public static final String KEY_CHARTING_DATE = "Date";
    public static final String KEY_CHARTING_TEMPERATURE = "temperature";
    public static final String KEY_CHARTING_STAMPS = "Stamps";
    public static final String KEY_CHARTING_FERTILE = "Fertile";
    public static final String KEY_CHARTING_NOTES = "Notes";
    public static final String KEY_CHARTING_PROC = "Proc";


    private DbHelper ourHelper;
    private final Context ourContext;
    private static SQLiteDatabase ourDatabase;

    private static class DbHelper extends SQLiteOpenHelper{
    public SQLHelper(Context c) {
        ourContext = c;
    }

            public DbHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL( "CREATE TABLE " + DATABASE_TABLE + " (" +
                                        KEY_ROWID + " INTEGER  primary key AUTOINCREMENT, " +
                                        KEY_CHARTING_DATE + " TEXT primary key NOT NULL, " +
                                        KEY_NAME + " TEXT, " +
                                        KEY_CHARTING_TEMPERATURE + " INTEGER, " +
                                        KEY_CHARTING_STAMPS  + " INTEGER, " +
                                        KEY_CHARTING_FERTILE + " TEXT, " +
                                        KEY_CHARTING_NOTES + " TEXT, " +
                                        KEY_CHARTING_PROC +  " ); "
                    );
        }

    public SQLHelper open() throws SQLException{
        ourHelper = new DbHelper(ourContext);
        ourDatabase = ourHelper.getWritableDatabase();
        return this;
    }

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

    public long createEntry(String date, String temperature, String fertile, String notes) {
        ContentValues cv = new ContentValues();
        cv.put(KEY_CHARTING_DATE, date);
        cv.put(KEY_CHARTING_TEMPERATURE, temperature);
        cv.put(KEY_CHARTING_FERTILE, fertile);
        cv.put(KEY_CHARTING_NOTES, notes);
        return ourDatabase.insertOrThrow (DATABASE_TABLE, null, cv);

    }

    public String getData() {
        String[] columns = new String[]{ KEY_CHARTING_DATE, KEY_CHARTING_TEMPERATURE, KEY_CHARTING_STAMPS, KEY_CHARTING_FERTILE, KEY_CHARTING_NOTES };
        Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);

        String result = "";

        int iDate = c.getColumnIndex(KEY_CHARTING_DATE);
        int iTemp = c.getColumnIndex(KEY_CHARTING_TEMPERATURE);
        int iStamps = c.getColumnIndex(KEY_CHARTING_STAMPS);
        int iFertile = c.getColumnIndex(KEY_CHARTING_FERTILE);
        int iNotes = c.getColumnIndex(KEY_CHARTING_NOTES);

        for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
            result = result + "" + c.getString(iDate) + "/n" + c.getString(iTemp) + "/n" + c.getString(iStamps) + "/n" + c.getString(iFertile) + "/n" + c.getString(iNotes) + "|";
        }

        return result;
    }
    public Cursor getAllData() {


        String[] columns = new String[]{ KEY_CHARTING_DATE, KEY_CHARTING_TEMPERATURE, KEY_CHARTING_STAMPS, KEY_CHARTING_FERTILE, KEY_CHARTING_NOTES };
        Cursor cursor = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);


        return cursor;
      }
}
4

1 回答 1

1

此任务有一个标准解决方案,由以下层组成:

数据库层

我对您使用的数据源一无所知:本地或远程,所以这里没有建议

内容提供者,提供来自您的数据库的数据。

这不是必需的,但允许使用内置加载器和 cursorAdapters 进行最少的修改。

您的自定义适配器扩展,例如 SimpleCursorAdapter,它使用示例图片上显示的行的自定义布局。通常,此布局存储在单独的 xml 布局文件中。适配器包含将数据从数据库游标行绑定到新创建的行视图的逻辑。

最后,在您的 Fragment 中添加 ListView 。您将 ListView 的适配器设置为您的适配器。

当然,这是一条很长的路,我相信不是唯一的,而是汗水最少的路。

细节太长,无法在一个答案中涵盖,因此请务必学习相应的教程:

自定义适配器和 ListView

Sqlite 数据库之上的内容提供者

您应该: I. 将 Content Provider 包裹在您的数据库周围,如上面的教程链接所示。结果:类 MyContentProvider。

 static {
    sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
    sUriMatcher.addURI(AUTHORITY, DATABASE_TABLE, MATCH_ALL);

    projectionMap = new HashMap<String, String>();
    projectionMap.put(KEY_ROWID, KEY_ROWID);
    projectionMap.put(KEY_NAME, KEY_NAME);
    //...the same for other fields
    projectionMap.put(KEY_CHARTING_PROC, KEY_CHARTING_PROC);
 }


@Override
public boolean onCreate() {
    ourHelper = new DbHelper(getContext());
    return true;
}

@Override
public String getType(Uri uri) {
    switch (sUriMatcher.match(uri)) {
        case MATCH_ALL:
            return MY_CONTENT_TYPE;
        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
    }
}

@Override
public int delete(Uri uri, String where, String[] whereArgs) {
    int count;
    SQLiteDatabase db = ourHelper.getWritableDatabase();
    switch (sUriMatcher.match(uri)) {
        case MATCH_ALL: {
            count = db.delete(DATABASE_TABLE, where, whereArgs);
            getContext().getContentResolver().notifyChange(uri, null);
            return count;
        }
        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
    }
}
//insert and update are just the same: copy from tutorial with the same changes

@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
    SQLiteQueryBuilder qb = new SQLiteQueryBuilder();

    SQLiteDatabase db = dbHelper.getReadableDatabase();

    switch (sUriMatcher.match(uri)) {
        case MATCH_ALL:
            qb.setTables(DATABASE_TABLE);
            qb.setProjectionMap(projectionMap);
            break;
        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
    }

    Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, sortOrder);
    c.setNotificationUri(getContext().getContentResolver(), uri);
    return c;
}

二、为单个数据库行创建 xml 布局(您已经有一个)。结果:entry.xml

三、编写类 MyAdapter 扩展 SimpleCursorAdapter,覆盖它的 newView() 和 bindView()。您还应该编写类构造函数。

    class MyAdapter extends SimpleCursorAdapter{
    private int layout;

    public MyAdapter (Context context, int layout, Cursor c, String[] from, int[] to) {
        super(context, layout, c, from, to); //deprecated, but used here for simplicity
        this.layout = layout; //your entry.xml id
    }

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {

        Cursor c = getCursor();

        //creating row view from entry.xml
        final LayoutInflater inflater = LayoutInflater.from(context);
        View v = inflater.inflate(layout, parent, false);

        bindView(v, context, c)    

        return v;
    }

    @Override
    public void bindView(View v, Context context, Cursor c) {
        //get data from current cursor position
        int myCol = c.getColumnIndex("my_field");
        int myField = c.getInt(myCol);

        //find a widget in the view, inflated with your entry.xml
        ImageView imgType = (ImageView) v.findViewById(R.id.imgMyField);
        if (imgType != null){
            if (myField == 0)
                imgType.setImageResource(R.drawable.img_zero);
            else
                imgType.setImageResource(R.drawable.img_non_zero);
        }

        return v;
    }
    }

请注意,当您为 ListView 或数据源更改设置 Adapter 时,将为 Cursor 中的每一行自动调用 newView()/bindView。

四。在您的 Fragment 的 onCreateView 中:查看 v

        //deprecated: only for simplicity
        //get database cursor from provider
        Cursor cursor = managedQuery(MyProvider.MY_CONTENT_URI, PROJECTION, null, null, BaseColumns.ID + " ASC");
    String[] dataColumns = {/* you columns here*/ } ;
    adapter
            = new MyAdapter(
            this.getActivity(),                             // The Context for the ListView
            R.layout.entry,          // Points to the XML for a list item
            cursor,                           // The cursor to get items from
            dataColumns,
            null
    );
    ListView listView = (ListView) v.findViewById(R.id.listView);
    listView.setAdapter(adapter); //here list view is actually filled

如果某些东西不起作用,请检查 Android SDK 中的 SearchableDictionary 和 NotePad 示例

重要提示:在您的列表视图开始工作后,不要坚持使用已弃用的 ManagedQuery。改用装载机。

于 2013-05-13T21:27:59.303 回答