传入的通知数据保存在SQLITE中的SQLITE中.如何检索.我已经将数据从SQLite传输到碎片.我没有任何数据.

sqlite data

我已经try 了SQLite来分割这个错误-&>说

Java.lang.NullPointerException:try 调用虚方法 ‘java.util.List 空值上的com.police.exam.databases.sqlite.DbHandler.getAllbell()‘ 对象引用

DbHandler

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 转接器bell;
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 转接器
    转接器bell = new Adapterbell(getActivity(), recyclerView,data);
    recyclerView.setAdapter(转接器bell);

    // on item list clicked
    转接器bell.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:try 调用虚方法 ‘java.util.List 空值上的com.police.exam.databases.sqlite.DbHandler.getAllbell()‘ 对象引用 how to slove

推荐答案

 private void loadDataFromDatabase() {
   databaseHandler = new DatabaseHelper(this);
   data = databaseHandler.getAllbell();
}

Android相关问答推荐

如何使用Jetpack Compose实现此底表?

无法将Kotlin序列化添加到Android项目

如何在Android中编写挂起函数和stateflow的单元测试

如何在初始合成期间在可组合函数中调用/获取远程API中的数据[防止无限重组]

如何共享没有';t是否存在?(仅信息)在Android?

android回收器查看点击事件无响应

需要 java 17 而不是 java 11:Android CI-CD GitHub Actions

列表更改时,RecyclerView 中的列表不会更新

Compose 状态不是 recomposing

通过 adb 解压并重新安装后 Android 应用程序崩溃

获取 ArithmeticException:除以零,但我没有在任何地方除以零

如何在jetpack compose中通过lamda返回columnScope/RowScope

java.lang.String 类型的值 Forbidden 无法转换为 JSONObject

如何在 Jetpack Compose 中为中心对齐设置动画?

是什么让 Android Studio 中的按钮变成紫色?加上新手的其他奇怪行为

firebase-messaging和firebase-inappmessaging-display之间有什么区别?

如何在 Jetpack compose 中将 Canvas 中的文本居中?

Android Jetpack Compose - 找不到 R.drawable?

Android Studio,Db 连接错误:发生异常情况导致驱动程序失败.请报告此异常

lambda 函数中的类型不匹配 - Kotlin