>>分享Android开发相关的技术 书籍支持  卫琴直播  品书摘要  在线测试  资源下载  联系我们
发表一个新主题 开启一个新投票 回复文章 您是本文章第 24170 个阅读者 刷新本主题
 * 贴子主题:  Android ListView与SQLite综合使用(水果商品展示案例) 回复文章 点赞(0)  收藏  
作者:日月光华    发表时间:2024-04-14 02:55:23     消息  查看  搜索  好友  邮件  复制  引用

Android ListView与SQLite综合使用(水果商品展示案例)

首先,看一下主页面。

点击在新窗口中浏览原图
CTRL+鼠标滚轮放大或缩小
做一个类似这样的页面,点击+号,输入商品名称,金额,商品就会显示在下面的ListView上,数据是从数据库中获取的。

1、我们先把页面做好。
<RelativeLayout 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"
                tools:context="com.bzu.cyz.fruitlistsqlite.MainActivity">

    <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">
        <EditText
                android:id="@+id/ed1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:hint="商品名称"/>
        <EditText
                android:id="@+id/ed2"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:hint="金额"/>
        <ImageView
                android:id="@+id/add"
                android:layout_width="wrap_content"
                android:layout_height="25dp"
                android:layout_weight="1"
                android:onClick="add"
                android:src="@drawable/add"/>
    </LinearLayout>

    <ListView
            android:id="@+id/list"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="30dp">

    </ListView>

</RelativeLayout>

2、然后是ListView的item页面


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="wrap_content"
    android:paddingBottom="3dp"
    android:paddingLeft="10dp"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/tv1"
        android:layout_margin="20dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="1"
        android:textSize="25dp"/>
    <TextView
        android:id="@+id/tv2"
        android:layout_margin="20dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="毛巾"
        android:layout_toRightOf="@+id/tv1"
        android:textSize="25dp"/>

    <TextView
        android:id="@+id/tv3"
        android:layout_margin="20dp"
        android:text="233"
        android:textSize="30dp"
        android:layout_toRightOf="@+id/tv2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

    <ImageView
        android:layout_toRightOf="@+id/tv3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:srcCompat="@android:drawable/arrow_up_float"
        android:id="@+id/iv1"
        android:layout_marginTop="22dp"
        android:layout_weight="1" />

    <ImageView
        android:layout_below="@+id/iv1"
        android:layout_toRightOf="@+id/tv3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:srcCompat="@android:drawable/arrow_down_float"
        android:id="@+id/iv2"
        android:layout_weight="0.17" />

    <ImageView
        android:onClick="delete"
        android:layout_margin="17dp"
        android:layout_toRightOf="@+id/iv1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:srcCompat="@android:drawable/ic_menu_delete"
        android:id="@+id/iv3"
        android:layout_weight="1" />
</RelativeLayout>

3、然后DbHelper类,创建数据库表。


public class DbHelper extends SQLiteOpenHelper {
    public DbHelper(Context context) {
        super(context, "fruit.db", null, 2);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        System.out.println("OnCreate");
        db.execSQL("Create TABLE fruit(id INTEGER PRIMARY KEY AUTOINCREMENT,name VARCHAR(20), balance INTEGER)");
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
        System.out.println("OnUpgrade");
    }
}

继承SQLiteOpenHelper,重写下面2个方法。

4、实体类Fruit。


public class Fruit  {
    private Long id;
    private String name;
    private int balance;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getBalance() {
        return balance;
    }

    public void setBalance(int balance) {
        this.balance = balance;
    }

    public Fruit(Long id, String name, int balance) {
        super();
        this.id = id;
        this.name = name;
        this.balance = balance;
    }

    public Fruit(String name, int balance) {
        super();
        this.name = name;
        this.balance = balance;
    }

    public Fruit() {
        super();
    }
}

5、对数据库操作类FruitDao


public class FruitDao {
    private DbHelper dbHelper;

    public FruitDao(Context context) {
        dbHelper =new DbHelper(context);
    }
    public void insert(Fruit fruit){
        SQLiteDatabase db =dbHelper.getWritableDatabase();
        ContentValues values =new ContentValues();
        values.put("name",fruit.getName());
        values.put("balance",fruit.getBalance());
        long id = db.insert("fruit",null,values);
        fruit.setId(id);
        db.close();
    }
    //根据id删除数据
    public  int delete(long id){
        SQLiteDatabase db =dbHelper.getWritableDatabase();
        int count=db.delete("fruit","id=?",new String[]{id+""});
        db.close();
        return count;
    }
    public List<Fruit> getAll(){
        SQLiteDatabase db =dbHelper.getReadableDatabase();
        Cursor c =db.query("fruit",null,null,null,null,null,"balance DESC");
        List<Fruit> list =new ArrayList<>();
        while (c.moveToNext()){
            long id =c.getLong(c.getColumnIndex("id"));
            String name = c.getString(1);
            int balance =c.getInt(2);
            list.add(new Fruit(id,name,balance));
        }
        c.close();
        db.close();
        return list;
    }
}

6、如果要把数据显示在ListView上,还要自定义一个适配器FruitAdapter


public class FruitAdapter extends ArrayAdapter<Fruit> {
    private int resourceID;
    public FruitAdapter(Context context, int resource, List<Fruit> objects) {
        super(context, resource, objects);
        resourceID =resource;

    }
    @NonNull
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Fruit fruit = getItem(position);
        View view= LayoutInflater.from(getContext()).inflate(resourceID,null);
        TextView tv_id = (TextView) view.findViewById(R.id.tv1);
        TextView tv_name = (TextView) view.findViewById(R.id.tv2);
        TextView tv_price = (TextView) view.findViewById(R.id.tv3);
        ImageView imageView1 = (ImageView) view.findViewById(R.id.iv1);
        ImageView imageView2 = (ImageView) view.findViewById(R.id.iv2);
        ImageView imageView3 = (ImageView) view.findViewById(R.id.iv3);
        tv_id.setText(fruit.getId()+"");
        tv_name.setText(fruit.getName());
        tv_price.setText(fruit.getBalance()+"");
        return view;
    }
}

7、最后是MainActivity中

public class MainActivity extends AppCompatActivity {
    private List<Fruit> list;
    private FruitDao fruidao;
    private EditText eName;
    private EditText eBalance;
    private ListView listView;
    private FruitAdapter fruitAdapter;
    private  Fruit f;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        fruidao =new FruitDao(this);
        list=fruidao.getAll();
        fruitAdapter =new FruitAdapter(this,R.layout.list_item,list);
        listView.setAdapter(fruitAdapter);
    }

    private void initView() {
        listView = (ListView) findViewById(R.id.list);
        eName = (EditText) findViewById(R.id.ed1);
        eBalance = (EditText) findViewById(R.id.ed2);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Fruit   fruit = (Fruit) adapterView.getItemAtPosition(i);

            }
        });


    }
    public void add(View view){
        String name =eName.getText().toString();
        String balance = eBalance.getText().toString();
        f =new Fruit(name,balance.equals("")?0:Integer.parseInt(balance));
        fruidao.insert(f);
        list.add(f);
        fruitAdapter.notifyDataSetChanged();
    }


}

现在添加一条就可以在ListView中显示了 。
————————————————
版权声明:本文为CSDN博主「Zander_Chen」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/chen185597989/article/details/70650034



程序猿的技术大观园:www.javathinker.net
  Java面向对象编程-->Java语言中的修饰符
  JavaWeb开发-->Web运作原理(Ⅳ)
  JSP与Hibernate开发-->第一个helloapp应用
  Java网络编程-->用Spring整合CXF发布Web服务
  精通Spring-->通过Vuex进行状态管理
  Vue3开发-->Vue组件开发高级技术
  android 自动化测试之MonkeyRunner学习
  Android中Activity之间的通信
  编译Irrlicht On Android
  Android 滚动Tab
  Android的Service和广播的讲解
  Android DownloadManager用法举例
  Android定义的路径全局变量
  Android 使用SQLite数据库
  众多Android 开源项目推荐
  Android 消息推送
  Android多线程断点续传
  android 如何监听自身应用被卸载
  Android 自定义九宫格手势锁
  Android 架构
  Android 判断当前设备是手机还是平板
  更多...
 IPIP: 已设置保密
树形列表:   
[url=https://www.1686990.c... 发货33 2024-04-14 02:55:23
[url=http://www.zhent.com]... nihaosb 2024-04-14 02:55:23
1页 2条记录 当前第1
发表一个新主题 开启一个新投票 回复文章


中文版权所有: JavaThinker技术网站 Copyright 2016-2026 沪ICP备16029593号-2
荟萃Java程序员智慧的结晶,分享交流Java前沿技术。  联系我们
如有技术文章涉及侵权,请与本站管理员联系。