AS如何从资产数据库文件

时间:2017-02-21 01:44:10

标签: android listview android-fragments

我想问一下OnClickListener。我在listview中调用了外部数据库文件[assets folder]。我想在listview中的每个项目上设置onClicklistener。当listview项目点击时,想要出现一个带有数据字段的小片段。我尝试了很多来源但仍无法正常工作。

这是想要做的示例片段。 enter image description here

这是数据库结构。 enter image description here

这是DatabaseHelper.java

package com.example.arlequina.sqlitefromassetexample.database;

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

import com.example.arlequina.sqlitefromassetexample.model.Product;

import java.util.ArrayList;
import java.util.List;
import java.sql.Blob;

/**
 * Created by ARLEQUINA on 2/10/2017.
 */

public class DatabaseHelper extends SQLiteOpenHelper {
    public static final String dbname = "sample.db";
    public static final String dblocation = "/data/data/com.example.arlequina.sqlitefromassetexample/databases/";
    private Context mContext;
    private SQLiteDatabase mDatabase;

    public DatabaseHelper(Context context){
        super(context, dbname, null, 1);
        this.mContext = context;
    }
    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {

    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

    }
    public void openDatabase(){
        String dbPath = mContext.getDatabasePath(dbname).getPath();
        if(mDatabase != null && mDatabase.isOpen()){
            return;
        }
        mDatabase = SQLiteDatabase.openDatabase(dbPath, null, SQLiteDatabase.OPEN_READWRITE);
    }
    public void closeDatabase(){
        if(mDatabase != null){
            mDatabase.close();
        }
    }
    public List<Product> getListProduct(){
        Product product = null;
        List<Product> productList = new ArrayList<>();
        openDatabase();
        Cursor cursor = mDatabase.rawQuery(" SELECT * FROM Product ", null);
        cursor.moveToFirst();
        while(!cursor.isAfterLast()){
            product = new Product(cursor.getInt(0), cursor.getString(1), cursor.getString(2),cursor.getString(3));
            productList.add(product);
            cursor.moveToNext();
        }
        cursor.close();
        closeDatabase();
        return productList;
    }
}

这是ListProductAdapter.java

package com.example.arlequina.sqlitefromassetexample.adapter;

import android.content.Context;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.arlequina.sqlitefromassetexample.R;
import com.example.arlequina.sqlitefromassetexample.model.Product;

import org.w3c.dom.Text;

import java.util.List;

/**
 * Created by ARLEQUINA on 2/10/2017.
 */

public class ListProductAdapter extends BaseAdapter{
    private Context mContext;
    private List<Product> mProductList;

    public ListProductAdapter(Context mContext, List<Product> mProductList){
        this.mContext = mContext;
        this.mProductList = mProductList;
    }

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

    @Override
    public Object getItem(int position) {
        return mProductList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return mProductList.get(position).getId();
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public View getView(int position, View view, ViewGroup viewGroup) {
        View v = View.inflate(mContext, R.layout.item_listview, null);
        TextView tvName = (TextView)v.findViewById(R.id.tv_product_name);
        TextView tvPrice = (TextView)v.findViewById(R.id.tv_product_price);
        TextView tvDesc = (TextView)v.findViewById(R.id.tv_product_desc);
        //ImageView tvImage = (ImageView)v.findViewById(R.id.tv_product_img);
        tvName.setText(mProductList.get(position).getName());
        tvPrice.setText(String.valueOf(mProductList.get(position).getPrice()) + " $");
        tvDesc.setText(mProductList.get(position).getDesc());
       // tvImage.setImageIcon(mProductList.get(position).getImage());
        return v;
    }
}

这是MainActivity

package com.example.arlequina.sqlitefromassetexample;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.arlequina.sqlitefromassetexample.adapter.ListProductAdapter;
import com.example.arlequina.sqlitefromassetexample.database.DatabaseHelper;
import com.example.arlequina.sqlitefromassetexample.model.Product;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

/**
 * Created by ARLEQUINA on 2/10/2017.
 */

public class MainActivity extends Activity {
    private ListView lvProduct;
    private ListProductAdapter adapter;
    private List<Product> mProductList;
    private DatabaseHelper mDBHelper;

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

        setContentView(R.layout.activity_main);
        lvProduct = (ListView)findViewById(R.id.listview_product);
        mDBHelper = new DatabaseHelper(this);
        //Check exists database
        File database = getApplicationContext().getDatabasePath(DatabaseHelper.dbname);
        if(false == database.exists()){
            mDBHelper.getReadableDatabase();

            //Copy db
            if(copyDatabase(this)){
                Toast.makeText(this,"Copy database success", Toast.LENGTH_SHORT).show();
            }else{
                Toast.makeText(this, "Copy data error", Toast.LENGTH_SHORT).show();
                return;
            }
        }
        //Get product list in db when db exists
        mProductList = mDBHelper.getListProduct();
        //Init adapter
        adapter  = new ListProductAdapter(this,mProductList);
        //Set adapter for listview
        lvProduct.setAdapter(adapter);




    }
    private boolean copyDatabase(Context context){
        try{
            InputStream inputStream =  context.getAssets().open(DatabaseHelper.dbname);
            String outFileName = DatabaseHelper.dblocation + DatabaseHelper.dbname;
            OutputStream outputStream = new FileOutputStream(outFileName);
            byte[] buff = new byte[1024];
            int length = 0;
            while((length = inputStream.read(buff)) > 0){
                outputStream.write(buff, 0, length);
            }
            outputStream.flush();
            outputStream.close();
            Log.v("MainActivity", "DB copied");
            return true;
        } catch(Exception e){
            e.printStackTrace();
            return false;
        }
    }
}

item_listview.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ffffff"
    android:paddingBottom="5dp"
    android:paddingLeft="10dp"
    android:paddingRight="10dp"
    android:paddingTop="5dp">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/tv_product_name"
        android:text = "Name"
        android:textColor="#4bb6d6"
        android:textSize="20dp"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id = "@+id/tv_product_price"
        android:text="100$"
        android:textColor="#b30000"
        android:textSize="18dp"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id = "@+id/tv_product_desc"
        android:text="Description"
        android:textSize="16dp"
        android:textStyle="italic"/>
</LinearLayout>

activity_main.xml中

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

    <ListView
        android:id = "@+id/listview_product"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="10dp"
        android:divider="#d1d1d1"
        android:dividerHeight="10dp"></ListView>
</LinearLayout>

Product.java

package com.example.arlequina.sqlitefromassetexample.model;

import java.sql.Blob;

/**
 * Created by ARLEQUINA on 2/10/2017.
 */

public class Product {

    private int id;
    private String name;
    private String price;
    private String desc;
    //private Blob img;

    public Product(int id, String name, String price, String desc){
        this.id = id;
        this.name = name;
        this.price = price;
        this.desc = desc;
        //this.img = img;
    }

    public int getId(){
        return id;
    }
    public void setId(int id){
        this.id = id;
    }
    public String getName(){
        return name;
    }
    public void setName(String name){
        this.name = name;
    }
    public String getPrice(){
        return price;
    }
    public void setPrice(String price){
        this.price = price;
    }
    public String getDesc(){
        return desc;
    }
    public void setDesc(String desc){
        this.desc = desc;
    }

}

2 个答案:

答案 0 :(得分:0)

您可以使用ImportantSpecies = which(hyp > quantile(hyp, 0.75) plot(mds$points[ImportantSpecies,1], mds$point[ImportantSpecies,2]) arrows(0, 0, mds$species[ImportantSpecies,1], mds$species[ImportantSpecies,2], col = "grey50") listview.setOnItemClickListener来解决您的问题。这是最基本的人。

答案 1 :(得分:0)

由于您的问题是使您的列表项可以点击,您可以在活动中的init listview之后使用它。

lvProduct.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

    }
});

position是列表中单击项目的位置。因此,您可以使用mProductList.get(position)

获取该项目

您可以获得该项目后,现在是时候展示您的项目了。您可以使用custom dialog使其像演示一样(因为您必须再创建1个xml):

在此官方链接中查看自定义对话框部分:https://developer.android.com/guide/topics/ui/dialogs.html