我创建了一个包含4列的表:_id(自动增量),Vocab(文本),含义(文本)和收藏夹(数字)。现在我创建了一个搜索查询,如下所示:
public class StudentRepo {
private DBHelper dbHelper;
public StudentRepo(Context context) {
dbHelper = new DBHelper(context);
}
public Cursor getStudentListByKeyword(String search) {
//Open connection to read only
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor cursor=db.query("dictionary",new String []{"_id","Vocab","Favorite"},"Vocab LIKE ?", new String[]{"%"+search+"%"},null,null,null);
if (cursor == null) {
return null;
} else if (!cursor.moveToFirst()) {
cursor.close();
return null;
}
return cursor;
}
}
请找到搜索栏代码:
@Override
///@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.options_menu, menu);
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
SearchManager manager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView search = (SearchView) menu.findItem(R.id.search).getActionView();
search.setSearchableInfo(manager.getSearchableInfo(getComponentName()));
search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String s) {
Log.d(TAG, "onQueryTextSubmit ");
cursor = studentRepo.getStudentListByKeyword(s);
if (cursor == null) {
Toast.makeText(MainActivity.this, "No records found!", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this, cursor.getCount() + " records found!", Toast.LENGTH_LONG).show();
}
customAdapter.swapCursor(cursor);
return false;
}
DBHelper代码:
public class DBHelper extends SQLiteAssetHelper {
//version number to upgrade database version
//each time if you Add, Edit table, you need to change the
//version number.
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "Dictionary.db";
public DBHelper(Context context ) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed, all data will be gone!!!
//Toast.makeText(DBHelper.this,"Just Added",Toast.LENGTH_LONG).show();
}
}
每当我运行应用程序并点击搜索栏开始搜索单词时,我的应用程序就会停止工作。请找到Logcat输出
05-09 13:46:58.931 2178-2178/com.example.doctor.searchwidget
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.doctor.searchwidget, PID: 2178
java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.Cursor
com.example.doctor.searchwidget.StudentRepo.getStudentListByKeyword(java.lang.String)'
on a null object reference
at com.example.doctor.searchwidget.MainActivity$2.onQueryTextChange(MainActivity.java:145)
at android.support.v7.widget.SearchView.onTextChanged(SearchView.java:1150)
at android.support.v7.widget.SearchView.access$2000(SearchView.java:103)
at android.support.v7.widget.SearchView$12.onTextChanged(SearchView.java:1680)
at android.widget.TextView.sendOnTextChanged(TextView.java:7663)
at android.widget.TextView.setText(TextView.java:4050)
at android.widget.TextView.setText(TextView.java:3905)
at android.widget.EditText.setText(EditText.java:85)
at android.widget.TextView.setText(TextView.java:3880)
at android.support.v7.widget.SearchView.onActionViewExpanded(SearchView.java:1265)
at android.support.v7.widget.Toolbar$ExpandedActionViewMenuPresenter.expandItemActionView(Toolbar.java:2026)
at android.support.v7.view.menu.MenuBuilder.expandItemActionView(MenuBuilder.java:1323)
at android.support.v7.view.menu.MenuItemImpl.expandActionView(MenuItemImpl.java:687)
at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:963)
at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:948)
at android.support.v7.widget.ActionMenuView.invokeItem(ActionMenuView.java:618)
at android.support.v7.view.menu.ActionMenuItemView.onClick(ActionMenuItemView.java:139)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
MainActivity.java:145指向“getStudentListByKeyword(String search)”
我尝试更改查询但所有工作都失败了。我在stackoverflow上的某个地方因为没有连接到sqlite数据库而发生这种情况,请帮助我。
MainActivity Code:
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.SearchView;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
import com.oguzdev.circularfloatingactionmenu.library.FloatingActionButton;
import com.oguzdev.circularfloatingactionmenu.library.FloatingActionMenu;
import com.oguzdev.circularfloatingactionmenu.library.SubActionButton;
import java.util.List;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private CustomAdapter customAdapter;
ListView listView;
public Cursor cursor;
public StudentRepo studentRepo;
private final static String TAG = MainActivity.class.getName().toString();
private static final String TAG_BOOKMARKS="bookmarks";
private static final String TAG_ABOUT_US="about";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AdapterView.OnItemClickListener itemClickListener = new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> listView, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this, SearchResult.class);
intent.putExtra(SearchResult.EXTRA_NO, (int) id);
startActivity(intent);
}
};
listView = (ListView) findViewById(R.id.lstStudent);
listView.setOnItemClickListener(itemClickListener);
DatabaseAccess databaseAccess = DatabaseAccess.getInstance(this);
databaseAccess.open();
List<String> quotes = databaseAccess.getQuotes();
databaseAccess.close();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, quotes);
this.listView.setAdapter(adapter);
//Done Testing
ImageView imageView=new ImageView(this);
imageView.setImageResource(R.drawable.button_action);
FloatingActionButton actionButton = new FloatingActionButton.Builder(this)
.setContentView(imageView)
.build();
ImageView Bookmarks=new ImageView(this);
Bookmarks.setImageResource(R.drawable.button_action);
ImageView Aboutus=new ImageView(this);
Aboutus.setImageResource(R.drawable.button_action);
SubActionButton.Builder itemBuilder = new SubActionButton.Builder(this);
SubActionButton buttonbookmark = itemBuilder.setContentView(Bookmarks).build();
SubActionButton buttonaboutus = itemBuilder.setContentView(Aboutus).build();
buttonbookmark.setOnClickListener(this);
buttonaboutus.setOnClickListener(this);
buttonbookmark.setTag(TAG_BOOKMARKS);
buttonaboutus.setTag(TAG_ABOUT_US);
FloatingActionMenu actionMenu = new FloatingActionMenu.Builder(this)
.addSubActionView(buttonbookmark)
.addSubActionView(buttonaboutus)
.attachTo(actionButton)
.build();
}
@Override
public void onResume() {
super.onResume();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.options_menu, menu);
SearchManager manager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView search = (SearchView) menu.findItem(R.id.search).getActionView();
search.setSearchableInfo(manager.getSearchableInfo(getComponentName()));
search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String s) {
Log.d(TAG, "onQueryTextSubmit ");
cursor = studentRepo.getStudentListByKeyword(s);
if (cursor == null) {
Toast.makeText(MainActivity.this, "No records found!", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this, cursor.getCount() + " records found!", Toast.LENGTH_LONG).show();
}
customAdapter.swapCursor(cursor);
return false;
}
@Override
public boolean onQueryTextChange(String s) {
Log.d(TAG, "onQueryTextChange ");
cursor = studentRepo.getStudentListByKeyword(s);
if (cursor != null) {
customAdapter.swapCursor(cursor);
}
return false;
}
});
return true;
}
@Override
public void onClick(View v) {
if (v.getTag().equals(TAG_BOOKMARKS)){
startActivity(new Intent(this,Bookmarks.class));
}
if (v.getTag().equals(TAG_ABOUT_US)){
}
}
}
初始化studentRepo后,我收到了新的错误:
05-14 01:45:44.506 2142-2142/com.example.doctor.searchwidget E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.doctor.searchwidget, PID: 2142
java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.Cursor com.example.doctor.searchwidget.CustomAdapter.swapCursor(android.database.Cursor)' on a null object reference
at com.example.doctor.searchwidget.MainActivity$2.onQueryTextChange(MainActivity.java:148)
at android.support.v7.widget.SearchView.onTextChanged(SearchView.java:1150)
at android.support.v7.widget.SearchView.access$2000(SearchView.java:103)
at android.support.v7.widget.SearchView$12.onTextChanged(SearchView.java:1680)
at android.widget.TextView.sendOnTextChanged(TextView.java:7663)
at android.widget.TextView.setText(TextView.java:4050)
at android.widget.TextView.setText(TextView.java:3905)
at android.widget.EditText.setText(EditText.java:85)
at android.widget.TextView.setText(TextView.java:3880)
at android.support.v7.widget.SearchView.onActionViewExpanded(SearchView.java:1265)
at android.support.v7.widget.Toolbar$ExpandedActionViewMenuPresenter.expandItemActionView(Toolbar.java:2026)
at android.support.v7.view.menu.MenuBuilder.expandItemActionView(MenuBuilder.java:1323)
at android.support.v7.view.menu.MenuItemImpl.expandActionView(MenuItemImpl.java:687)
at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:963)
at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:948)
at android.support.v7.widget.ActionMenuView.invokeItem(ActionMenuView.java:618)
at android.support.v7.view.menu.ActionMenuItemView.onClick(ActionMenuItemView.java:139)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
答案 0 :(得分:0)
studentRepo未初始化,在MainActivity的onCreate方法(在setContentView下面)中添加此行
studentRepo = new StudentRepo(this);