java - 通过另一个类中的列表输出数据库信息 - Eclipse Android SQLite

标签 java android eclipse sqlite

我已经构建了 3 个类(class),1)tableStudents 2)DB 3)MainActivity

到目前为止,代码成功创建了一个数据库,并将给定的设置编码测试数据插入到数据库中。但是我不知道如何打印这些信息只是为了表明它确实已成功输入。

  • 我使用的是大学计算机,因此无法访问数据库文件

  • 在不检查文件的情况下,我尝试使用我编写的获取数据的方法输出列表,但我不确定如何将其物理输出为文本。

完整代码如下:

tableStudents.java

public class tableStudents {
     public String name, gender, password, course, modules;
        public int age;
    //Constructor
    public tableStudents()
    {

    }

     //constructor
    public tableStudents(String name, String gender, int age, String password, String course, String modules)
    {
        this.name = name;
        this.password = password;
        this.gender = gender;
        this.age = age;      
        this.course = course;
        this.modules = modules;
    }


    public static abstract class tableColumns implements BaseColumns
    {
        public static final String Student_ID= "Student_ID";
        public static final String Student_Name= "Student_Name";
        public static final String Student_Password = "Student_Password";
        public static final String Student_Gender = "gender";
        public static final String Student_Age = "age";
        public static final String Student_Course = "course";
        public static final String Modules = "modules";
        public static final String Database = "databasename";
        public static final String Table = "tablename";
    }


}

DB.java

public class DB extends SQLiteOpenHelper {
    public static final int db_version = 1;  
    public static final String Table = "Students";  
    public static final String Student_ID = "Student_ID";
    public static final String Student_Name = "Student_Name";
    public static final String Student_Password = "Student_Password";
    public static final String Student_Gender = "gender";
    public static final String Student_Age = "age";
    public static final String Student_Course = "course";
    public static final String Modules = "modules";
    public DB(Context context) {
        super(context, tableColumns.Database, null, db_version);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        //Create Table
        db.execSQL("CREATE TABLE " + Table + "(" + 
                Student_ID + " INTEGER PRIMARY KEY, " +
                Student_Name + " TEXT, " +
                Student_Password + " TEXT, " +
                Student_Gender + " TEXT, " +
                Student_Age + " INTEGER, " +
                Student_Course + " TEXT, " +
                Modules + " TEXT)");
        Log.d("DB", "DB Created");      
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + Table);
        onCreate(db);
    }

    public List<tableStudents> getData() {
        List<tableStudents> studentList = new ArrayList<tableStudents>();
        // Select All Query
        String selectQuery = "SELECT  * FROM " + Table;
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);
        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                tableStudents student = new tableStudents();
                student.name = cursor.getString(0);
                student.password = cursor.getString(1);
                student.gender = cursor.getString(2);
                student.age = Integer.parseInt(cursor.getString(3));          
                student.course = cursor.getString(4);
                student.modules = cursor.getString(5);
                studentList.add(student);
            } while (cursor.moveToNext());
        }
        // return contact list
        return studentList;
    }


    public boolean insertStudent(String name, String gender, int age, String password, String course, String modules) {
        SQLiteDatabase db = getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(Student_Name, name);
        contentValues.put(Student_Password, password);
        contentValues.put(Student_Gender, gender);
        contentValues.put(Student_Age, age);        
        contentValues.put(Student_Course, course);
        contentValues.put(Modules, modules);
        Log.d("DB", "Inserted Successfully");
        return true;
    }

}

MainActivity.java

public class MainActivity extends Activity {

    Intent appIntent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main); 
        DB db = new DB(this);
        db.insertStudent("T", "T", 5, "T", "T", "T");
        List<tableStudents> outputList = db.getData();     
    }

    public void goHomepage(View v)
    {
        Intent intent = new Intent(MainActivity.this, Homepage.class);
        startActivity(intent);
    }
    public void goAccount(View v)
    {
        Intent intent = new Intent(MainActivity.this, MyAccount.class);
        startActivity(intent);
    }   

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

最佳答案

好吧,您有一个 List,因此您可以使用 ListView 显示相应的数据。如果您只想查看从 getData 返回的数据,您可以循环遍历该数组并将其记录到您的 logcat 输出中。

for (tableStudents student: outputList) {
    // Log your results.
    Log.d("result_list", student.toString())
}

如果您想在应用中显示此信息,您可以使用 ListView。 Android 为任意数据和 ListView 提供了一个基本接口(interface),您可以根据需要扩展和自定义该接口(interface),称为 BaseAdapter。它们还提供了 BaseAdapter 的具体实现,供您无需太多工作即可使用。

这样的实现之一是 ArrayAdapter 类。 ( See here) 该类描述如下:

A concrete BaseAdapter that is backed by an array of arbitrary objects. By default this class expects that the provided resource id references a single TextView. If you want to use a more complex layout, use the constructors that also takes a field id. That field id should reference a TextView in the larger layout resource.

However the TextView is referenced, it will be filled with the toString() of each object in the array. You can add lists or arrays of custom objects. Override the toString() method of your objects to determine what text will be displayed for the item in the list.

因此,您可以在 Activity 的布局文件中创建一个 ListView,为其指定一个 ID,然后创建一个适配器来为该 ListView 提供支持。例如:

首先在您的 Activity xml 文件中创建 ListView 。

activity_main.xml

<ListView
    android:id="@+id/my_list_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

定义后,您应该重写 tableStudents.toString() 方法并实现一个用户友好的版本,将相关字段显示为字符串。

tableStudents.java(通常,您应该避免这样做,而是扩展 ArrayAdapter,然后重写 getView() 并显示那里有对象的属性)

@Override
public String toString() {
    StringBuilder out = new StringBuilder();
    out.append("Student: ")
    out.append(this.name);
    // etc.
    return out.toString();
}

现在,在您的 Activity 中调用 getData() 后,引用 ListView 并创建 ArrayAdapter:

MainActivity.java

List<tableStudents> outputList = db.getData();

// Reference the list view.
ListView listView = (ListView) findViewById(R.id.my_list_view);

// Create the adapter.
ArrayAdapter listViewAdapter = new ArrayAdapter(
        this, 
        android.R.layout.simple_list_item_1,
        android.R.id.text1,
        outputList
);

// Then set the adapter for the list view.
listView.setAdapter(listViewAdapter);

您的数据库结果应该显示在应用程序中一个漂亮的可滚动列表中。

希望这对您有所帮助,如果您有任何疑问,请告诉我。

关于java - 通过另一个类中的列表输出数据库信息 - Eclipse Android SQLite,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35303092/

相关文章:

java - ImageView 中的旋转图像

c++ - 进入系统,Linux下的CRTL功能与Eclipse

java - 如何在 Spring MVC Controller get call 中提取 IP 地址?

java - 如何找到特定字符串在图像上的位置?

android - 如何从 android 手机 db(sqlite) 上传记录到网页

android - com.android.internal.R.attr 和 android.R.attr 是否具有相同的值集?

java - 如何在maven插件中初始化/运行java项目

android - Android 设备选择器窗口目标栏中的橙色三角形是什么意思?

java - 房间一对多警告

java - 如何获取 as400 (jt400) 登录用户列表