Android SQLite:检索表的所有数据的列表

时间:2016-05-04 03:16:23

标签: android list sqlite listview android-sqlite

实际上我可以循环并登录控制台的所有行:

    db.getAllPoids();
    List<Poids> poids = db.getAllPoids();

    for (Poids val : poids) {
        String log = "Id: " + val.getId() + " ,Date: " + val.getDate_enr() + " ,Poids: " + val.getPoids() + " ,Evolution: " + val.getEvolution() ;
        // Writing Contacts to log
        Log.d("Name: ", log);
    }

数据库处理器:

public List<Poids> getAllPoids() {
    List<Poids> poidsList = new ArrayList<Poids>();
    // Select All Query
    String selectQuery = "SELECT * FROM " + TABLE_POIDS;

    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);

    // looping through all rows and adding to list
    if (cursor.moveToFirst()) {
        do {
            Poids poid = new Poids();
            poid.setId(Integer.parseInt(cursor.getString(0)));
            poid.setPoids(Integer.parseInt(cursor.getString(1)));
            poid.setDate_enr(cursor.getString(2));
            poid.setEvolution(cursor.getString(3));
            poid.setId_utilisateurs(Integer.parseInt(cursor.getString(4)));
            // Adding contact to list
            poidsList.add(poid);
        } while (cursor.moveToNext());
    }

但是现在我不想做一个更好的观点,我需要像桌子或听众一样的东西,我知道他们是google上的listview例子,但不是我使用的这种方法。

在我看来,我需要有3行: 获取第一个中的日期,第二个和第n个图像视图中的行“poids”包含用于删除单击行的ID。有可能的 ?我不知道该怎么做。

PoidsAdapter:

public class PoidsAdapter extends ArrayAdapter<Poids> {
    private Context mContext;
    private List<Poids> mListPoids;

    public PoidsAdapter(Context context, int resource, List<Poids> objects) {
        super(context, resource, objects);
        this.mContext = context;
        this.mListPoids = objects;
    }


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

    @Override
    public Poids getItem(int position) {
        return mListPoids.get(position);
    }

    @Override
    public View getView(final int position, View view, final ViewGroup parent) {
        final holder holder;
            LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = inflater.inflate(R.layout.listpoids, null);
            holder = new holder();
            holder.mTvTitle = (TextView) view.findViewById(R.id.textViewDate);
            holder.mTvMediaName = (TextView) view.findViewById(R.id.textViewPoids);
            holder.mImageUrl = (Button) view.findViewById(R.id.buttonSupprimer);
    return view;
    }

    public class holder {
        public Button mImageUrl;
        public TextView mTvTitle;
        public TextView mTvMediaName;
    }
}

更新2:

我隐藏了一个文本视图来保存id:

@Override
public View getView(final int position, View view, final ViewGroup parent) {
    final ViewHolder holder;
        LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = inflater.inflate(R.layout.listpoids, null);
        holder = new ViewHolder();
        holder.mTvTitle = (TextView) view.findViewById(R.id.textViewDate);
    holder.mTvMediaName = (TextView) view.findViewById(R.id.textViewPoids);
    holder.poidsId = (TextView) view.findViewById(R.id.textViewPoidsId);
        holder.mImageUrl = (Button) view.findViewById(R.id.buttonSupprimer);
        Poids poids = mListPoids.get(position);
        holder.mTvTitle.setText(poids.getDate_enr().toString());
    holder.mTvMediaName.setText(String.valueOf(poids.getPoids()).toString() + "kg");
    holder.poidsId.setText(String.valueOf(poids.getId()).toString());


    return view;
}

片段:

public class MonPoidsFragment extends Fragment {

    DatabaseHandler db = new DatabaseHandler(getActivity());

    public MonPoidsFragment(){}

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //View rootView = inflater.inflate(R.layout.accueil_activity, container, false);
        View view = inflater.inflate(R.layout.monpoids_activity, container, false);

        final ListView listView=(ListView) view.findViewById(R.id.listView);
        Button  buttonAjouter = (Button)view.findViewById(R.id.buttonAjouter);
        Button  buttonSupprimer = (Button)view.findViewById(R.id.buttonSupprimer);

        db = new DatabaseHandler(getActivity());

        db.getAllPoids();
        final List<Poids> poids = db.getAllPoids();


        PoidsAdapter  mAdapter = new PoidsAdapter(getActivity(), R.layout.listpoids, poids);
        listView.setAdapter(mAdapter);
        Log.d("getCount(): ", "" + mAdapter.getCount());

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(final AdapterView<?> parent, View view, final int position, long id) {

                poids.remove(position);
                db.deletePoids(position);

            }
        });


        buttonSupprimer.setOnClickListener(
                listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                                    @Override
                                                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                                        poids.remove(position);
                                                        db.deletePoids(position);
                                                    }
                                                })});

        buttonAjouter.setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Fragment fragment = null;
                        fragment = new AjoutPoidsFragment();
                        FragmentManager fragmentManager = getFragmentManager();
                        fragmentManager.beginTransaction().replace(R.id.frame_container, fragment).commit();
                    }
                });


        return view;
    }
}

数据库:

public void deletePoids(int rowID) {
    SQLiteDatabase db = this.getWritableDatabase();
    db.delete(TABLE_POIDS, KEY_ID + " =? ", new String[]{String.valueOf(rowID)});
}

monpoids_activity:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="fill_parent"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:descendantFocusability="beforeDescendants"
    android:background="#ffffff"
    android:orientation="vertical">

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="fill_parent" android:layout_height="fill_parent"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:padding="10dp">


        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Ajouter un poids"
            android:id="@+id/buttonAjouter"
            android:background="#70cbed"
            android:textColor="#ffffff"
            android:textAlignment="center"
            android:layout_marginTop="20dp" />

        <ListView

            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:id="@+id/listView" />

    </LinearLayout>

</RelativeLayout>

listpoids.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:background="#bbd3dc">

    <TextView
        android:id="@+id/textViewDate"
        android:layout_gravity="center"
        android:layout_width="0.7in"
        android:layout_height="wrap_content"
        android:text="TextView"
        android:padding="10dp" />

    <TextView
        android:layout_gravity="center"
        android:layout_width="0.7in"
        android:layout_height="wrap_content"
        android:text="New Text"
        android:id="@+id/textViewPoids"
        android:padding="10dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/textViewPoidsId"
        android:text="hidden"
        android:visibility="gone"/>

    <Button
        android:layout_gravity="center"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Supprimer"
        android:id="@+id/buttonSupprimer" />

</LinearLayout>

2 个答案:

答案 0 :(得分:0)

将方法添加到 DatabaseHandler

   public static void delete(int rowID) {
    SQLiteDatabase database = this.getWritableDatabase();
    database.delete(TABLE_POIDS, COL_ID + " =? ", new String[]{String.valueOf(rowID)});
   }
listview.setOnItemClickListener

中的

@Override
public void onItemClick(final AdapterView<?> parent, View view, final int position, long id) {
     Poids poids= mAdapter.getItem(position);
     int id = poids.getId();
     poids.remove(position);
     db.delete(id);
      mAdapter.notifyDataSetChanged();

}

创建PoidsAdapter.class

public class PoidsAdapter extends ArrayAdapter<Poids> {
private Context mContext;
private List<Poids> mListPoids;

public PoidsAdapter(Context context, int resource, List<Poids> objects) {
    super(context, resource, objects);
    this.mContext = context;
    this.mListPoids = objects;
}


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

@Override
public Poids getItem(int position) {
    return mListPoids.get(position);
}

@Override
public View getView(final int position, View view, final ViewGroup parent) {
    final ViewHolder holder;
    if (view == null) {
        LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = inflater.inflate(R.layout.item_poids, null);
        holder = new ViewHolder();
        holder.mTvTitle = (TextView) view.findViewById(R.id.text_title);
        holder.mTvMediaName = (TextView) view.findViewById(R.id.text_mediaName);
        holder.mImageUrl = (ImageView) view.findViewById(R.id.image_url);
        view.setTag(holder);
    } else {
        holder = (ViewHolder) view.getTag();
    }
    final Poids poids = mListPoids.get(position);
    holder.mTvTitle.setText(poids.getTitle());
    holder.mTvMediaName.setText(poids.getMediaName());
    Picasso.with(mContext).load(poids.getImageUrl())
            //.fit().centerInside()
            .into(holder.mImageUrl);

    return view;
}

public class ViewHolder {
    public ImageView mImageUrl;
    public TextView mTvTitle;
    public TextView mTvMediaName;
}
}
在Oncreate中

List<Poids> poids= db.getAllPoids();
PoidsAdapter  mAdapter = new PoidsAdapter(this, R.layout.item_poids, poids);
    listView.setAdapter(mAdapter);

将picasso添加到build.gradle

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:22.2.1'
compile 'com.squareup.picasso:picasso:2.5.2'

}

在activity_main.xml中添加控件ListView

创建布局item_poids.xml有3个控件TextView,TextView,ImageView

答案 1 :(得分:0)

是的,这是可能的。

一种方法是使用ListView。

这需要将ListView定义为布局的一部分,例如: -

    <ListView
        android:id="@+id/mylistview"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">
    </ListView>

然后,您需要在列表视图中为行/条目布局(即它等同于光标行)。一个简单的例子,适用于两个db列(名称和顺序): -

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="@dimen/standard_listview_row_height"
    android:paddingBottom="@dimen/standard_listview_row_padding_vertical"
    android:paddingLeft="@dimen/standard_listview_row_padding_horizontal"
    android:paddingRight="@dimen/standard_listview_row_padding_horizontal"
    android:paddingTop="@dimen/standard_listview_row_padding_vertical">
    <!-- Aisle Name -->
    <TextView
        android:id="@+id/aisle_name_entry"
        android:layout_width="@dimen/standard_dummy_size"
        android:layout_height="match_parent"
        android:layout_weight="0.89"
        android:textSize="@dimen/standard_listview_text_size"
        android:textStyle="bold" />
    <!-- Aisle Order-->
    <TextView
        android:id="@+id/aisle_order_entry"
        android:layout_width="@dimen/standard_dummy_size"
        android:layout_height="match_parent"
        android:layout_weight="0.1"
        android:gravity="end"
        android:textSize="@dimen/standard_listview_text_size"
        android:visibility="visible"/>
</LinearLayout>

您需要一个Adapter.A游标适配器基本上将数据库游标中的数据放入适当的视图中。这是上面的适配器: -

class AislesCursorAdapter extends CursorAdapter {
    public AislesCursorAdapter(Context context, Cursor cursor, int flags) {
        super(context, cursor, 0);
    }
    @Override
    public View getView(int position, View convertview, ViewGroup parent) {
        View view = super.getView(position, convertview, parent);
        Context context = view.getContext();
        if (position % 2 == 0) {
            view.setBackgroundColor(ContextCompat.getColor(context, R.color.colorlistviewroweven));
        } else {
            view.setBackgroundColor(ContextCompat.getColor(context, R.color.colorlistviewrowodd));
        }
        return view;
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        TextView textviewaislename = (TextView) view.findViewById(R.id.aisle_name_entry);
        TextView textviewaisleorder = (TextView) view.findViewById(R.id.aisle_order_entry);

        textviewaislename.setText(cursor.getString(ShopperDBHelper.AISLES_COLUMN_NAME_INDEX));
        textviewaisleorder.setText(cursor.getString(ShopperDBHelper.AISLES_COLUMN_ORDER_INDEX));

    }
    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        return LayoutInflater.from(context).inflate(R.layout.activity_aisle_list_entry, parent, false);
    }
}

请注意! getView 方法不是必需的。在这里,它用于交替背景颜色。另外 ShopperDBHelper。?????? _ ORDER 等于数据库游标中相应列的偏移量。膨胀的布局( R.layout.activity_aisle_list_entry )是第二个布局(如上所述)。

通过创建数据库游标,使用数据库游标创建适配器实例,然后将ListView设置为使用该适配器,可以在相应的活动中将它们绑定在一起。 : -

        Cursor aislescsr = shopperdb.getAislesPerShopAsCursor(csr.getInt(ShopperDBHelper.SHOPS_COLUMNN_ID_INDEX));
        ListView lv = (ListView) findViewById(R.id.aislelist_listview);
        AislesCursorAdapter aisleadapter = new AislesCursorAdapter(lv.getContext(), aislescsr, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
        lv.setAdapter(aisleadapter);

对于可点击的图像,您可以将其添加到条目布局中,并将onClick属性设置为活动中方法的名称(不是唯一的wau,但可能是最简单的)。例如(这是针对TextView而不是图像): -

        <TextView
            android:id="@+id/shoppinglist_deletebutton"
            android:layout_width="@dimen/standard_dummy_size"
            android:layout_height="@dimen/shoppinglist_listview_button_height"
            android:layout_weight="0.05"
            android:singleLine="true"
            android:text="@string/standarddeletetext"
            android:gravity="center"
            android:textSize="@dimen/standard_subsubsubheading_text_size"
            android:textStyle="bold"
            android:background="@color/colorRequiredLabel"
            android:textColor="@color/colorNormalButtonText"
            android:onClick="sledelete"/>

以下是相应的 sledelete 方法: -

public void sledelete(View view) {
        Integer tag = (Integer)view.getTag();
        shoppinglistcsr.moveToPosition(tag);
        shopperdb.setShopListEntryAsComplete(shoppinglistcsr.getLong(0));
        shoppinglistcsr = shopperdb.getShoppingList();
        currentsla.swapCursor(shoppinglistcsr);
    }

请注意!该方法只传递视图,重要的是不是位置。因此getTag(标签设置在adpter中的位置,示例如下)。请注意,最后2行刷新Listview,即从DB获取新光标,然后交换到新光标(您还可以使用changeCursor和onNotifyDataSetChanged)。

这是适配器中的标签设置代码。这是在 bindView 方法中(并设置3个TextViews的标签): -

public void bindView(View view,Context context, Cursor cursor) {
    int pos = cursor.getPosition();
.........
    donebtntv.setTag(pos);
    deletebtntv.setTag(pos);
    replacebtntv.setTag(pos); 

或者你可以在getView方法中设置这个标签,该方法有一个位置传递给它(所以你不需要int pos = cursor.getPosition