bounty将在7天内到期。回答此问题有资格获得+50信誉奖励。jay ram正在寻找此问题的更详细的答案:如何检索数据sqlite数据库android
输入的数据被保存在sqlite.how的sqlite中以检索它。我已经将数据从sqlite传输到片段。我没有任何数据。x1c 0d1x我已经尝试sqlite片段错误this->java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“java.util.List com.police.exam.databases.sqlite. Dborder.getAllbell()”
德贝什
public class DbHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 14;
private static final String DATABASE_NAME = "db_recipes_favorite";
private static final String TABLE_NAME = "tbl_recipes_favorite";
private static final String TABLE_NOTIFICATION = "notification1";
private static final String KEY_ID = "id";
private static final String KEY_CAT_NAME = "category_name";
private static final String KEY_RECIPE_ID = "recipe_id";
private static final String KEY_RECIPE_TITLE = "recipes_title";
private static final String KEY_RECIPE_TIME = "recipe_time";
private static final String KEY_RECIPE_IMAGE = "recipe_image";
private static final String KEY_RECIPE_DESCRIPTION = "recipe_description";
private static final String KEY_VIDEO_URL = "video_url";
private static final String KEY_VIDEO_ID = "video_id";
private static final String KEY_CONTENT_TYPE = "content_type";
private static final String KEY_FEATURED = "featured";
private static final String KEY_TAGS = "tags";
private static final String KEY_TOTAL_VIEWS = "total_views";
private static final String unique_id = "unique_id";
private static final String id = "id";
private static final String title = "title";
private static final String message = "message";
private static final String big_image = "big_image";
private static final String image = "image";
private static final String content_type = "content_type";
private static final String video_id = "video_id";
private static final String link = "link";
private static final String post_id = "post_id";
public DbHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_NAME + "("
+ KEY_ID + " INTEGER PRIMARY KEY,"
+ KEY_CAT_NAME + " TEXT,"
+ KEY_RECIPE_ID + " TEXT,"
+ KEY_RECIPE_TITLE + " TEXT,"
+ KEY_RECIPE_TIME + " TEXT,"
+ KEY_RECIPE_IMAGE + " TEXT,"
+ KEY_RECIPE_DESCRIPTION + " TEXT,"
+ KEY_VIDEO_URL + " TEXT,"
+ KEY_VIDEO_ID + " TEXT,"
+ KEY_CONTENT_TYPE + " TEXT,"
+ KEY_FEATURED + " TEXT,"
+ KEY_TAGS + " TEXT,"
+ KEY_TOTAL_VIEWS + " TEXT"
+ ")";
db.execSQL(CREATE_CONTACTS_TABLE);
String CREATE_CONTACTS_NOTIFICATION = "CREATE TABLE " + TABLE_NOTIFICATION + "("
+ id + " INTEGER PRIMARY KEY,"
+ unique_id + " TEXT,"
+ title + " TEXT,"
+ message + " TEXT,"
+ big_image + " TEXT,"
+ image + " TEXT,"
+ content_type + " TEXT,"
+ video_id + " TEXT,"
+ link + " TEXT,"
+ post_id + " TEXT"
+ ")";
db.execSQL(CREATE_CONTACTS_NOTIFICATION);
}
// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
// Create tables again
onCreate(db);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NOTIFICATION);
// Create tables again
onCreate(db);
}
public void AddtoFavorite(Recipe p) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_CAT_NAME, p.getCategory_name());
values.put(KEY_RECIPE_ID, p.getRecipe_id());
values.put(KEY_RECIPE_TITLE, p.getRecipe_title());
values.put(KEY_RECIPE_TIME, p.getRecipe_time());
values.put(KEY_RECIPE_IMAGE, p.getRecipe_image());
values.put(KEY_RECIPE_DESCRIPTION, p.getRecipe_description());
values.put(KEY_VIDEO_URL, p.getVideo_url());
values.put(KEY_VIDEO_ID, p.getVideo_id());
values.put(KEY_CONTENT_TYPE, p.getContent_type());
values.put(KEY_FEATURED, p.getFeatured());
values.put(KEY_TAGS, p.getTags());
values.put(KEY_TOTAL_VIEWS, p.getTotal_views());
// Inserting Row
db.insert(TABLE_NAME, null, values);
db.close(); // Closing database connection
}
// Getting All Data
public List<Recipe> getAllData() {
List<Recipe> dataList = new ArrayList<Recipe>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_NAME + " ORDER BY id DESC";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Recipe values = new Recipe();
values.setId(Integer.parseInt(cursor.getString(0)));
values.setCategory_name(cursor.getString(1));
values.setRecipe_id(cursor.getString(2));
values.setRecipe_title(cursor.getString(3));
values.setRecipe_time(cursor.getString(4));
values.setRecipe_image(cursor.getString(5));
values.setRecipe_description(cursor.getString(6));
values.setVideo_url(cursor.getString(7));
values.setVideo_id(cursor.getString(8));
values.setContent_type(cursor.getString(9));
values.setFeatured(cursor.getString(10));
values.setTags(cursor.getString(11));
values.setTotal_views(cursor.getLong(12));
// Adding contact to list
dataList.add(values);
} while (cursor.moveToNext());
}
// return contact list
return dataList;
}
public List<bell> getAllbell() {
List<bell> dataList = new ArrayList<bell>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_NOTIFICATION + " ORDER BY id DESC";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
bell values = new bell();
values.setId(Integer.parseInt(cursor.getString(0)));
values.setunique_id(Integer.parseInt(cursor.getString(1)));
values.settitle(cursor.getString(1));
values.setmessage(cursor.getString(2));
values.setbig_image(cursor.getString(3));
values.setimage(cursor.getString(4));
values.setcontent_type(cursor.getString(5));
values.setpost_id(cursor.getString(6));
dataList.add(values);
} while (cursor.moveToNext());
}
// return contact list
return dataList;
}
public List<Recipe> getFavRow(String id) {
List<Recipe> dataList = new ArrayList<Recipe>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_NAME + " WHERE recipe_id=" + id;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Recipe values = new Recipe();
values.setId(Integer.parseInt(cursor.getString(0)));
values.setCategory_name(cursor.getString(1));
values.setRecipe_id(cursor.getString(2));
values.setRecipe_title(cursor.getString(3));
values.setRecipe_time(cursor.getString(4));
values.setRecipe_image(cursor.getString(5));
values.setRecipe_description(cursor.getString(6));
values.setVideo_url(cursor.getString(7));
values.setVideo_id(cursor.getString(8));
values.setContent_type(cursor.getString(9));
values.setFeatured(cursor.getString(10));
values.setTags(cursor.getString(11));
values.setTotal_views(cursor.getLong(12));
// Adding contact to list
dataList.add(values);
} while (cursor.moveToNext());
}
// return contact list
return dataList;
}
//for remove favorite
public void RemoveFav(Recipe contact) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME, KEY_RECIPE_ID + " = ?",
new String[]{String.valueOf(contact.getRecipe_id())});
db.close();
}
public void notifcation(long unique_id, String title, String message, String big_image,String image,String content_type,String video_id, String link, long post_id) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("unique_id", unique_id);
values.put("title", title);
values.put("message", message);
values.put("big_image", big_image);
values.put("image", image);
values.put("content_type", content_type);
values.put("video_id", video_id);
values.put("link", link);
values.put("post_id", post_id);
// Inserting Row
db.insert(TABLE_NOTIFICATION, null, values);
db.close(); // Closing database connection
}
public enum DatabaseManager {
INSTANCE;
private SQLiteDatabase db;
private boolean isDbClosed = true;
DbHandler dbHelper;
public void init(Context context) {
dbHelper = new DbHandler(context);
if (isDbClosed) {
isDbClosed = false;
this.db = dbHelper.getWritableDatabase();
}
}
public boolean isDatabaseClosed() {
return isDbClosed;
}
public void closeDatabase() {
if (!isDbClosed && db != null) {
isDbClosed = true;
db.close();
dbHelper.close();
}
}
}
}
字符串
数据传递sqlite到片段
public class Fragmentbell extends Fragment {
private View root_view;
private RecyclerView recyclerView;
private SwipeRefreshLayout swipeRefreshLayout;
private Adapterbell adapterbell;
public static final String EXTRA_OBJC = "key.EXTRA_OBJC";
DbHandler databaseHandler;
private ShimmerFrameLayout lyt_shimmer;
SharedPref sharedPref;
private List<bell> data = new ArrayList<>();
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
root_view = inflater.inflate(R.layout.fragment_category, container, false);
sharedPref = new SharedPref(getActivity());
lyt_shimmer = root_view.findViewById(R.id.shimmer_view_container);
swipeRefreshLayout = root_view.findViewById(R.id.swipe_refresh_layout_category);
swipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary);
recyclerView = root_view.findViewById(R.id.recyclerViewCategory);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new StaggeredGridLayoutManager(1, LinearLayoutManager.VERTICAL));
recyclerView.addItemDecoration(new EqualSpacingItemDecoration(0));
recyclerView.setHasFixedSize(true);
//set data and list adapter
adapterbell = new Adapterbell(getActivity(), recyclerView,data);
recyclerView.setAdapter(adapterbell);
// on item list clicked
adapterbell.setOnItemClickListener((v, obj, position) -> {
Intent intent = new Intent(getActivity(), ActivityCategoryDetail.class);
intent.putExtra(EXTRA_OBJC, obj);
startActivity(intent);
((MainActivity) getActivity()).showInterstitialAd();
});
loadDataFromDatabase();
//initShimmerLayout();
return root_view;
}
private void loadDataFromDatabase() {
data = databaseHandler.getAllbell();
}`
型
适配器
public class Adapterbell extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private final int VIEW_ITEM = 1;
private final int VIEW_PROG = 0;
private List<bell> items;
private boolean loading;
private OnLoadMoreListener onLoadMoreListener;
private Context context;
private OnItemClickListener mOnItemClickListener;
boolean scrolling = false;
private SharedPref sharedPref;
public interface OnItemClickListener {
void onItemClick(View view, bell obj, int position);
}
public void setOnItemClickListener(final OnItemClickListener mItemClickListener) {
this.mOnItemClickListener = mItemClickListener;
}
public Adapterbell(Context context, RecyclerView view, List<bell> items) {
this.items = items;
this.context = context;
this.sharedPref = new SharedPref(context);
lastItemViewDetector(view);
}
public class OriginalViewHolder extends RecyclerView.ViewHolder {
public TextView category_name;
public TextView recipe_title;
public ImageView recipe_image;
public ImageView thumbnail_video;
public MaterialRippleLayout lyt_parent;
public OriginalViewHolder(View v) {
super(v);
category_name = v.findViewById(R.id.category_name);
recipe_title = v.findViewById(R.id.recipe_title);
recipe_image = v.findViewById(R.id.recipe_image);
thumbnail_video = v.findViewById(R.id.thumbnail_video);
lyt_parent = v.findViewById(R.id.lyt_parent);
}
}
public static class ProgressViewHolder extends RecyclerView.ViewHolder {
public ProgressBar progressBar;
public ProgressViewHolder(View v) {
super(v);
progressBar = v.findViewById(R.id.load_more);
}
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
RecyclerView.ViewHolder vh;
if (viewType == VIEW_ITEM) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_home_recipe, parent, false);
vh = new OriginalViewHolder(v);
} else {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_load_more, parent, false);
vh = new ProgressViewHolder(v);
}
return vh;
}
// Replace the contents of a view (invoked by the layout manager)
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, final int position) {
if (holder instanceof OriginalViewHolder) {
final bell b = items.get(position);
final OriginalViewHolder vItem = (OriginalViewHolder) holder;
vItem.recipe_title.setText(b.title);
if (b.content_type != null && b.content_type.equals("youtube")) {
Picasso.get()
.load(Constant.YOUTUBE_IMAGE_FRONT + b.video_id + Constant.YOUTUBE_IMAGE_BACK_MQ)
.placeholder(R.drawable.ic_thumbnail)
.into(vItem.recipe_image);
} else {
Picasso.get()
.load(sharedPref.getApiUrl() + "/upload/" + b.image)
.placeholder(R.drawable.ic_thumbnail)
.into(vItem.recipe_image);
}
if (b.content_type != null && b.content_type.equals("Post")) {
vItem.thumbnail_video.setVisibility(View.GONE);
} else {
vItem.thumbnail_video.setVisibility(View.VISIBLE);
}
vItem.lyt_parent.setOnClickListener(view -> {
if (mOnItemClickListener != null) {
mOnItemClickListener.onItemClick(view, b, position);
}
});
} else {
((ProgressViewHolder) holder).progressBar.setIndeterminate(true);
}
if (getItemViewType(position) == VIEW_PROG) {
StaggeredGridLayoutManager.LayoutParams layoutParams = (StaggeredGridLayoutManager.LayoutParams) holder.itemView.getLayoutParams();
layoutParams.setFullSpan(true);
} else {
StaggeredGridLayoutManager.LayoutParams layoutParams = (StaggeredGridLayoutManager.LayoutParams) holder.itemView.getLayoutParams();
layoutParams.setFullSpan(false);
}
}
@Override
public int getItemCount() {
return items.size();
}
@Override
public int getItemViewType(int position) {
if (items.get(position) != null) {
return VIEW_ITEM;
} else {
return VIEW_PROG;
}
}
public void insertData(List<bell> items) {
setLoaded();
int positionStart = getItemCount();
int itemCount = items.size();
this.items.addAll(items);
notifyItemRangeInserted(positionStart, itemCount);
}
public void setLoaded() {
loading = false;
for (int i = 0; i < getItemCount(); i++) {
if (items.get(i) == null) {
items.remove(i);
notifyItemRemoved(i);
}
}
}
public void setLoading() {
if (getItemCount() != 0) {
this.items.add(null);
notifyItemInserted(getItemCount() - 1);
loading = true;
}
}
public void resetListData() {
this.items = new ArrayList<>();
notifyDataSetChanged();
}
public void setOnLoadMoreListener(OnLoadMoreListener onLoadMoreListener) {
this.onLoadMoreListener = onLoadMoreListener;
}
private void lastItemViewDetector(RecyclerView recyclerView) {
if (recyclerView.getLayoutManager() instanceof StaggeredGridLayoutManager) {
final StaggeredGridLayoutManager layoutManager = (StaggeredGridLayoutManager) recyclerView.getLayoutManager();
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
int lastPos = getLastVisibleItem(layoutManager.findLastVisibleItemPositions(null));
if (!loading && lastPos == getItemCount() - 1 && onLoadMoreListener != null) {
int current_page = getItemCount() / AppConfig.POST_PER_PAGE;
onLoadMoreListener.onLoadMore(current_page);
loading = true;
}
}
});
}
}
public interface OnLoadMoreListener {
void onLoadMore(int current_page);
}
private int getLastVisibleItem(int[] into) {
int last_idx = into[0];
for (int i : into) {
if (last_idx < i) last_idx = i;
}
return last_idx;
}
}
型
模型
import java.io.Serializable;
public class bell implements Serializable {
public int id;
public long unique_id;
public String title;
public String message;
public String big_image;
public String image;
public String content_type;
public String video_id;
public String link;
public long post_id;
public bell(long unique_id, String title, String message, String big_image, String image, String content_type, String video_id, String link, long post_id) {
this.unique_id = unique_id;
this.title = title;
this.message = message;
this.big_image = big_image;
this.image = image;
this.content_type = content_type;
this.video_id = video_id;
this.link = link;
this.post_id = post_id;
}
public bell() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public long getunique_id() {
return unique_id;
}
public void setunique_id(long unique_id) {
this.unique_id = unique_id;
}
public String gettitle() {
return title;
}
public void settitle(String title) {
this.title = title;
}
public String getmessage() {
return message;
}
public void setmessage(String message) {
this.message = message;
}
public String getbig_image() {
return big_image;
}
public void setbig_image(String big_image) {
this.big_image = big_image;
}
public String getimage() {
return image;
}
public void setimage(String image) {
this.image = image;
}
public String getcontent_type() {
return content_type;
}
public String getvideo_id() {
return video_id;
}
public void setvideo_id(String video_id) {
this.video_id = video_id;
}
public void setcontent_type(String content_type) {
this.content_type = content_type;
}
public long getpost_id() {
return post_id;
}
public void setpost_id(long post_id) {
this.post_id = post_id;
}
型
}
java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“java.util.List com.police.exam.databases.sqlite. Dborder.getAllbell()”如何slove
1条答案
按热度按时间wwodge7n1#
在片段中,您需要初始化
DbHandler
字符串