简体   繁体   English

有没有一种方法可以通过使用listview显示所有sqlite表和内容?

[英]Is there a way of displaying all sqlite tables and contents by using listview?

I made a little tool for getting all information from database at runtime. 我制作了一个用于在运行时从数据库获取所有信息的小工具。 Here is my code: 这是我的代码:

package com.example.helix.whiffs; 包com.example.helix.whiffs;

import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.PopupMenu;
import android.widget.TextView;

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

public class FragmentDatabase extends Fragment{

    private final String LOG_TAG = "FRAGMENTDATABASE";

    DatabaseListener listener;

    int rowHeight = 40;
    String text;

    Button select;
    TextView counter;
    LinearLayout titleBar;
    LinearLayout dataList;
    PopupMenu popup;

    String[] fields;
    int[] colWidths;
    List<String> data;
    HashMap<Integer, String[]> dataItems;
    HashMap<Integer, String> menuItems;

    DBAdapter db;
    public interface DatabaseListener{
        void onload(String table);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        View v = inflater.inflate(R.layout.fragment_database, container, false);
        select = (Button)v.findViewById(R.id.select);
        counter = (TextView)v.findViewById(R.id.count);
        titleBar = (LinearLayout)v.findViewById(R.id.titles);
        dataList = (LinearLayout) v.findViewById(R.id.list);

        data = new ArrayList<>();
        menuItems = new HashMap<>();
        dataItems = new HashMap<>();

        db = new DBAdapter(getActivity().getApplicationContext());
        data = db.allTables();

        popup = new PopupMenu(getActivity().getApplicationContext(), select);
        for(int i = 0; i < data.size(); i++) {
            popup.getMenu().add(Menu.NONE, i, i, data.get(i));
            menuItems.put(i, data.get(i));
        }

        popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem menuItem) {
                dataList.removeAllViews();
                titleBar.removeAllViews();
                dataItems.clear();

                int itemId = menuItem.getItemId();
                String table = menuItems.get(itemId);
                fields = db.allFields(table);
                TextView idField = new TextView(getActivity().getApplicationContext());
                idField.setText(fields[0]);
                titleBar.addView(idField);
                colWidths = new int[fields.length];
                colWidths[0] = 80;
                for(int i = 1; i < fields.length; i++){
                    colWidths[i] = 200;
                    TextView f = new TextView(getActivity().getApplicationContext());
                    String text = fields[i];
                    f.setText(text);
                    titleBar.addView(f);
                }

                dataItems = db.allValues(table);
                counter.setText(String.valueOf(dataItems.size()));

                for(int i = 0; i < dataItems.size(); i++){

                    LinearLayout row = new LinearLayout(getActivity().getApplicationContext());
                    row.setOrientation(LinearLayout.HORIZONTAL);

                    String[] rowData = dataItems.get(i);

                    TextView idf = new TextView(getActivity().getApplicationContext());
                    if(rowData.length != 0) idf.setText(rowData[0]);
                    row.addView(idf);

                    for(int j = 1; j < rowData.length; j++){
                        TextView idf2 = new TextView(getActivity().getApplicationContext());
                        text = rowData[j];
                        row.addView(idf2);

                        if(text != null && text.length() > 9){
                            int length = 18 * text.length();
                            if(colWidths[j] < length) colWidths[j] = length;
                        }
                        idf2.setText(text);
                    }
                    dataList.addView(row);
                }

                for(int j = 0; j < colWidths.length; j++){
                    TextView tv = (TextView) titleBar.getChildAt(j);
                    ViewGroup.LayoutParams vlp = tv.getLayoutParams();
                    vlp.width = colWidths[j];
                    vlp.height = rowHeight;
                    tv.setLayoutParams(vlp);
                }
                for(int i = 0; i < dataItems.size(); i++){
                    LinearLayout rowLayout = (LinearLayout) dataList.getChildAt(i);
                    for(int j = 0; j < colWidths.length; j++){
                        TextView tv = (TextView) rowLayout.getChildAt(j);
                        ViewGroup.LayoutParams vlp = tv.getLayoutParams();
                        vlp.width = colWidths[j];
                        vlp.height = rowHeight;
                        tv.setLayoutParams(vlp);
                    }
                }
                return true;
            }
        });

        select.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popup.show();
            }
        });
        return v;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof FragmentDatabase.DatabaseListener) {
            listener = (FragmentDatabase.DatabaseListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement FragmentListener");
        }
    }

    @Override
    public void onDetach() {
        listener = null;
        super.onDetach();
    }
}

Here is important part of my database adapter: 这是我的数据库适配器的重要部分:

myDbHelper myhelper;

public List<String> allTables(){
        List<String> result = new ArrayList<>();
        SQLiteDatabase db = myhelper.getWritableDatabase();
        Cursor c = db.rawQuery("SELECT name FROM sqlite_master WHERE type = 'table'",null);
        if(c.moveToFirst()){
            while (!c.isAfterLast()){
                result.add(c.getString(0));
                c.moveToNext();
            }
        }
        return result;
    }

    public String[] allFields(String table){
        List<String> result = new ArrayList<>();
        SQLiteDatabase db = myhelper.getWritableDatabase();
        Cursor c = db.query(table, null, null, null, null, null, null);
        return c.getColumnNames();
    }

    public HashMap<Integer, String[]> allValues(String table) {
        HashMap<Integer, String[]> result = new HashMap<>();
        String[] row;

        SQLiteDatabase db = myhelper.getWritableDatabase();
        Cursor c = db.rawQuery("SELECT * FROM "+table, null);
        int columns = c.getColumnCount();
        if(c.moveToFirst()){
            int rowCount = 0;
            while(!c.isAfterLast()){
                row = new String[columns];
                for(int i = 0; i < columns; i++){
                    row[i] = c.getString(i);
                    Log.i(LOG_TAG, "Row add "+String.valueOf(c.getString(i)));
                }
                result.put(rowCount, row);
                rowCount ++;
                c.moveToNext();
            }
        }
        return result;
    }

static class myDbHelper extends SQLiteOpenHelper
    {
    private Context context;

        public myDbHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_Version);
            this.context=context;
            onCreate(this.getWritableDatabase());
        }
    }
}

And finally the layout file for fragment 最后是片段的布局文件

<?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="match_parent">
    <LinearLayout
        android:id="@+id/top_bar"
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:background="#888888"
        android:orientation="horizontal"
        >
        <Button
            android:id="@+id/select"
            android:layout_width="100dp"
            android:layout_height="match_parent"
            android:text="table"/>
        <TextView
            android:id="@+id/count"
            android:layout_width="100dp"
            android:layout_height="match_parent"
            android:text="total"
            android:textSize="24sp"
            android:gravity="center_horizontal"
            android:layout_marginTop="5dp"/>
    </LinearLayout>
    <HorizontalScrollView
        android:layout_below="@+id/top_bar"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            >
            <LinearLayout
                android:id="@+id/titles"
                android:background="#777777"
                android:layout_width="match_parent"
                android:layout_height="36dp"
                android:orientation="horizontal">
            </LinearLayout>
            <ScrollView
                android:layout_width="match_parent"
                android:layout_height="match_parent">
                <LinearLayout
                    android:id="@+id/list"
                    android:orientation="vertical"
                    android:layout_width="match_parent"
                    android:layout_height="0dp"
                    android:layout_weight="1">

                </LinearLayout>
            </ScrollView>
        </LinearLayout>
    </HorizontalScrollView>
</RelativeLayout>

This is all done manually (using nested LinearLayouts). 所有这些都是手动完成的(使用嵌套的LinearLayouts)。 Performance is very good on my Huawei p8. 我的华为p8的性能非常好。 If no list- or recyclerview option is not an option, perhaps this code might be useful for someone. 如果没有list-or recyclerview选项,则此代码可能对某人有用。

The answer is Yes as :- 答案是肯定的:-

I have a tool I call SQLiteInfoAssistant that is designed as a module and will display information and the underlying data for multiple database should they exist. 我有一个称为SQLiteInfoAssistant的工具,该工具被设计为模块,并且在存在多个数据库时将显示信息和基础数据。

The information is displayed in 3 ListView. 该信息显示在3 ListView中。 2 side by side at the top which initially display the Databases in the upper left view and tables in the selected database in the upper right view. 顶部并排显示2个,它们最初在左上方显示数据库,而在右上方显示所选数据库的表。

In this initial view various Database information is displayed in the bottom view. 在此初始视图中,各种数据库信息都显示在底部视图中。 eg The path along with various other information obtained via pragma's. 例如,路径以及通过编译指示获得的各种其他信息。

When a table is clicked, the tables for the database are then displayed in the upper left view and the columns in the upper right view. 单击表后,数据库的表将显示在左上方视图中,而列则显示在右上方视图中。 The lower view shows table information name, SQL used to create the table, column count and the count of columns in the primary key. 下部视图显示表信息名称,用于创建表的SQL,列数和主键中的列数。

In either of the above views long clicking a table will then display the actual data (blobs truncated and displayed as hex representation). 在以上任一视图中,长按一个表将显示实际数据(斑点被截断并显示为十六进制表示)。

Here's some screen shots:- 以下是一些屏幕截图:

Database and Tables 数据库和表

  • (note database testDB001 has been clicked as emptydb001 only has android_metadata) :- (注意数据库testDB001已被单击,因为emptydb001仅具有android_metadata):-

在此处输入图片说明

Table and Columns 表和列

在此处输入图片说明

Data in a Table 表中的数据

在此处输入图片说明

  • Can be scrolled horizontally and vertically. 可以水平和垂直滚动。

Invocation can be as simple as including the module, creating an instance of the SQLiteInformationAssistan t passing the context and then using the show method. 调用可以像包含模块一样简单,创建一个传递上下文SQLiteInformationAssistan实例,然后使用show方法。 However, many customisations can be made as can be seen by the comments in the following invocation code :- 但是,可以进行许多自定义,如以下调用代码中的注释所示:

private void tryitout() {
    // Get an SQLiteInformationAssistant instance
    // Note! the show method invokes the Activity
    SQLiteInformationAssistant SIA = new SQLiteInformationAssistant(this);

    // Instance customisation i.e set Display attributes
    //SIA.setBaseBackgroundColour(0xFFFFFFFF);
    //SIA.setHeadingTextColour(0xFFFFFF00);
    //SIA.setDatabaseListHeadingTextColour(0xFFFFFF00);
    //SIA.setTableListHeadingTextColour(0xFF0077FF);
    //SIA.setColumnListHeadingTextColour(0xFF77FF00);

    //SIA.setDatabaseListTextColour(0xFFFFFFFF);
    //SIA.setDatabaseInfoTextColour(0xFFFF0000);
    //SIA.setDatabaseListBackgroundColour(0xFFFFFF00);
    //SIA.setDatabaseInfoBackgroundColour(0xFFFFFF00);
    //SIA.setDatabaseInfoHeadingTextColour(0xFFFF0000);

    //SIA.setTableListTextColour(0xFFFF00FF);
    //SIA.setTableInfoTextcolour(0xFF0000FF);
    //SIA.setTableListBackgroundColour(0xFFFFFF00);
    //SIA.setTableInfoBackgroundColour(0xFFFFFF00);
    //SIA.setTableInfoHeadingTextColour(0xFFFF00FF);

    //SIA.setColumnListTextColour(0xFFFFFF00);
    //SIA.setColumnInfoTextColour(0xFF000000);
    //SIA.setColumnListBackgroundColour(0xFFFFFF00);
    //SIA.setColumnInfoBackgroundColour(0xFFFFFF00);
    //SIA.setColumnInfoHeadingTextColour(0xFF00FF00);

    //SIA.setStringCellBackgroundColour(0xFFEEEEEE);
    //SIA.setStringCellTextColour(0xFF0000FF);
    //SIA.setIntegerCellBackgroundColour(0xFFFF0000);
    //SIA.setIntegerCelltextColour(0XFFFFFFFF);
    //SIA.setDoubleCellBackgroundColour(0xFF00FFFF);
    //SIA.setDoubleCelltextColour(0XFF5555FF);
    //SIA.setBlobCellBackgroundColour(0xFF44FF55);
    //SIA.setBlobCelltextColour(0xFFFFFF00);
    //SIA.setUnkownCelltextColour(0xFFFFFF00);
    //SIA.setUnknownBackgroundCellColour(0xFFFF0000);
    // Note
    //SIA.setBytesToShowInBlob(128);
    SIA.show();
}

I haven't actually published this or made it available but if anyone is interested I can supply the code, this is mainly because I myself rarely use it as it's so easy to just copy a database into one of the freely available SQLite tools (Navicat, DB Browser for Sqlite, SQLite manager etc). 我实际上还没有发布它或使其可用,但是如果有人感兴趣,我可以提供代码,这主要是因为我自己很少使用它,因为将数据库复制到一个免费的SQLite工具(Navicat)中非常容易。 ,用于Sqlite的数据库浏览器,SQLite管理器等)。 The full code would probably be too large to post here though. 完整的代码可能太大,无法在此处发布。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM