How does Android Studio get SQLite data and display it on ListView

  • 2021-11-29 08:36:16
  • OfStack

When we use ListView, we need to bind with data, so the problem comes, how to get the data in SQLite database and dynamically display it to ListView? In fact, the process is very simple: first, get SQLite data (of course, first you have to create an SQLite database and fill in some data), then introduce ListView control, and finally bind the data with ListView.

1 Get the data in the SQLite database

SQLite is a lightweight database, it can save data to your phone, but the disadvantage is 1 software uninstall all data will be destroyed. Therefore, we should use it selectively according to our own project needs. The following will demonstrate extracting the data from SQLite.

First, define a class to instantiate the database


public class initdate {
  public Bitmap bitmap;
  public String content;
  public String data;
  public initdate (Bitmap bitmap ,String context,String time){
    this.bitmap =bitmap;
    this.content =context;
    this.data =time;
  }
}

Create 1 List object to store data

List < initdate > list = new ArrayList < > ();

Get the data of the corresponding table in SQLite


 DBOpenHelper helper = new DBOpenHelper(getActivity(), " Name of the database ", null, 1);// Create an object 
    SQLiteDatabase db = helper.getWritableDatabase();
    Cursor c = db.query(" Table name ", null, null, null, null, null, null);
    if (c != null && c.getCount() >= 1) {
      while (c.moveToNext()) {
        list.add(new initdate(base64ToBitmap(c.getString(c.getColumnIndex(" Field name 1"))), c.getString(c.getColumnIndex(" Field name 2")),
            c.getString(c.getColumnIndex(" Field name 3"))));
      }
      c.close();
      db.close();// Close the database 
    }

The base64ToBitmap method is used to convert an String type to an Bitmap


 public static Bitmap base64ToBitmap(String base64info) {
    byte[] bytes = Base64.decode(base64info, Base64.DEFAULT);
    return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
  }

2 Introducing ListView control

The introduction of ListView is relatively simple, we can directly drag the ListView control into the xml file. There is not much introduction here


 <ListView
    android:id="@+id/lv_expense"
    style="@style/Animation.AppCompat.DropDownUp"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>

3 Bind data to ListView

First, the acquired data is stored in the map object through a loop


 for (int i = 0; i < list.size(); i++) {
      Map<String, Object> map = new HashMap<String, Object>();
      map.put("image", list.get(i).bitmap);
      map.put("category", list.get(i).content);
      map.put("money", list.get(i).data);
      listitem.add(map);
    }

    SimpleAdapter adapter = new SimpleAdapter(getActivity()
        , listitem
        , R.layout.fragment_one_item
        , new String[]{"category", "money", "image"}
        , new int[]{R.id.tv_expense_category, R.id.tv_expense_money, R.id.image_expense});
   
    ListView listView = (ListView) v.findViewById(R.id.lv_expense);
    listView.setAdapter(adapter);

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {// Set up the listener 
      @Override
      public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Map<String, Object> map = (Map<String, Object>) parent.getItemAtPosition(position);
        Toast.makeText(getActivity(), map.get("category").toString(), Toast.LENGTH_LONG).show();
      }
    });

fragment_one_item.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">

  <ImageView
    android:id="@+id/image_expense"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:paddingTop="10dp"
    android:paddingRight="10dp"
    android:paddingBottom="10dp"
    android:adjustViewBounds="true"
    android:maxWidth="72dp"
    android:maxHeight="72dp"/>
  <TextView
    android:id="@+id/tv_expense_category"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:padding="10dp"/>
  <TextView
    android:id="@+id/tv_expense_money"
    android:layout_width="wrap_content"
    android:layout_height="40dp"
    android:text="100yuan"/>
</LinearLayout>

At this time, we have bound the acquired data with ListView, and we can run it directly, and find that all other information is displayed normally except small photos. This is due to SimpleAdapter By default, the image resources displayed by the adapter are all local resources in the program, that is, they can pass R.drawable If we want to display the Bitmap type pictures obtained from the database to ListView, we must implement it ourselves ViewBinder() This interface defines the matching relationship between data and view.


 for (int i = 0; i < list.size(); i++) {
      Map<String, Object> map = new HashMap<String, Object>();
      map.put("image_expense", list.get(i).bitmap);
      map.put("expense_category", list.get(i).content);
      map.put("expense_money", list.get(i).data);
      listitem.add(map);
    }
     SimpleAdapter adapter = new SimpleAdapter(getActivity()
        , listitem
        , R.layout.fragment_one_item
        , new String[]{"expense_category", "expense_money", "image_expense"}
        , new int[]{R.id.tv_expense_category, R.id.tv_expense_money, R.id.image_expense});
    adapter.setViewBinder(new SimpleAdapter.ViewBinder() {

      @Override
      public boolean setViewValue(View view, Object data,
                    String textRepresentation) {
        if ((view instanceof ImageView) & (data instanceof Bitmap)) {
          ImageView iv = (ImageView) view;
          Bitmap bm = (Bitmap) data;
          iv.setImageBitmap(bm);
          return true;
        }
        return false;
      }
    });
    ListView listView = (ListView) v.findViewById(R.id.lv_expense);
    listView.setAdapter(adapter);

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {// Set up the listener 
      @Override
      public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Map<String, Object> map = (Map<String, Object>) parent.getItemAtPosition(position);
        Toast.makeText(getActivity(), map.get("expense_category").toString(), Toast.LENGTH_LONG).show();
      }
    });

At this time, photo resources can also be displayed normally.

Summarize


Related articles: