android中findViewById(R.id.XXX)提示空指针异常NullPointerException的原因

本文探讨了在Android开发过程中遇到的常见问题之一:在未加载布局文件、未正确组织视图树以及Eclipse相关问题下,使用findViewById()无法获取到预期的视图元素。提供了解决这三种情况的方法:确保已加载布局、调整视图层次结构以及通过清理项目解决Eclipse引起的问题。

注:转自  http://wangzhen19900908.iteye.com/blog/1515038


造成这种结果一般有3中情况

第一是:未加载布局文件,也就是没有设置布局之前,就findViewById(),这样肯定获取不到了

第二是:View应该是树形的组织,从当前所在的contentview中找不到,要设置contentview为包含有所要find的contentview;

第三是:Eclipse造成的;项目clean一次(Project菜单 -> Clean子菜单),就OK了。


package com.example.test_001; import android.app.DatePickerDialog; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.example.test_001.db.AccountingDBHelper; import com.example.test_001.enum_t.EnumType; import java.util.Calendar; public class SearchActivity extends AppCompatActivity { private EnumType currentType = EnumType.EXPENSE; // 默认是支出 private ImageButton selectedCategoryButton = null; private TextView searchTitle; private EditText searchInput; private Button datePickerButton; private Button incomeButton; private Button expenseButton; private Button byAmountButton; private TextView resultTextView; private AccountingDBHelper dbHelper; private LinearLayout expenseCategoryGroup, expenseCategoryOther; private LinearLayout incomeCategoryGroup, incomeCategoryOther; // 收入类别按钮 private ImageButton salaryButton, debtButton, bonusButton, investmentButton, accidentButton, otherIncomeButton; // 支出类别按钮 private ImageButton foodButton, shoppingButton, utilitiesButton, phoneButton, entertainmentButton, otherOutcomeButton; private int selectedYear, selectedMonth, selectedDay; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_search); // 初始化控件 searchTitle = findViewById(R.id.search_title); searchInput = findViewById(R.id.search_input); datePickerButton = findViewById(R.id.date_picker_button); incomeButton = findViewById(R.id.income_button); expenseButton = findViewById(R.id.expense_button); byAmountButton = findViewById(R.id.by_amount_button); resultTextView = findViewById(R.id.result_text_view); expenseCategoryGroup = findViewById(R.id.expense_category_group_search_1); expenseCategoryOther = findViewById(R.id.expense_category_group_search_2); incomeCategoryGroup = findViewById(R.id.income_category_group_search_1); incomeCategoryOther = findViewById(R.id.income_category_group_search_2); // 收入图标按钮 salaryButton = findViewById(R.id.category_salary); debtButton = findViewById(R.id.category_collect_debt); bonusButton = findViewById(R.id.category_bonus); investmentButton = findViewById(R.id.category_investment); accidentButton = findViewById(R.id.category_accident); otherIncomeButton = findViewById(R.id.category_other_income); // 支出图标按钮 foodButton = findViewById(R.id.category_food); shoppingButton = findViewById(R.id.category_shopping); utilitiesButton = findViewById(R.id.category_utilities); phoneButton = findViewById(R.id.category_phone); entertainmentButton = findViewById(R.id.category_entertainment); otherOutcomeButton = findViewById(R.id.category_other_outcome); // 找到返回按钮 Button backButton = findViewById(R.id.back_button); // 设置点击事件 backButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // 创建 Intent 跳转到 MainActivity Intent intent = new Intent(SearchActivity.this, MainActivity.class); startActivity(intent); // 结束当前的 SearchActivity finish(); } }); // 初始化数据库帮助器 dbHelper = new AccountingDBHelper(this); final Calendar calendar = Calendar.getInstance(); selectedYear = calendar.get(Calendar.YEAR); selectedMonth = calendar.get(Calendar.MONTH); selectedDay = calendar.get(Calendar.DAY_OF_MONTH); // 设置日期选择器按钮点击事件 datePickerButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showDatePickerDialog(); } }); setupCategoryButton(foodButton, "餐饮"); setupCategoryButton(shoppingButton, "购物"); setupCategoryButton(utilitiesButton, "水电"); setupCategoryButton(phoneButton, "话费"); setupCategoryButton(entertainmentButton, "娱乐"); setupCategoryButton(otherOutcomeButton, "其他"); setupCategoryButton(salaryButton, "工资"); setupCategoryButton(debtButton, "收债"); setupCategoryButton(bonusButton, "奖金"); setupCategoryButton(investmentButton, "投资"); setupCategoryButton(accidentButton, "意外所得"); setupCategoryButton(otherIncomeButton, "其他"); // 默认显示支出类别 showExpenseCategories(); // 收入按钮点击 incomeButton.setOnClickListener(v -> { currentType = EnumType.INCOME; showIncomeCategories(); }); // 支出按钮点击 expenseButton.setOnClickListener(v -> { currentType = EnumType.EXPENSE; showExpenseCategories(); }); // 按金额搜索 byAmountButton.setOnClickListener(v -> { String amountStr = searchInput.getText().toString(); if (!amountStr.isEmpty()) { try { double amount = Double.parseDouble(amountStr); // 构造带 type 条件的查询语句 String selection = AccountingDBHelper.COLUMN_AMOUNT + "=? AND " + AccountingDBHelper.COLUMN_TYPE + "=?"; String[] selectionArgs = new String[]{String.valueOf(amount), currentType.getValue()}; Cursor cursor = dbHelper.getReadableDatabase().query( AccountingDBHelper.TABLE_TRANSACTIONS, new String[]{ AccountingDBHelper.COLUMN_DATE, AccountingDBHelper.COLUMN_TYPE, AccountingDBHelper.COLUMN_CATEGORY, AccountingDBHelper.COLUMN_AMOUNT }, selection, selectionArgs, null, null, null); displayResults(cursor); } catch (NumberFormatException e) { Toast.makeText(SearchActivity.this, "请输入有效的金额", Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(SearchActivity.this, "请输入金额进行搜索", Toast.LENGTH_SHORT).show(); } }); } private void showDatePickerDialog() { DatePickerDialog datePickerDialog = new DatePickerDialog(this, (view, year, monthOfYear, dayOfMonth) -> { selectedYear = year; selectedMonth = monthOfYear; selectedDay = dayOfMonth; updateDateDisplay(); }, selectedYear, selectedMonth, selectedDay); datePickerDialog.getDatePicker().setMaxDate(System.currentTimeMillis()); datePickerDialog.show(); } private void updateDateDisplay() { String formattedMonth = (selectedMonth + 1) < 10 ? "0" + (selectedMonth + 1) : String.valueOf(selectedMonth + 1); String formattedDay = selectedDay < 10 ? "0" + selectedDay : String.valueOf(selectedDay); String date = selectedYear + "-" + formattedMonth + "-" + formattedDay; Cursor cursor = dbHelper.getReadableDatabase().query( AccountingDBHelper.TABLE_TRANSACTIONS, new String[]{AccountingDBHelper.COLUMN_DATE, AccountingDBHelper.COLUMN_TYPE, AccountingDBHelper.COLUMN_CATEGORY, AccountingDBHelper.COLUMN_AMOUNT}, AccountingDBHelper.COLUMN_DATE + "=?", new String[]{date}, null, null, null); displayResults(cursor); } private void displayResults(Cursor cursor) { if (cursor.getCount() == 0) { Toast.makeText(this, "没有找到匹配的数据", Toast.LENGTH_SHORT).show(); return; } StringBuilder result = new StringBuilder(); while (cursor.moveToNext()) { String date = cursor.getString(cursor.getColumnIndexOrThrow(AccountingDBHelper.COLUMN_DATE)); String type = cursor.getString(cursor.getColumnIndexOrThrow(AccountingDBHelper.COLUMN_TYPE)); String category = cursor.getString(cursor.getColumnIndexOrThrow(AccountingDBHelper.COLUMN_CATEGORY)).substring(6); double amount = cursor.getDouble(cursor.getColumnIndexOrThrow(AccountingDBHelper.COLUMN_AMOUNT)); result.append("日期: ").append(date) .append(", 类型: ").append(type) .append(", 类别: ").append(category) .append(", 金额: ").append(amount) .append("\n"); } resultTextView.setText(result.toString()); } /* private void setupCategoryButton(ImageButton button, String categoryName) { button.setOnClickListener(v -> { if (selectedCategoryButton != null) { selectedCategoryButton.setBackgroundColor(getColor(android.R.color.transparent)); } selectedCategoryButton = button; selectedCategoryButton.setBackgroundColor(getColor(android.R.color.holo_blue_light)); Cursor cursor = dbHelper.getReadableDatabase().query( AccountingDBHelper.TABLE_TRANSACTIONS, new String[]{AccountingDBHelper.COLUMN_DATE, AccountingDBHelper.COLUMN_TYPE, AccountingDBHelper.COLUMN_CATEGORY, AccountingDBHelper.COLUMN_AMOUNT}, AccountingDBHelper.COLUMN_CATEGORY + "=?", new String[]{categoryName}, null, null, null); displayResults(cursor); }); }*/ private String getFormattedDate() { String formattedMonth = (selectedMonth + 1) < 10 ? "0" + (selectedMonth + 1) : String.valueOf(selectedMonth + 1); String formattedDay = selectedDay < 10 ? "0" + selectedDay : String.valueOf(selectedDay); return selectedYear + "-" + formattedMonth + "-" + formattedDay; } private void setupCategoryButton(ImageButton button, String categoryName) {// button.setOnClickListener(v -> { if (selectedCategoryButton != null) { selectedCategoryButton.setBackgroundColor(getResources().getColor(android.R.color.transparent)); } selectedCategoryButton = button; selectedCategoryButton.setBackgroundColor(getResources().getColor(android.R.color.holo_blue_light)); String selection; String[] selectionArgs; // 获取格式化后的日期 String selectedDate = getFormattedDate(); // 判断是否是“其他”类别按钮 if ("其他".equals(categoryName) && (button.getId() == R.id.category_other_income || button.getId() == R.id.category_other_outcome)) { // 查询所有“other%”类别,且匹配当前收支类型和日期 selection = AccountingDBHelper.COLUMN_CATEGORY + " LIKE ? AND " + AccountingDBHelper.COLUMN_TYPE + "=? AND " + AccountingDBHelper.COLUMN_DATE + "=?"; selectionArgs = new String[]{"other%", currentType.getValue(), selectedDate}; } else { // 精确匹配类别、收支类型和日期 selection = AccountingDBHelper.COLUMN_CATEGORY + "=? AND " + AccountingDBHelper.COLUMN_TYPE + "=? AND " + AccountingDBHelper.COLUMN_DATE + "=?"; selectionArgs = new String[]{categoryName, currentType.getValue(), selectedDate}; } Cursor cursor = dbHelper.getReadableDatabase().query( AccountingDBHelper.TABLE_TRANSACTIONS, new String[]{ AccountingDBHelper.COLUMN_DATE, AccountingDBHelper.COLUMN_TYPE, AccountingDBHelper.COLUMN_CATEGORY, AccountingDBHelper.COLUMN_AMOUNT }, selection, selectionArgs, null, null, null); displayResults(cursor); }); } private void showIncomeCategories() { incomeButton.setBackgroundColor(getResources().getColor(android.R.color.holo_red_light)); expenseButton.setBackgroundColor(getResources().getColor(R.color.bg_gray)); // 隐藏支出类别 findViewById(R.id.expense_category_group_search_1).setVisibility(View.GONE); findViewById(R.id.expense_category_group_search_2).setVisibility(View.GONE); // 显示收入类别 findViewById(R.id.income_category_group_search_1).setVisibility(View.VISIBLE); findViewById(R.id.income_category_group_search_2).setVisibility(View.VISIBLE); } private void showExpenseCategories() { expenseButton.setBackgroundColor(getResources().getColor(android.R.color.holo_blue_light)); incomeButton.setBackgroundColor(getResources().getColor(R.color.bg_gray)); // 隐藏收入类别 findViewById(R.id.income_category_group_search_1).setVisibility(View.GONE); findViewById(R.id.income_category_group_search_2).setVisibility(View.GONE); // 显示支出类别 findViewById(R.id.expense_category_group_search_1).setVisibility(View.VISIBLE); findViewById(R.id.expense_category_group_search_2).setVisibility(View.VISIBLE); } } package com.example.test_001.enum_t; public enum EnumType { INCOME("收入"), EXPENSE("支出"); private final String value; EnumType(String value) { this.value = value; } public String getValue() { return value; } /* public static EnumType fromValue(String value) { for (EnumType type : values()) { if (type.getValue().equals(value)) { return type; } } throw new IllegalArgumentException("Invalid enum type: " + value); }*/ }为什么点击查找中的类别图标会闪退
06-29
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值