Android中cursor.getInt()返回值的坑

本文详细介绍了Android中Cursor类的getInt方法。当从数据库获取的数据为null时,此方法不会抛出异常,而是返回0,这可能导致null与0的混淆。为了避免这种混淆,建议使用getString方法替代。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Cursor中的getInt方法:

public abstract int getInt (int columnIndex)

如果你代码中有用它从数据库中取一个整型值,需要注意:

如果数据库中的这一个数据恰好是null,而null又不是int,此时并不会抛出NumberFormatException 异常,而是直接返回0!

为了避免将null和0混淆,可以考虑用getString()代替。



// 位置: java/com/example/todoapp/DatabaseHelper.java public class DatabaseHelper extends SQLiteOpenHelper { private static final String DATABASE_NAME = "todo.db"; private static final int DATABASE_VERSION = 1; private static final String TABLE_TASKS = "tasks"; private static final String COLUMN_ID = "id"; private static final String COLUMN_TITLE = "title"; // 其他列定义... public DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { String CREATE_TABLE = "CREATE TABLE " + TABLE_TASKS + "(" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + COLUMN_TITLE + " TEXT," + "description TEXT," + "is_completed INTEGER DEFAULT 0," + "category TEXT," + "timestamp INTEGER)"; db.execSQL(CREATE_TABLE); } // 添加任务 public void addTask(Task task) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(COLUMN_TITLE, task.getTitle()); values.put("description", task.getDescription()); values.put("category", task.getCategory()); values.put("timestamp", task.getTimestamp()); db.insert(TABLE_TASKS, null, values); db.close(); } // 获取所有任务 public List<Task> getAllTasks() { List<Task> taskList = new ArrayList<>(); String selectQuery = "SELECT * FROM " + TABLE_TASKS; SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.rawQuery(selectQuery, null); if (cursor.moveToFirst()) { do { Task task = new Task( cursor.getString(1), cursor.getString(2), cursor.getString(4) ); task.setId(cursor.getInt(0)); task.setCompleted(cursor.getInt(3) == 1); taskList.add(task); } while (cursor.moveToNext()); } cursor.close(); return taskList; } // 更新任务状态/删除任务等方法(此处省略) } 刚才就是这段代码报了上面的错误,大面积的No candidates found for method call task.getTitle().报错或No candidates found for method call cursor.getString(2).这个报错,请帮我检查并尝试在不改变源程序的情况下修改
06-18
package com.example.myapplication; import android.annotation.SuppressLint; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import androidx.annotation.Nullable; public class UserDbHelper extends SQLiteOpenHelper { private static UserDbHelper sHelper; private static final String DB_NAME = "user.db"; //数据库名 private static final int VERSION = 1; //版本号 //必须实现其中一个构方法 public UserDbHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) { super(context, name, factory, version); } //创建单例,供使用调用该类里面的的增删改查的方法 public synchronized static UserDbHelper getInstance(Context context) { if (null == sHelper) { sHelper = new UserDbHelper(context, DB_NAME, null, VERSION); } return sHelper; } @Override public void onCreate(SQLiteDatabase db) { //创建user_table表 db.execSQL("create table user_table(user_id integer primary key autoincrement, " + "username text," + //用户名 "password text," + //密码 "nickname text" + // ")"); } @Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) { } /** * 登录 */ @SuppressLint("Range") public UserInfo login(String username) { //获取SQLiteDatabase实例 SQLiteDatabase db = getReadableDatabase(); UserInfo userInfo = null; String sql = "select user_id,username,password,nickname from user_table where username=?"; String[] selectionArgs = {username}; Cursor cursor = db.rawQuery(sql, selectionArgs); if (cursor.moveToNext()) { int user_id = cursor.getInt(cursor.getColumnIndex("user_id")); String name = cursor.getString(cursor.getColumnIndex("username")); String password = cursor.getString(cursor.getColumnIndex("password")); String nickname = cursor.getString(cursor.getColumnIndex("nickname")); userInfo = new UserInfo(user_id, name, password, nickname); } cursor.close(); db.close(); return userInfo; } /** * 注册 */ public int register(String username, String password, String nickname) { //获取SQLiteDatabase实例 SQLiteDatabase db = getWritableDatabase(); ContentValues values = new ContentValues(); //填充占位符 values.put("username", username); values.put("password", password); values.put("nickname", nickname); String nullColumnHack = "values(null,?,?,?)"; //执行 int insert = (int) db.insert("user_table", nullColumnHack, values); // db.close(); return insert; } public int updatePassword(String username, String newPassword) { return ; } }
06-24
分析一下代码: public void printContacts() { //生成ContentResolver对象 ContentResolver contentResolver = getContentResolver(); // 获得所有的联系人 /*Cursor cursor = contentResolver.query( ContactsContract.Contacts.CONTENT_URI, null, null, null, null); */ //这段代码和上面代码是等价的,使用两种方式获得联系人的Uri Cursor cursor = contentResolver.query(Uri.parse("content://com.android.contacts/contacts"),null,null,null,null); // 循环遍历 if (cursor.moveToFirst()) { int idColumn = cursor.getColumnIndex(ContactsContract.Contacts._ID); int displayNameColumn = cursor .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME); do { // 获得联系人的ID String contactId = cursor.getString(idColumn); // 获得联系人姓名 String displayName = cursor.getString(displayNameColumn); //使用Toast技术显示获得的联系人信息 Toast.makeText(ContentProviderDemo.this, "联系人姓名:" + displayName,Toast.LENGTH_LONG).show(); // 查看联系人有多少个号码,如果没有号码,返回0 int phoneCount = cursor .getInt(cursor .getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)); if (phoneCount > 0) { // 获得联系人的电话号码列表 Cursor phoneCursor = getContentResolver().query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + contactId, null, null); if(phoneCursor.moveToFirst()) { do { //遍历所有的联系人下面所有的电话号码 String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); //使用Toast技术显示获得的号码 Toast.makeText(ContentProviderDemo.this, "联系人电话:"+phoneNumber,Toast.LENGTH_LONG).show(); }while(phoneCursor.moveToNext()); } } } while (cursor.moveToNext()); } } }
最新发布
07-23
代码如下:package com.example.myapplication; import android.annotation.SuppressLint; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import androidx.annotation.Nullable; import java.util.ArrayList; import java.util.List; public class PersonDBHelper extends SQLiteOpenHelper { private static final String DATABASE_NAME = "Person.db"; private static final int DATABASE_VERSION = 1; public static final String TABLE_PERSON = "person"; public static final String COLUMN_ID = "id"; public static final String COLUMN_NAME = "name"; public static final String COLUMN_NUMBER = "number"; public static final String COLUMN_ISSTAR = "isstar"; private static final String CREATE_TABLE = "CREATE TABLE " + TABLE_PERSON + " (" + COLUMN_ID + " Text, " + COLUMN_NAME + " TEXT, " + COLUMN_NUMBER + " TEXT, " + COLUMN_ISSTAR + " TEXT )"; public PersonDBHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(CREATE_TABLE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS " + TABLE_PERSON); onCreate(db); } public void insertPerson(Person person){ SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(COLUMN_NAME, person.getName()); values.put(COLUMN_NUMBER, person.getNumber()); values.put(COLUMN_ID, person.getId()); values.put(COLUMN_ISSTAR, person.isStar()); db.close(); } @SuppressLint("Range") public List<Person> getAllPersons() { List<Person> persons = new ArrayList<>(); SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.query(TABLE_PERSON, null, null, null, null, null, null); if (cursor.moveToFirst()) { do { Boolean isstar; if(cursor.getString(cursor.getColumnIndex(COLUMN_ISSTAR)).equals("true")){ isstar=true; } else { isstar=false; } @SuppressLint("Range") Person person = new Person( cursor.getString(cursor.getColumnIndex(COLUMN_NAME)), cursor.getString(cursor.getColumnIndex(COLUMN_NUMBER)), cursor.getString(cursor.getColumnIndex(COLUMN_ID)), isstar ); persons.add(person); } while (cursor.moveToNext()); } cursor.close(); return persons; } } Activity调用语句如下: Person person = new Person("测试", "25", "111", true); dbHelper.insertPerson(person); List<Person> persons = dbHelper.getAllPersons(); Toast.makeText(this, "插入成功,ID: " + persons.get(0).getName(), Toast.LENGTH_SHORT).show();
07-22
package cn.itcast.notepad; //package com.example.helloworld; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import java.util.ArrayList; import java.util.List; public class NoteRepository { private DatabaseHelper dbHelper; public NoteRepository(Context context) { dbHelper = new DatabaseHelper(context); } public long insert(Note note) { SQLiteDatabase db = dbHelper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put("title", note.getTitle()); values.put("content", note.getContent()); long id = db.insert(DatabaseHelper.TABLE_NOTES, null, values); db.close(); return id; } public List<Note> getAllNotes() { List<Note> notes = new ArrayList<>(); SQLiteDatabase db = dbHelper.getReadableDatabase(); Cursor cursor = db.query(DatabaseHelper.TABLE_NOTES, null, null, null, null, null, null); while (cursor.moveToNext()) { long id = cursor.getLong(cursor.getColumnIndex(DatabaseHelper.COLUMN_ID)); String title = cursor.getString(cursor.getColumnIndex(DatabaseHelper.COLUMN_TITLE)); String content = cursor.getString(cursor.getColumnIndex(DatabaseHelper.COLUMN_CONTENT)); notes.add(new Note(id, title, content)); } cursor.close(); db.close(); return notes; } public void update(Note note) { SQLiteDatabase db = dbHelper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put("title", note.getTitle()); values.put("content", note.getContent()); db.update(DatabaseHelper.TABLE_NOTES, values, DatabaseHelper.COLUMN_ID + " = ?", new String[]{String.valueOf(note.getId())}); db.close(); } public void delete(long id) { SQLiteDatabase db = dbHelper.getWritableDatabase();
03-13
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值