我的数据没有保存到我的应用程序中,但是为什么呢?

时间:2018-11-29 03:06:07

标签: sqlite android-fragments android-sqlite android-adapter

我已经创建了一个应用程序并将sqlite数据库添加到我的应用程序中,但是该应用程序没有将数据保存到sqlite数据库中,但是为什么呢? 我在这里发布代码。如果您在我的代码中遇到任何错误,请帮助我解决。 如果您需要我的应用程序的更多代码,请发表评论。.我将在此处发布代码。 我将感谢你...

HomeLatestAdapter

LatestVideoAdapter.java

public class LatestVideoAdapter extends RecyclerView.Adapter<LatestVideoAdapter.ItemRowHolder> {

    private ArrayList<ItemMostView> dataList;
    private Context mContext;
    private DatabaseHelper databaseHelper;
    private InterstitialAd mInterstitial;
    private int AD_COUNT = 0;

    public LatestVideoAdapter(Context context, ArrayList<ItemMostView> dataList) {
        this.dataList = dataList;
        this.mContext = context;
        databaseHelper = new DatabaseHelper(mContext);
    }

    @Override
    public ItemRowHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_most_view_item, parent, false);
        return new ItemRowHolder(v);
    }

    @Override
    public void onBindViewHolder(final ItemRowHolder holder, final int position) {
        final ItemMostView singleItem = dataList.get(position);

        holder.text.setText(singleItem.getVideoName());
        holder.txt_cat_name.setText(singleItem.getCategoryName());
        holder.txt_time.setText(singleItem.getDuration());
        holder.text_view.setText(JsonUtils.Format(Integer.parseInt(singleItem.getViewC())));
        if (singleItem.getType().equals("local")) {
            Picasso.with(mContext).load(singleItem.getImageUrl()).into(holder.image);
        } else if (singleItem.getType().equals("server_url")) {
            Picasso.with(mContext).load(singleItem.getImageUrl()).into(holder.image);
        } else if (singleItem.getType().equals("youtube")) {
            Picasso.with(mContext).load(Constant.YOUTUBE_IMAGE_FRONT + singleItem.getVideoId() + Constant.YOUTUBE_IMAGE_BACK).into(holder.image);
        }

        holder.lyt_parent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Constant.LATEST_IDD = singleItem.getId();

                if (Constant.SAVE_ADS_FULL_ON_OFF.equals("true")) {
                    AD_COUNT++;
                    if (AD_COUNT == Integer.parseInt(Constant.SAVE_ADS_CLICK)) {
                        AD_COUNT = 0;
                        mInterstitial = new InterstitialAd(mContext);
                        mInterstitial.setAdUnitId(Constant.SAVE_ADS_FULL_ID);
                        AdRequest adRequest;
                        if (JsonUtils.personalization_ad) {
                            adRequest = new AdRequest.Builder()
                                    .build();
                        } else {
                            Bundle extras = new Bundle();
                            extras.putString("npa", "1");
                            adRequest = new AdRequest.Builder()
                                    .addNetworkExtrasBundle(AdMobAdapter.class, extras)
                                    .build();
                        }
                        mInterstitial.loadAd(adRequest);
                        mInterstitial.setAdListener(new AdListener() {
                            @Override
                            public void onAdLoaded() {
                                // TODO Auto-generated method stub
                                super.onAdLoaded();
                                if (mInterstitial.isLoaded()) {
                                    mInterstitial.show();
                                }
                            }

                            public void onAdClosed() {
                                Intent intent_single = new Intent(mContext, ActivityVideoDetails.class);
                                mContext.startActivity(intent_single);

                            }

                            @Override
                            public void onAdFailedToLoad(int errorCode) {
                                Intent intent_single = new Intent(mContext, ActivityVideoDetails.class);
                                mContext.startActivity(intent_single);
                            }
                        });
                    } else {
                        Intent intent_single = new Intent(mContext, ActivityVideoDetails.class);
                        mContext.startActivity(intent_single);
                    }
                } else {
                    Intent intent_single = new Intent(mContext, ActivityVideoDetails.class);
                    mContext.startActivity(intent_single);
                }

            }
        });

        if (databaseHelper.getFavouriteById(singleItem.getId())) {
            holder.floating_fav.setImageResource(R.drawable.ic_fav_hov);
        } else {
            holder.floating_fav.setImageResource(R.drawable.ic_fav);
        }

        holder.floating_fav.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ContentValues fav_list = new ContentValues();
                if (databaseHelper.getFavouriteById(singleItem.getId())) {
                    databaseHelper.removeFavouriteById(singleItem.getId());
                    holder.floating_fav.setImageResource(R.drawable.ic_fav);
                    Toast.makeText(mContext, mContext.getString(R.string.favourite_remove), Toast.LENGTH_SHORT).show();
                } else {
                    fav_list.put(DatabaseHelper.KEY_ID, singleItem.getId());
                    fav_list.put(DatabaseHelper.KEY_TITLE, singleItem.getVideoName());
                    fav_list.put(DatabaseHelper.KEY_IMAGE, singleItem.getImageUrl());
                    fav_list.put(DatabaseHelper.KEY_VIEW, singleItem.getViewC());
                    fav_list.put(DatabaseHelper.KEY_TYPE, singleItem.getType());
                    fav_list.put(DatabaseHelper.KEY_PID, singleItem.getVideoId());
                    fav_list.put(DatabaseHelper.KEY_TIME, singleItem.getDuration());
                    fav_list.put(DatabaseHelper.KEY_CNAME, singleItem.getCategoryName());
                    databaseHelper.addFavourite(DatabaseHelper.TABLE_FAVOURITE_NAME, fav_list, null);
                    holder.floating_fav.setImageResource(R.drawable.ic_fav_hov);
                    Toast.makeText(mContext, mContext.getString(R.string.favourite_add), Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    @Override
    public int getItemCount() {
        return (null != dataList ? dataList.size() : 0);
    }

    public class ItemRowHolder extends RecyclerView.ViewHolder {
        public ImageView image;
        public TextView text, txt_cat_name, txt_time, text_view;
        public LinearLayout lyt_parent;
        FloatingActionButton floating_fav;

        public ItemRowHolder(View itemView) {
            super(itemView);
            image = itemView.findViewById(R.id.image);
            text = itemView.findViewById(R.id.text);
            lyt_parent = itemView.findViewById(R.id.rootLayout);
            txt_cat_name = itemView.findViewById(R.id.text_category);
            txt_time = itemView.findViewById(R.id.text_time);
            text_view = itemView.findViewById(R.id.text_view);
            floating_fav = itemView.findViewById(R.id.floating_fav);

        }
    }
}

DatabaseHelper.java

public class DatabaseHelper extends SQLiteOpenHelper {

    public static final int DATABASE_VERSION = 1;
    public static final String DATABASE_NAME = "favoritevideo.db";
    public static final String TABLE_FAVOURITE_NAME = "favourite";

    public static final String KEY_ID = "id";
    public static final String KEY_TITLE = "title";
    public static final String KEY_IMAGE = "image";
    public static final String KEY_VIEW = "rate";
    public static final String KEY_TYPE = "type";
    public static final String KEY_PID = "playid";
    public static final String KEY_TIME = "time";
    public static final String KEY_CNAME = "cname";


    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        String CREATE_FAVOURITE_TABLE = "CREATE TABLE " + TABLE_FAVOURITE_NAME + "("
                + KEY_ID + " INTEGER,"
                + KEY_TITLE + " TEXT,"
                + KEY_IMAGE + " TEXT,"
                + KEY_VIEW + " TEXT,"
                + KEY_TYPE + " TEXT,"
                + KEY_PID + " TEXT,"
                + KEY_TIME + " TEXT,"
                + KEY_CNAME + " TEXT"
                + ")";
        db.execSQL(CREATE_FAVOURITE_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVOURITE_NAME);
        // Create tables again
        onCreate(db);
    }

    public boolean getFavouriteById(String story_id) {
        boolean count = false;
        SQLiteDatabase db = this.getWritableDatabase();
        String[] args = new String[]{story_id};
        Cursor cursor = db.rawQuery("SELECT id FROM favourite WHERE id=? ", args);
        if (cursor.moveToFirst()) {
            count = true;
        }
        cursor.close();
        db.close();
        return count;
    }

    public void removeFavouriteById(String _id) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.execSQL("DELETE FROM  favourite " + " WHERE " + KEY_ID + " = " + _id);
        db.close();
    }

    public long addFavourite(String TableName, ContentValues contentvalues, String s1) {
        SQLiteDatabase db = this.getWritableDatabase();
        return db.insert(TableName, s1, contentvalues);
    }

    public ArrayList<ItemMostView> getFavourite() {
        ArrayList<ItemMostView> chapterList = new ArrayList<>();
        String selectQuery = "SELECT *  FROM "
                + TABLE_FAVOURITE_NAME;
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);
        if (cursor.moveToFirst()) {
            do {
                ItemMostView contact = new ItemMostView();
                contact.setId(cursor.getString(cursor.getColumnIndexOrThrow(KEY_ID)));
                contact.setVideoName(cursor.getString(cursor.getColumnIndexOrThrow(KEY_TITLE)));
                contact.setImageUrl(cursor.getString(cursor.getColumnIndexOrThrow(KEY_IMAGE)));
                contact.setViewC(cursor.getString(cursor.getColumnIndexOrThrow(KEY_VIEW)));
                contact.setType(cursor.getString(cursor.getColumnIndexOrThrow(KEY_TYPE)));
                contact.setVideoId(cursor.getString(cursor.getColumnIndexOrThrow(KEY_PID)));
                contact.setDuration(cursor.getString(cursor.getColumnIndexOrThrow(KEY_TIME)));
                contact.setCategoryName(cursor.getString(cursor.getColumnIndexOrThrow(KEY_CNAME)));
                 chapterList.add(contact);
            } while (cursor.moveToNext());
        }
        cursor.close();
        db.close();
        return chapterList;
    }
}

latestDatabaseHelper.java

public class latestDatabaseHelper extends SQLiteOpenHelper {

    public static final int DATABASE_VERSION = 1;
    public static final String DATABASE_NAME = "latest.db";
    public static final String TABLE_FAVOURITE_NAME = "latestvideo";

    public static final String KEY_ID = "id";
    public static final String KEY_AUTO_ID = "auto_id";
    public static final String KEY_TITLE = "title";
    public static final String KEY_IMAGE = "image";
    public static final String KEY_VIEW = "rate";
    public static final String KEY_TYPE = "type";
    public static final String KEY_PID = "playid";
    public static final String KEY_TIME = "time";
    public static final String KEY_CNAME = "cname";


    public latestDatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        String CREATE_FAVOURITE_TABLE = "CREATE TABLE " + TABLE_FAVOURITE_NAME + "("
                + KEY_ID + " INTEGER,"
                + KEY_AUTO_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
                + KEY_TITLE + " TEXT,"
                + KEY_IMAGE + " TEXT,"
                + KEY_VIEW + " TEXT,"
                + KEY_TYPE + " TEXT,"
                + KEY_PID + " TEXT,"
                + KEY_TIME + " TEXT,"
                + KEY_CNAME + " TEXT"
                + ")";
        db.execSQL(CREATE_FAVOURITE_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVOURITE_NAME);
        // Create tables again
        onCreate(db);
    }

    public boolean getFavouriteByIdRecent(String story_id) {
        boolean count = false;
        SQLiteDatabase db = this.getWritableDatabase();
        String[] args = new String[]{story_id};
        Cursor cursor = db.rawQuery("SELECT id FROM recentfavourite WHERE id=? ", args);
        if (cursor.moveToFirst()) {
            count = true;
        }
        cursor.close();
        db.close();
        return count;
    }

    public void removeFavouriteByIdRecent(String _id) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.execSQL("DELETE FROM  recentfavourite " + " WHERE " + KEY_ID + " = " + _id);
        db.close();
    }

    public long addFavouriteRecent(String TableName, ContentValues contentvalues, String s1) {
        SQLiteDatabase db = this.getWritableDatabase();
        return db.insert(TableName, s1, contentvalues);
    }

    public ArrayList<ItemMostView> getFavouriteRecent() {
        ArrayList<ItemMostView> chapterList = new ArrayList<>();
        String selectQuery = "SELECT *  FROM "
                + TABLE_FAVOURITE_NAME +" ORDER BY auto_id DESC";
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);
        if (cursor.moveToFirst()) {
            do {
                ItemMostView contact = new ItemMostView();
                contact.setId(cursor.getString(cursor.getColumnIndexOrThrow(KEY_ID)));
                contact.setVideoName(cursor.getString(cursor.getColumnIndexOrThrow(KEY_TITLE)));
                contact.setImageUrl(cursor.getString(cursor.getColumnIndexOrThrow(KEY_IMAGE)));
                contact.setViewC(cursor.getString(cursor.getColumnIndexOrThrow(KEY_VIEW)));
                contact.setType(cursor.getString(cursor.getColumnIndexOrThrow(KEY_TYPE)));
                contact.setVideoId(cursor.getString(cursor.getColumnIndexOrThrow(KEY_PID)));
                contact.setDuration(cursor.getString(cursor.getColumnIndexOrThrow(KEY_TIME)));
                contact.setCategoryName(cursor.getString(cursor.getColumnIndexOrThrow(KEY_CNAME)));
                chapterList.add(contact);
            } while (cursor.moveToNext());
        }
        cursor.close();
        db.close();
        return chapterList;
    }
}

LatestVideoFragment.java

public class LatestVideoFragment extends Fragment {

    private static final String SubCatId = "ID";
    String selectedSubCatId;

    ArrayList<ItemMostView> mListItem;
    public RecyclerView recyclerView;
    LatestVideoAdapter LatestVideoAdapter;
    latestDatabaseHelper latestDatabaseHelper;
    TextView textView;
    private ProgressBar progressBar;
    int page = 1;



    public static LatestVideoFragment newInstance(String SCatId) {
        LatestVideoFragment f = new LatestVideoFragment();
        Bundle args = new Bundle();
        args.putString(SubCatId, SCatId);
        f.setArguments(args);
        return f;
    }




    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_latest_video, container, false);

        selectedSubCatId = getArguments().getString(SubCatId);
        mListItem = new ArrayList<>();

        latestDatabaseHelper = new latestDatabaseHelper(requireActivity());
        progressBar = rootView.findViewById(R.id.progressBar);
        recyclerView = rootView.findViewById(R.id.rv_video);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 1));
        ItemOffsetDecoration itemDecoration = new ItemOffsetDecoration(requireActivity(), R.dimen.item_offset);
        recyclerView.addItemDecoration(itemDecoration);

        if (JsonUtils.isNetworkAvailable(requireActivity())) {
            new getSubCat().execute(Constant.CATEGORY_ITEM_URL + selectedSubCatId + "&page=" + page);
            Log.e("yes", "yes");
        }

        return rootView;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            Log.e("yes", "yes");
        } else {
            Log.e("yes", "no");

        }
    }

    private class getSubCat extends AsyncTask<String, Void, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressBar.setVisibility(View.VISIBLE);
            recyclerView.setVisibility(View.GONE);
        }

        @Override
        protected String doInBackground(String... params) {
            return JsonUtils.getJSONString(params[0]);
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            progressBar.setVisibility(View.GONE);
            recyclerView.setVisibility(View.VISIBLE);

            if (null == result || result.length() == 0) {
                showToast(getString(R.string.no_data));
            } else {
                try {
                    JSONObject mainJson = new JSONObject(result);
                    JSONArray jsonArray = mainJson.getJSONArray(Constant.CATEGORY_ARRAY_NAME);
                    JSONObject objJson;
                    for (int i = 0; i < jsonArray.length(); i++) {
                        objJson = jsonArray.getJSONObject(i);

                        ItemMostView objItem = new ItemMostView();

                        objItem.setId(objJson.getString(Constant.LATEST_ID));
                        objItem.setCategoryId(objJson.getString(Constant.LATEST_CATID));
                        objItem.setCategoryName(objJson.getString(Constant.LATEST_CAT_NAME));
                        objItem.setVideoUrl(objJson.getString(Constant.LATEST_VIDEO_URL));
                        objItem.setVideoId(objJson.getString(Constant.LATEST_VIDEO_ID));
                        objItem.setVideoName(objJson.getString(Constant.LATEST_VIDEO_NAME));
                        objItem.setDuration(objJson.getString(Constant.LATEST_VIDEO_DURATION));
                        objItem.setDescription(objJson.getString(Constant.LATEST_VIDEO_DESCRIPTION));
                        objItem.setImageUrl(objJson.getString(Constant.LATEST_IMAGE_URL));
                        objItem.setType(objJson.getString(Constant.LATEST_TYPE));
                        objItem.setViewC(objJson.getString(Constant.LATEST_VIEW));

                        mListItem.add(objItem);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                displayData();
            }
        }
    }


    @Override
    public void onResume() {
        super.onResume();
        mListItem = latestDatabaseHelper.getFavouriteRecent();
        displayData();
    }
    private void displayData() {
        if (getActivity() != null) {
            LatestVideoAdapter = new LatestVideoAdapter(getActivity(), mListItem);
            recyclerView.setAdapter(LatestVideoAdapter);
        }

    }
    public void showToast(String msg) {
        Toast.makeText(getActivity(), msg, Toast.LENGTH_LONG).show();
    }

}

0 个答案:

没有答案