samedi 10 octobre 2015

Database with repeating records

I have sqlite database in my app.When I have Internet connection,data is saved and when I haven't Internet connection,I loaded data from database and show that in ListView.But in this ListView I have many records,I think when I have Internet I created records how many times,how I start the app.But now how can I delete all records,create new,and dont create the same records every time when I start my app? MainList:

public class MainList extends ListFragment{
    SqlHelper dbHelper;
    ListView mainList;
    ProgressBar progBar;
    private static String url = "http://ift.tt/1MiJRNN";
    private static final String TITLE = "title";
    private static final String DESCRIPTION = "description";
    private static final String IMAGE = "image";
    ArrayList<HashMap<String,String>> jsonlist1 = new ArrayList<HashMap<String, String>>();
    ArrayList<HashMap<String,String>> bdList = new ArrayList<HashMap<String, String>>();
    public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.list_fragme, null);
        mainList = (ListView)v.findViewById(android.R.id.list);
progBar = (ProgressBar) v.findViewById(R.id.progressBar);
        return v;
    }




    public void onActivityCreated(Bundle savedInstanceState){
        super.onActivityCreated(savedInstanceState);
if (isNetworkConnected()==true) {
    new ProgressTask().execute();
}
        else{
    displaysavedlv();
}
    }

    @Override
    public void onListItemClick(ListView l, View view, int position, long id) {
        super.onListItemClick(l, view, position, id);
        String title = jsonlist1.get(position).get("title");
        String description= jsonlist1.get(position).get("description");
        String image = jsonlist1.get(position).get("image");


        MyDetailFragment detailFragment = new MyDetailFragment();
        Bundle bundle = new Bundle();
        if(isNetworkConnected()==true) {
            bundle.putString("title", title);
            bundle.putString("description", description);
            bundle.putString("image", image);
        }
        else
        {
            String dbtitle= bdList.get(position).get("title");
            String dbdescription = bdList.get(position).get("description");
            String dvimage = bdList.get(position).get("image");
            bundle.putString("title",dbtitle);
            bundle.putString("description",dbdescription);
            bundle.putString("image",dvimage);
        }
        detailFragment.setArguments(bundle);
        FragmentTransaction fragmentTransaction = getActivity().getFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.FragmentCont,detailFragment);
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commit();
    }

    private class ProgressTask extends AsyncTask<String,Void,Boolean> {
        private ProgressDialog dialog;
        private Activity activity;
        private MainActivity context;
        private String[] params;

        public ProgressTask(MainActivity activity) throws SQLException {
            this.activity = getActivity();
            context = activity;
            dialog = new ProgressDialog(getActivity().getApplicationContext());

        }

        public ProgressTask()  {
            dialog = new ProgressDialog(getActivity().getApplicationContext());
            try {
                dbHelper = new SqlHelper(getActivity().getApplicationContext());
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        @Override
        protected Boolean doInBackground(String... params) {
            this.params = params;
            JSONParser jParser = new JSONParser();
            JSONArray json = jParser.getJSONFromUrl(url);
            for(int i =0;i<json.length();i++) {
                try {
                    JSONObject c = json.getJSONObject(i);
                    String vtitle = c.getString(TITLE);
                    String vdescription = c.getString(DESCRIPTION);
                    String vimage = c.getString(IMAGE);
                    dbHelper.open();
                    dbHelper.createEntry(vtitle, vimage, vdescription);
                    dbHelper.close();

                    HashMap<String, String> map = new HashMap<>();
                    map.put(TITLE, vtitle);
                    map.put(DESCRIPTION, vdescription);
                    map.put(IMAGE, vimage);

                    jsonlist1.add(map);

                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }


        protected void onPreExecute(){
progBar.setVisibility(View.VISIBLE);
        }
        protected void onPostExecute(final Boolean success){



if (isNetworkConnected()==true) {
    progBar.setVisibility(View.GONE);
    CustomListAdapter adapter = new CustomListAdapter(getActivity(), jsonlist1, R.layout.list_item, new String[]{TITLE, DESCRIPTION}, new int[]{R.id.title, R.id.description});
    mainList.setAdapter(adapter);
}
            else {
    displaysavedlv();
}




        }

    }
    private void displaysavedlv() {
        try {
            dbHelper = new SqlHelper(getActivity().getApplicationContext());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        bdList = dbHelper.getAllData();

        CustomListAdapter adapter1 = new CustomListAdapter(getActivity(), bdList, R.id.list_item, new String[]{TITLE, DESCRIPTION}, new int[]{R.id.title, R.id.description});
        mainList.setAdapter(adapter1);
    }
    private boolean isNetworkConnected() {
        ConnectivityManager cm = (ConnectivityManager)getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = cm.getActiveNetworkInfo();
        if (ni == null) {
            // There are no active networks.
            return false;
        } else
            return true;
    }
}

SqlHelper class:

public class SqlHelper {
    String title;
    String description;
    String image;
    private static final String TEXT_TYPE = " TEXT";
    private static final String COMMA_SEP = ",";
    public static final String KEY_ROWID = "_id";
    public static final String KEY_TITLE = "title";
    public static final String KEY_DESCRIPTION = "description";
    public static final String KEY_IMAGE = "image";
    private SqlHelper mDb;
    private static final String DATABASE_NAME = "DBCategory";
    private static final String DATABASE_TABLE = "categoryTable";
    private static final int DATABASE_VERSION = 1;
    private static final String SQL_CREATE_ENTRIES =
            "CREATE TABLE " + DATABASE_TABLE + " (" +
                    KEY_ROWID + " INTEGER PRIMARY KEY," +
                    KEY_TITLE + TEXT_TYPE + COMMA_SEP +
                    KEY_DESCRIPTION + TEXT_TYPE + COMMA_SEP + KEY_IMAGE + TEXT_TYPE +

                    " )";
    private DbHelper ourHelper;
    private final Context ourContext;
    private SQLiteDatabase ourDatabase;

    public SqlHelper(Context c) throws SQLException {
        ourContext = c;
        try {
            open();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public SqlHelper open() throws SQLException{
        ourHelper = new DbHelper(ourContext);
        ourDatabase = ourHelper.getWritableDatabase();
        return this;
    }

    public void close(){
        ourHelper.close();
    }





    private static class DbHelper extends SQLiteOpenHelper {

        public DbHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
            // TODO Auto-generated constructor stub
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
                            KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
                            KEY_TITLE + " TEXT NOT NULL," + KEY_DESCRIPTION + " TEXT NOT NULL," + KEY_IMAGE + " TEXT NOT NULL );"
            );
        }

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

    }

    public long createEntry(String title, String description,String image) {
        ContentValues cv = new ContentValues();
        cv.put(KEY_TITLE, title);
        cv.put(KEY_DESCRIPTION,description);
        cv.put(KEY_IMAGE, image);

        return ourDatabase.insert(DATABASE_TABLE, null, cv);
    }

    public ArrayList<HashMap<String, String>> getAllData()
    {
        ArrayList<HashMap<String, String>> array_list = new ArrayList<HashMap<String, String>>();

        //hp = new HashMap();
        SQLiteDatabase db = this.ourHelper.getReadableDatabase();
        Cursor res =  db.rawQuery( "select * from categoryTable", null );
        res.moveToFirst();

        while(res.isAfterLast() == false){

            HashMap<String,String>  hashmap = new HashMap<String, String>();
            hashmap.put("title", res.getString(res.getColumnIndex(KEY_TITLE)));
            hashmap.put("description", res.getString(res.getColumnIndex(KEY_IMAGE)));
            hashmap.put("image", res.getString(res.getColumnIndex(KEY_DESCRIPTION)));




            array_list.add(hashmap);
            res.moveToNext();
        }
        return array_list;
    }
}

Aucun commentaire:

Enregistrer un commentaire