1. 程式人生 > >從資料庫裡查詢資料展示到listview上的案例

從資料庫裡查詢資料展示到listview上的案例

編寫一個從資料庫裡查詢資料展示到listview上的案例

執行結果:點選find按鈕,會將資料庫中新增的資料顯示在List View上

結果如下:


建立如圖所示:


程式碼如下:

PersonAdapter

package cn.edu.bzu.datashow.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import 
android.widget.TextView; import java.util.List; import cn.edu.bzu.datashow.R; import cn.edu.bzu.datashow.entity.Person; public class PersonAdapter extends ArrayAdapter<Person> { private int resourceId; public PersonAdapter(Context context, int textViewResourceId, List<Person> objects) { super
(context, textViewResourceId, objects); resourceId = textViewResourceId; } @Override public View getView(int position, View convertView, ViewGroup parent) { Person person= getItem(position); View view; ViewHolder viewHolder; if (convertView == null) { //任務 補充完整
view = LayoutInflater.from(getContext()).inflate(resourceId, null); viewHolder = new ViewHolder(); viewHolder.tvName = (TextView) view.findViewById(R.id.tvName); viewHolder.tvPhone = (TextView) view.findViewById(R.id.tvPhone); view.setTag(viewHolder); } else { view = convertView; viewHolder = (ViewHolder) view.getTag(); } viewHolder.tvName.setText(person.getName()); viewHolder.tvPhone.setText(person.getPhone()); return view; } class ViewHolder { TextView tvName; TextView tvPhone; } }

PersonDao:

package cn.edu.bzu.datashow.dao;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import java.util.ArrayList;
import java.util.List;

import cn.edu.bzu.datashow.db.PersonDBHelper;
import cn.edu.bzu.datashow.entity.Person;
/**
 * Created by fengj on 2017/5/10.
 */
public class PersonDao {
    private PersonDBHelper personDBHelper;
    public PersonDao(Context context){
        personDBHelper=new PersonDBHelper(context);
    }
    public void add(Person person){
        SQLiteDatabase sqLiteDatabase=personDBHelper.getWritableDatabase();
        ContentValues contentValues=new ContentValues();
        contentValues.put("name",person.getName());
        contentValues.put("phone",person.getPhone());
        sqLiteDatabase.insert("info",null,contentValues);
    }
    public List<Person> getPersons(){
        //任務 完成查詢所有資料的方法
List<Person> persons=new ArrayList<Person>();
        SQLiteDatabase sqLiteDatabase=personDBHelper.getWritableDatabase();
        Cursor cursor=sqLiteDatabase.query("info",null,null,null,null,null,null);
        while(cursor.moveToNext()){
           int id= cursor.getInt(cursor.getColumnIndex("_id"));
            String name=cursor.getString(cursor.getColumnIndex("name"));
            String phone=cursor.getString(cursor.getColumnIndex("phone"));
            Person person=new Person(name,phone);
            person.setId(id);
            persons.add(person);
        }
        return persons;
    }
}
 
PersonDBHelper:
package cn.edu.bzu.datashow.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

/**
 * Created by fengj on 2017/5/10.
 */
//任務:修正問題
public class PersonDBHelper extends SQLiteOpenHelper {
    //資料庫的名稱為person.db ,資料庫的版本為1
public PersonDBHelper(Context context) {
        super(context,"person.db", null, 1);
    }

    @Override
public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table info(_id integer primary key,name varchar(20),phone varchar(20))");
    }

    @Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
}
 
MainActivity:
package cn.edu.bzu.datashow;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ListView;

import java.util.List;

import cn.edu.bzu.datashow.adapter.PersonAdapter;
import cn.edu.bzu.datashow.dao.PersonDao;
import cn.edu.bzu.datashow.entity.Person;

public class MainActivity extends AppCompatActivity {
    private PersonDao personDao;
    private ListView lvPersons;
    @Override
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        lvPersons= (ListView) findViewById(R.id.lvPersons);
        personDao=new PersonDao(this);
        personDao.add(new Person("張三","13476089006"));
        personDao.add(new Person("李四","13476089008"));
    }

    public void find(View view){
        //任務 查詢資料庫中的所有person,顯示在列表中
List<Person> persons=personDao.getPersons();
        PersonAdapter personAdapter=new PersonAdapter(this,R.layout.item,persons);
        lvPersons.setAdapter(personAdapter);


    }
}
Activity-main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
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"
android:orientation="vertical"
tools:context="cn.edu.bzu.datashow.MainActivity">

    <ListView
android:id="@+id/lvPersons"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="@color/colorPrimary"
android:layout_weight="1"
/>

    <Button
android:text="Find"
android:layout_gravity="center_horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/lvPersons"
android:onClick="find"
android:id="@+id/btnFind" />
</LinearLayout>
 
item.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_shop"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="vertical"
>
    <TextViewandroid:text="名字"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/tvName"
android:textSize="24sp"
/>

    <TextViewandroid:text="電話"
android:layout_marginTop="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="18sp"
android:id="@+id/tvPhone"
/>
</LinearLayout>
執行出來就好啦!

相關推薦

資料庫查詢資料展示listview案例

編寫一個從資料庫裡查詢資料展示到listview上的案例 執行結果:點選find按鈕,會將資料庫中新增的資料顯示在List View上 結果如下: 建立如圖所示: 程式碼如下: Perso

資料庫查詢資料並顯示到datagridview中的兩種方法

第一種方法:利用SqlDataAdapter的Fill()方法,                      優點:可以不用考慮資料庫表中每一列的資料型別,將資料一次性匯入到表中;                      缺點:不能在查詢過程中編輯查詢的資料 strin

破解微信資料庫查詢資料傳伺服器

            Cursor c1 = db.rawQuery("select * from rcontact where username not like 'gh_%' and verifyFlag<>24 and verifyFlag<>29 and verifyFlag

資料庫取到資料轉換json後,時間格式帶T的解決辦法

從資料庫取得資料之後,轉換成json顯示在前臺,在轉換json時發現yyyy-MM-dd HH:mm:ss格式的日期變成了yyyy-MM-ddTHH:mm:ss, 日與小時之間多出個T字元.這是因為 Newtonsoft.Json轉換json導致的; Newtonsoft.Json產生的預設日期時間

Android實現一個簡單的天氣預報APP(八) 資料庫讀取城市資料

學習參考資源:https://www.gitbook.com/book/zhangqx/mini-weather/details 前面我們已經實現了今日天氣的主介面佈局,並可以從網路上實時獲取天氣資料更新到介面上,並通過按鈕切入選擇城市介面。接下來,我們通過讀取資料庫檔案獲

Winform中listView控制元件資料庫中新增資料的方法

繫結資料庫資料到listview中,有兩種方式 第一種:使用SqlDateReader public void BindData() {//連線資料庫string strcon="server=.;database=student;uid=sa;pwd=123456;";S

php將資料庫取出的資料分為6個一組的二維陣列

$presell = M('presell')->field('id,sname,num,weight,shop_price,endtime,supply,givetime')->where($info)->order('id desc')->select(); &nbs

SQL與eclipse的連線,資料庫讀取表資料,將二維陣列資料匯入表

示例: import java.util.List; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; impor

專案總結:每隔5分鐘資料庫拉取資料轉為Json格式通過WebService客戶端傳送至服務端

   第一次接手需求寫的小專案,過程也有點坎坷,以此記錄總結編碼過程中遇到的問題。    專案背景:本次寫的是一個小模組,主要為客戶端,作用是每隔5分鐘從資料庫拉取資料傳送至服務端。本次專案採用的是spring3+Quartz+JdbcTemplate+J

html頁面做迴圈輸出標籤,將資料庫中的資料展示在頁面上

頁面是html頁面.只是其中兩塊div.我用到了跨庫查詢. 注:我後臺傳值,頁面未顯示資料.我後臺不傳值,只定義空的方法,不傳引數.頁面可顯示資料. dao層的方法我是這麼定義的. public List<Cars> queryByNew(); service層: p

介面測試: 用Jmeter資料庫獲取測試資料, 作為下一個介面引數方法

現在有一個需求,從資料庫tieba_info表查出rank小於某個值的username和count(*),然後把所有查出來的username和count(*)作為引數值,用於下一個介面。 (資料庫連線配置,請參考我的另外一篇博文jmeter測試mysql資料庫之JDBC請求https://blo

thinkphp 3.2連結Oracle資料庫查詢資料

ennnn,換工作了,開始用新的東西了,最近就是呼叫nc介面,資料庫是Oracle,首先先把資料查出來,這個比較簡單。 在網上看的其他的方法都是改資料庫配置檔案,然後需要修改tp核心的一個類檔案,比較繁瑣, 現在教你一個超級簡單的方法,不需要改任何地方,自己寫就行了 public function

通過JDBC連線資料庫再向資料庫錄入資料

一  首先第一步我們現在資料庫裡建立一張examstudent空表: 二 接著對應著表裡內容建立一個學生類: package com.atguigu.jdbc; public class Student { // 流水號 private int flowId;

實現銀行家演算法和先進先出演算法_檔案資料

作業系統考試老師出了兩道題,一個是先進先出,另一個是銀行家演算法,題目如下 1.請使用FCFS演算法模擬程序排程。假設系統有n (n>=2) 個程序,給定程序的到達時間以及需要執行的時間長短,給出相應的執行順序。資料以檔案方式給出,檔名為data.fcfs,格式為: 檔案共n(N1…Nn)

如何資料庫服務讀取資料

1:背景    在從資料庫服務data讀取(以下簡稱data)之前,首先需要確保自己的服務(假設服務名為fegin-demo)是正常能向Eureka註冊中心註冊的,註冊步驟如下: 將 src/main

資料庫中匯出資料成Dataframe格式兩種方法效率比較

方法1: import pymysql import pandas as pd import time import xlrd first = time.time() #在資料庫中操作150s,在python中操作320s #方法1 con = pymysql.connect(host="

Prefuse學習(二)資料庫中讀取資料

prefuse是一個非常不錯的開源視覺化專案,尤其是用在social network/complex network上,個人感覺要比jung好。不過可惜的是,prefuse的user manual還在建

採用Redis統計客戶端線上使用者——redis-server獲取資料展示到html頁面

var dom = document.getElementById("container"); var myChart = echarts.init(dom); var app = {}; option = null; option = {

1.簡單例項:ASP.NET下Echarts通過Ajax資料庫中獲取資料

後臺:Test01.ashx.cs:從資料庫獲取資料,通過HTTP請求(HttpContext)實現和前臺資料傳遞json資料 using System; using System.Collections.Generic; using System.Linq; using

ASP.NET+Echarts+Ajax資料庫中獲取資料

html <div class="panel-body"> <div id="signNum" style="height: 400px; width: