lundi 12 octobre 2015

Android Sqlite rating bar

Currently my codes is working except for 2 issues.

Issue : 1. Only able to add name and rating once

2. Can only update the ratings not the name

Hi all if anyone can take sometime to take a lot will appreciate it.

MainActivity.java

public class MainActivity extends AppCompatActivity {

    private RatingBar ratingBar;
    private DatabaseHandler db;
    ListView lvInfo;
    EditText txtName;
    ArrayList<String> ArrayofName = new ArrayList<>();
    List<Result> results;
    static ArrayAdapter<String> dbAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        lvInfo = (ListView) findViewById(R.id.listView);
        txtName = (EditText) findViewById(R.id.editText);
        ratingBar = (RatingBar) findViewById(R.id.ratingBar);

        db = new DatabaseHandler(this);
        dbAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, android.R.id.text1, ArrayofName);
        lvInfo.setAdapter(dbAdapter);

        lvInfo.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                txtName.setText(results.get(position).getName());
               ratingBar.setRating(results.get(position).getRating());

            }
        });
        DisplayAll();
    }

    public void DisplayAll() {
        results = db.getAllResults();
        ArrayofName.clear();
        for (Result rs : results) {
            ArrayofName.add(rs.getId() + ".\t" + rs.getName() + ".\t" + rs.getRating());
        }
        dbAdapter.notifyDataSetChanged();
        txtName.setText("");
        ratingBar.setRating(5);
    }

    public void AddResult(View view) {
        if ((txtName.getText().length() == 0) || (ratingBar.getRating() == 0) )
            Toast.makeText(this, "Please enter the name and rating to be added!",  Toast.LENGTH_LONG).show();
        else {
            Result tmp = new Result(txtName.getText().toString(),
                    ratingBar.getRating() );

            db.addResult(tmp);
            DisplayAll();
            Toast.makeText(this, "Results Added!", Toast.LENGTH_LONG).show();
        }
    }

    public void UpdateResult(View view) {
        if ((txtName.getText().length() == 0) || (ratingBar.getRating() == 0) )
            Toast.makeText(this, "Please select result to be updated!", Toast.LENGTH_LONG).show();
        else {
            Result tmp = new Result(txtName.getText().toString(),ratingBar.getRating() );

            db.updateResult(tmp);
            DisplayAll();
            Toast.makeText(this, "Result Updated!", Toast.LENGTH_LONG).show();
        }
    }
    }

DatabaseHandler.java

public class DatabaseHandler extends SQLiteOpenHelper {

        private static final int DATABASE_VERSION = 1;
        private static final String DATABASE_NAME = Environment.getExternalStorageDirectory().toString() + "/result.db";
       // private  static final String DATABASE_NAME = "result";
        private static final String TABLE_RESULT = "Result";
        private static final String KEY_ID = "id";
        private static final String KEY_NAME = "name";
        private static final String KEY_RATING = "rating";

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

        //creating Tables
        @Override
        public void onCreate(SQLiteDatabase db){
            String CREATE_RESULTS_TABLE = "CREATE TABLE " + TABLE_RESULT + "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_NAME +
                    " TEXT,"+ KEY_RATING + " REAL)";
            db.execSQL(CREATE_RESULTS_TABLE);
        }

        //upgrading database
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
            //drop older table if existed
            db.execSQL("DROP TABLE IF EXISTS " + TABLE_RESULT);
            //create tables again
            onCreate(db);
        }

        public void addResult(Result result){
            SQLiteDatabase db = this.getWritableDatabase();
            ContentValues values = new ContentValues();
            values.put(KEY_NAME, result.getName());  //get name
            values.put(KEY_RATING, result.getRating());  //get rating
            db.insert(TABLE_RESULT, null, values);
            db.close();
        }

     public Result getResult(int id) {
            SQLiteDatabase db = this.getReadableDatabase();

         //build query
            Cursor cursor = db.query(TABLE_RESULT, new String[]{KEY_ID,
                            KEY_NAME, KEY_RATING}, KEY_ID + "=?",
                    new String[]{String.valueOf(id)}, null, null, null, null);

            if (cursor != null)  //if get results get the first one
                cursor.moveToFirst();
         //build result project
         Result result;
          result = new Result(Integer.parseInt(cursor.getString(0)),
                    cursor.getString(1), Float.parseFloat(cursor.getString(2)));
            return result;
        }

      public List<Result> getAllResults() {
            List<Result> resultList = new ArrayList<Result>();
            String selectQuery = "SELECT * FROM " + TABLE_RESULT;
            SQLiteDatabase db = this.getWritableDatabase();
            Cursor cursor = db.rawQuery(selectQuery, null);
            //looping through all rows and adding to list
            if (cursor.moveToFirst()) {
                do {
                    Result result = new Result();
                    result.setId(Integer.parseInt(cursor.getString(0)));
                    result.setName(cursor.getString(1));
                    result.setRating(Float.parseFloat(cursor.getString(2)));
                    resultList.add(result);
                } while (cursor.moveToNext());
            }
            return resultList;
        }

        public int updateResult(Result result){
            SQLiteDatabase db = this.getWritableDatabase();
            ContentValues values = new ContentValues();
            values.put(KEY_RATING ,result.getRating());
            values.put(KEY_NAME , result.getName());

            //updating row
            return db.update(TABLE_RESULT, values, KEY_NAME + " = ?", new String[]{String.valueOf(result.getName())});
        }

        public int getResultsCount(){
            String countQuery = "SELECT * FROM " + TABLE_RESULT;
            SQLiteDatabase db = this.getReadableDatabase();
            Cursor cursor = db.rawQuery(countQuery, null);
            cursor.close();
            return cursor.getCount();
        }

    }

Aucun commentaire:

Enregistrer un commentaire