Android sqLite数据检索[无错误显示]

时间:2015-06-11 17:02:05

标签: java android sqlite

尝试从sqLite检索数据并在Alert Dialog Builder中显示它。 但根本没有显示数据。当我点击View Button时没有任何反应。

MainActivity.java

package com.example.database;

import android.support.v7.app.ActionBarActivity;
import android.text.Editable;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;


public class MainActivity extends Activity{

    EditText first,last,age,classc;
    Button add,view;

    String FirstName;
    String LastName;
    String Class;
    Integer Age;

    sqLit myDB;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        myDB = new sqLit(this);

        Link();
        addButtonClicked();
        viewButtonClicked();





    }

    public void addButtonClicked()
    {
         add.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {


                xmlToVar();
                Integer flag=myDB.insertValue(FirstName, LastName, Class, Age);
                if (flag==1)
                {
                    Context context=MainActivity.this;
                    Toast toast = Toast.makeText(context, "Record Added" , Toast.LENGTH_LONG);
                    toast.show();
                }
                else
                {
                    Context context=MainActivity.this;
                    Toast toast = Toast.makeText(context, "Error Occured" , Toast.LENGTH_LONG);
                    toast.show();
                }
            }
        });
    }

    public void viewButtonClicked()
    {
         view.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Cursor res = myDB.getData();
                if (res.getCount()==0)
                {
                    showMessage("Error" , "No Data Found");
                    return;
                }

                StringBuffer buffer = new StringBuffer();
                while (res.moveToNext())
                {
                    buffer.append("ID : " + res.getString(0) + "\n");
                    buffer.append("FirstName : " + res.getString(1) + "\n");
                    buffer.append("LastName : " + res.getString(2) + "\n");
                    buffer.append("Class : " + res.getString(3) + "\n");
                    buffer.append("Age : " + res.getString(4) + "\n");
                    showMessage("Here is your Data",buffer.toString() );
                }



            }
        });
    }
    public void showMessage(String title, String message)
    {
        AlertDialog.Builder Builder = new AlertDialog.Builder(this);
        Builder.setCancelable(true);
        Builder.setTitle(title);
        Builder.setMessage(message);

    }
    public void Link()
    {
        first=(EditText) findViewById(R.id.editFirst);
        last=(EditText) findViewById(R.id.editLast);
        classc=(EditText) findViewById(R.id.editClass);
        age=(EditText) findViewById(R.id.editAge);
        add=(Button) findViewById(R.id.Add);
        view=(Button) findViewById(R.id.ViewAll);
    }

    public void xmlToVar()
    {
        FirstName = first.getText().toString();
        LastName = last.getText().toString();
        Class = classc.getText().toString();

            Age = Integer.parseInt(age.getText().toString());




    }


}

sqLit.java

package com.example.database;

import org.w3c.dom.Text;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.text.Editable;

public class sqLit extends SQLiteOpenHelper
{

    public static final String DB_NAME="student12.db";
    public static final String TABLE_NAME="class1";

    public static final String COL_1="ROLLNO";
    public static final String COL_2="FirstName";
    public static final String COL_3="LastName";
    public static final String COL_4="Class";
    public static final String COL_5="Age";

    public sqLit(Context context) {
        super(context, DB_NAME, null, 1);
        // TODO Auto-generated constructor stub
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        db.execSQL("CREATE TABLE " + TABLE_NAME + "(" +COL_1 + " INTEGER  PRIMARY KEY AUTOINCREMENT,"+COL_2 + " TEXT,"+COL_3 + " TEXT,"+COL_4 + " TEXT,"+COL_5 + " INTEGER)");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
        db.execSQL("Drop Table If Exist" + TABLE_NAME );
        onCreate(db);
    }

    public Integer insertValue(String firstName, String lastName, String Class, Integer Age)
    {

        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentV = new ContentValues();
        contentV.put(COL_2, firstName);
        contentV.put(COL_3, lastName);
        contentV.put(COL_4, Class);
        contentV.put(COL_5, Age);
        long isInserted = db.insert(TABLE_NAME, null, contentV);
        if (isInserted == -1){
            return 0;
        }
        else
        {
            return 1;
        }
        }

    public Cursor getData()
    {
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor res = db.rawQuery("Select * From "+TABLE_NAME, null);
        return res;
    }




}

logcat的

06-11 22:02:40.728: D/dalvikvm(1576): Not late-enabling CheckJNI (already on)
06-11 22:02:40.737: E/Trace(1576): error opening trace file: No such file or directory (2)
06-11 22:02:40.817: D/gralloc_goldfish(1576): Emulator without GPU emulation detected.
06-11 22:05:14.779: D/dalvikvm(1576): GC_CONCURRENT freed 197K, 5% free 6176K/6471K, paused 15ms+0ms, total 19ms
06-11 22:08:27.242: E/Trace(2066): error opening trace file: No such file or directory (2)
06-11 22:08:27.322: D/gralloc_goldfish(2066): Emulator without GPU emulation detected.
06-11 22:08:31.472: D/dalvikvm(2066): GC_CONCURRENT freed 225K, 5% free 6148K/6471K, paused 17ms+1ms, total 19ms
06-11 22:10:36.644: D/dalvikvm(2290): GC_CONCURRENT freed 225K, 5% free 6148K/6471K, paused 16ms+0ms, total 19ms
06-11 22:10:52.355: D/AndroidRuntime(2290): Shutting down VM
06-11 22:10:52.355: W/dalvikvm(2290): threadid=1: thread exiting with uncaught exception (group=0xb3f1c288)
06-11 22:10:52.355: E/AndroidRuntime(2290): FATAL EXCEPTION: main
06-11 22:10:52.355: E/AndroidRuntime(2290): java.lang.NumberFormatException: Invalid int: ""
06-11 22:10:52.355: E/AndroidRuntime(2290):     at java.lang.Integer.invalidInt(Integer.java:138)
06-11 22:10:52.355: E/AndroidRuntime(2290):     at java.lang.Integer.parseInt(Integer.java:359)
06-11 22:10:52.355: E/AndroidRuntime(2290):     at java.lang.Integer.parseInt(Integer.java:332)
06-11 22:10:52.355: E/AndroidRuntime(2290):     at com.example.database.MainActivity.xmlToVar(MainActivity.java:115)
06-11 22:10:52.355: E/AndroidRuntime(2290):     at com.example.database.MainActivity$1.onClick(MainActivity.java:46)
06-11 22:10:52.355: E/AndroidRuntime(2290):     at android.view.View.performClick(View.java:4084)
06-11 22:10:52.355: E/AndroidRuntime(2290):     at android.view.View$PerformClick.run(View.java:16966)
06-11 22:10:52.355: E/AndroidRuntime(2290):     at android.os.Handler.handleCallback(Handler.java:615)
06-11 22:10:52.355: E/AndroidRuntime(2290):     at android.os.Handler.dispatchMessage(Handler.java:92)
06-11 22:10:52.355: E/AndroidRuntime(2290):     at android.os.Looper.loop(Looper.java:137)
06-11 22:10:52.355: E/AndroidRuntime(2290):     at android.app.ActivityThread.main(ActivityThread.java:4745)
06-11 22:10:52.355: E/AndroidRuntime(2290):     at java.lang.reflect.Method.invokeNative(Native Method)
06-11 22:10:52.355: E/AndroidRuntime(2290):     at java.lang.reflect.Method.invoke(Method.java:511)
06-11 22:10:52.355: E/AndroidRuntime(2290):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
06-11 22:10:52.355: E/AndroidRuntime(2290):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
06-11 22:10:52.355: E/AndroidRuntime(2290):     at dalvik.system.NativeStart.main(Native Method)
06-11 22:12:22.676: D/dalvikvm(2455): GC_CONCURRENT freed 201K, 5% free 6172K/6471K, paused 17ms+0ms, total 19ms
06-11 22:14:01.238: D/dalvikvm(2652): Not late-enabling CheckJNI (already on)
06-11 22:14:01.248: E/Trace(2652): error opening trace file: No such file or directory (2)
06-11 22:14:01.338: D/gralloc_goldfish(2652): Emulator without GPU emulation detected.

按钮根本不起作用。

3 个答案:

答案 0 :(得分:0)

xmlToVar方法的以下异常是问题,你在addButtonClicked方法中调用它

java.lang.NumberFormatException:无效的int:""

如果未输入Age字段中的值,则在调用

之前进行空检查时会发生此错误

Age = Integer.parseInt(age.getText()。toString());

应解决问题

答案 1 :(得分:0)

在xmlToVar()中使用parseInt之前验证输入:

    String ageStr = age.getText().toString();

    if (ageStr != "")
        r.age = Integer.parseInt(ageStr);

如果可以有默认值,您也可以初始化Integer age

答案 2 :(得分:0)

您需要提供以下信息:

i)您是否尝试过调试? ii)如果是,光标是否获得任何数据?

现在采用不同的方法解决问题:

创建数据类[使其更易于处理,即存储和从数据库中获取]

示例:

班级:

public class NoticeInformation {
    private String  NoticeType, NoticeHeader, NoticeLink;
    private int Important, NoticeId, Read;

    public NoticeInformation(int NoticeId,
                             String NoticeType,
                             String NoticeHeader,
                             String NoticeLink,
                             int Important,
                             int Read){
        this.NoticeId = NoticeId;
        this.NoticeType = NoticeType;
        this.NoticeHeader = NoticeHeader;
        this.NoticeLink = NoticeLink;
        this.Important = Important;
        this.Read = Read;
    }

    public int getNoticeId() {
        return NoticeId;
    }

    public void setNoticeId(int noticeId) {
        NoticeId = noticeId;
    }

    public String getNoticeType() {
        return NoticeType;
    }

    public void setNoticeType(String noticeType) {
        NoticeType = noticeType;
    }

    public String getNoticeHeader() {
        return NoticeHeader;
    }

    public void setNoticeHeader(String noticeHeader) {
        NoticeHeader = noticeHeader;
    }

    public String getNoticeLink() {
        return NoticeLink;
    }

    public void setNoticeLink(String noticeLink) {
        NoticeLink = noticeLink;
    }

    public int getImportant() {
        return Important;
    }

    public void setImportant(int important) {
        Important = important;
    }

    public int getRead() {
        return Read;
    }

    public void setRead(int read) {
        Read = read;
    }
}

数据库阅读:

public List<NoticeInformation> getScheduleNotice(){
        SQLiteDatabase db = this.getReadableDatabase();
        List<NoticeInformation> res = new ArrayList<>();
        String Query = "SELECT * FROM " + TABLE_NAME1 + " WHERE NoticeType = 'Schedule';";
        Cursor cursor = db.rawQuery(Query,  null);
        if (cursor.moveToFirst()){
            cursor.moveToFirst();
            do
            {
                NoticeInformation obj = new NoticeInformation(cursor.getInt(0), cursor.getString(1),
                        cursor.getString(2), cursor.getString(3), cursor.getInt(5),
                        cursor.getInt(4));
                res.add(obj);
            }while(cursor.moveToNext());
            return res;
        }
        return null;
    }

不是在应用程序端处理游标,而是将数据放在列表中。 [以我的拙见]更容易处理。

尝试这种方法,让我知道结果。