mercredi 1 juillet 2015

Simple solution for selecting multiple elements using WHERE OR in greenDAO?

I've got a list of primary keys and I need these elements from my greendao database.

The most trivial method would be to query each object idividually and inserting it into a list:

public List<MyObject> getMyObjectByIds(List<String> ids) {
    List<MyObject> result = new ArrayList<MyObject>();

    for (String id : ids) {
        QueryBuilder<MyObject> queryBuilder = myObjectDao.queryBuilder();
        MyObject myObject = queryBuilder.where(MyObjectDao.Properties.Id.eq(id)).unique();
        result.add(myObject);
    }

    return result;
}

However this seem quite ineffective since it would have to do ids.size() queries. A single query with multiple OR statements would be better. However, since the whereOr() and or() methods only except 2 or more parameters you'd have to make quite a few IF ELSE statements to catch lists with 0, 1 or 2 ids:

public List<MyObject> getMyObjectByIds(List<String> ids) {
    QueryBuilder<MyObject> queryBuilder = myObjectDao.queryBuilder();

    if (ids.size() == 0) {
        List<MyObject> result = new ArrayList<MyObject>();
        return result;
    } else if (ids.size() == 1) {
        return queryBuilder.where(MyObjectDao.Properties.Id.eq(ids.get(0))).list();
    } else if (ids.size() == 2) {
        queryBuilder.whereOr(MyObjectDao.Properties.Id.eq(ids.get(0)), MyObjectDao.Properties.Id.eq(ids.get(1)));
        return queryBuilder.list();
    } else if (ids.size() >= 3) {
        queryBuilder.whereOr(MyObjectDao.Properties.Id.eq(ids.get(0)), MyObjectDao.Properties.Id.eq(ids.get(1)), getWhereConditionsEqIdRefFromThirdElementOn(ids));
        return queryBuilder.list();
    }
}

private WhereCondition[] getWhereConditionsEqIdFromThirdElementOn(List<String> ids) {
    WhereCondition[] whereConditions = new WhereCondition[ids.size() - 1];
    for (int i = 2; i < ids.size(); ++i) {
        whereConditions[i] = MyObjectDao.Properties.Id.eq(ids.get(i));
    }
    return whereConditions;
}

Honestly, this might be faster but it still seems quite ugly to me. Is there another way? Or do I have to make a raw query?

javascript/sqlite noob -declaration of variables

I'm trying to learn sqlite ,after some time of learning JS. I've recently found a short tutorial about how to create a to do list with sqlite and JS . here is some of the code:

var html5rocks = {};
html5rocks.webdb = {};
html5rocks.webdb.db = null;

html5rocks.webdb.open = function() {
  var dbSize = 5 * 1024 * 1024; // 5MB
  html5rocks.webdb.db = openDatabase("Todo", "1.0", "Todo manager", dbSize);
}

html5rocks.webdb.createTable = function() {
  var db = html5rocks.webdb.db;
  db.transaction(function(tx) {
    tx.executeSql("CREATE TABLE IF NOT EXISTS todo(ID INTEGER PRIMARY KEY ASC, todo TEXT, added_on DATETIME)", []);
  });
}

What I don't understand is why the declaration of html5rocks.webdb = {}; and html5rocks.webdb.db = null;' was written like that. How can you assign webdb and webdb.db in that way before you declare them as variables inside 'html5rocks{}?

I've never seen this way to declare variables. Can someone please explain ?

android: passing double data latitude and longitude can't show in map fragment

any one can help me? i got some project, my project is make a tourism application, is can show map for every place using latitude and logitude from database, i use this script.

double lat = 0;
double lng = 0;
if(cursor.moveToFirst()){
cursor.moveToPosition(position);
lat = cursor.getDouble(cursor.getColumnIndex("lat"));
lng = cursor.getDouble(cursor.getColumnIndex("lng"));

}

and then, i pass double data lat and lng to map1.class

Intent intent1  =   new Intent(this, map1.class);
intent1.putExtra("latx", lat);
intent1.putExtra("lngy", lng);
setResult(RESULT_OK, intent1);

in map1.class, i receive using this script.

Intent i = getIntent();
Double d1 = i.getDoubleExtra("latx", latitude1);
Double d2 = i.getDoubleExtra("lngy", longitude2);

 FragmentManager myFragmentManager = getSupportFragmentManager();
 SupportMapFragment mySupportMapFragment =  (SupportMapFragment)myFragmentManager.findFragmentById(R.id.map1);
  myMap = mySupportMapFragment.getMap();

 LatLng alam3 = new LatLng(d1, d2);
 MarkerOptions markerPosong = new MarkerOptions();
 markerPosong.position(alam3);
 markerPosong.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));

and why in fragment map can't show coordinate from latlng .? its like the data double isn't receive the data from database.

How to delete a single row in android sqlite

I have sqlite data represented on a ListView by a CustomListAdapter.On clicking a row an alert dialogue pops up that prompts the user to delete the single row from sqlite in my activity:

private void deleteDialog() {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(MyCart.this);
        alertDialog.setCancelable(false);
        alertDialog.setMessage("Delete item?");
        alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                myDb.deleteSingleContact(toString());
            }
        });
        alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();

            }
        });
        alertDialog.show();
    }

On my DBHelper.java:

 public void deleteSingleContact(String title){

        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(CONTACTS_TABLE_NAME, CONTACTS_COLUMN_TITLE + "=?", new String[]{title});
//KEY_NAME is a column name
    }

However the above code doesn't delete anything.I guess its the function i havent done correctly.Any suggestions?

Full DBHelper.java

public class DBHelper extends SQLiteOpenHelper {

    public static final String DATABASE_NAME = "MyDBName.db";
    public static final String CONTACTS_TABLE_NAME = "contacts";
    public static final String CONTACTS_COLUMN_ID = "id";
    public static final String CONTACTS_COLUMN_TITLE = "title";
    public static final String CONTACTS_COLUMN_AMOUNT = "amount";
    public static final String CONTACTS_COLUMN_DESC = "description";

    private HashMap hp;

    public DBHelper(Context context) {
        super(context, DATABASE_NAME, null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        db.execSQL(
                "create table contacts " +
                        "(id integer primary key, title text,amount float,description text)"
        );
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
        db.execSQL("DROP TABLE IF EXISTS contacts");
        onCreate(db);
    }

    public boolean insertContact(String title,  float amount, String description) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();

        contentValues.put("title", title);
        contentValues.put("amount", amount);
        contentValues.put("description", description);


        db.insert("contacts", null, contentValues);
        return true;
    }

    public Cursor getData(int id) {
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor res = db.rawQuery("select * from contacts where id=" + id + "", null);
        return res;
    }

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

    public boolean updateContact(Integer id, String title, float amount, String description) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put("title", title);
        contentValues.put("amount", amount);
        contentValues.put("description", description);

        db.update("contacts", contentValues, "id = ? ", new String[]{Integer.toString(id)});
        return true;
    }

    public void deleteContact() {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete("contacts", null, null);
        db.close();
    }

    public void deleteSingleContact(String title){

        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(CONTACTS_TABLE_NAME, CONTACTS_COLUMN_TITLE + "=?", new String[]{title});
//KEY_NAME is a column name
    }

    public boolean checkForTables() {
        boolean hasRows = false;
        SQLiteDatabase db = getReadableDatabase();
        Cursor cursor = db.rawQuery("SELECT COUNT(*) FROM " + CONTACTS_TABLE_NAME, null);
        cursor.moveToFirst();
        int count = cursor.getInt(0);
        if(count > 0)
            hasRows = true;
        db.close();
        return hasRows;
    }
    public ArrayList<ContactListItems> getAllContacts() {
        ArrayList<ContactListItems> contactList = new ArrayList<>();
        hp = new HashMap();
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor res = db.rawQuery("select * from contacts", null);
        res.moveToFirst();
        while (!res.isAfterLast()) {
                ContactListItems contactListItems = new ContactListItems();

                contactListItems.setTitle(res.getString(res
                        .getColumnIndex("title")));
                contactListItems.setAmount(res.getFloat(res
                        .getColumnIndex("amount")));
                contactListItems.setDescription(res.getString(res
                        .getColumnIndex("description")));
                contactList.add( contactListItems);
                res.moveToNext();
            }
        res.close();
        return contactList;
    }
    public int getTotalOfAmount(){
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor c=db.rawQuery("SELECT SUM(amount) FROM " +CONTACTS_TABLE_NAME,null);
        c.moveToFirst();
        int i=c.getInt(0);
        c.close();
        return i;
    }
}

IOS error inserting data on sqlite

i am on final project making GOLyrics apps for ios. my apps can search lyric and favorited it. but i have problems in my add favorite lyric, and i do not know why, im newbie in objective C especially in ios programming. help me please.

here's my add to favorite method:

  -(void)insertFav:(Favorite*)favssssdsd{

fileMgrs = [NSFileManager defaultManager];
sqlite3_stmt *stmt=nil;

NSString *sqlQuery=[NSString stringWithFormat:@"INSERT or REPLACE INTO fav (username,title,artist,image,song,lyric) VALUES ('%@','%@','%@','%@','%@','%@');",favssssdsd.username,favssssdsd.lirikTitle,favssssdsd.lirikArtist,favssssdsd.lirikImage,favssssdsd.lirikSong,favssssdsd.lirik];
NSLog(@"query:%@",sqlQuery);
const char *sql =[sqlQuery cStringUsingEncoding:NSUTF8StringEncoding];

//NSLog(@"row:%d",row);
//Open db
NSString *cruddatabase = [self.GetCacheDirectory stringByAppendingPathComponent:@"TB.sqlite"];
sqlite3_open([cruddatabase UTF8String], &db);
sqlite3_prepare_v2(db, sql, -1, &stmt, NULL);
@try
{
    if(sqlite3_step(stmt)==SQLITE_DONE)
    {
        NSLog(@"Succes insert fav");
    }
    else  NSLog(@"failed insert fav");


}
@catch (NSException *exception) {
    NSLog(@"An exception occured: %@", [exception reason]);
}

sqlite3_reset(stmt);

sqlite3_finalize(stmt);
sqlite3_close(db);
   }

the output is :

TestYey[1505:47536] query:INSERT or REPLACE INTO fav      (username,title,artist,image,song,lyric) VALUES ('shasapo','Stay','Rihanna','18.jpg','Stay.mp3','the lyrics in here');

TestYey[1505:47536] failed insert fav

Someone help me please :") i dont know why it isn't inserting

Search Database for String Containing Characters

I use the below code to search the exact string in the database. For example, if I would like to search for "abc", then I need to enter "abc". What I intend to do is to enable the searching without the exact string. For example, I can enter "bc" and return the "abc" as the result. I tried to change the englishWord.equals("") to englishWord.contains(""). However, this is not work.

public List<Bean> getWords(String englishWord) {
        if(englishWord.equals(""))
            return new ArrayList<Bean>();

        String sql = "SELECT * FROM " + TABLE_NAME +
                " WHERE " + ENGLISH + " LIKE ? ORDER BY " + ENGLISH + " LIMIT 100";

        SQLiteDatabase db = initializer.getReadableDatabase();

        Cursor cursor = null;
        try {
            cursor = db.rawQuery(sql, new String[]{englishWord + "%"});

            List<Bean> wordList = new ArrayList<Bean>();
            while(cursor.moveToNext()) {
                int id = cursor.getInt(0);
                String english = cursor.getString(1);
                String bangla = cursor.getString(2);
                String status = cursor.getString(3);
                wordList.add(new Bean(id, english, bangla, status));
            }

            return wordList;
        } catch (SQLiteException exception) {
            exception.printStackTrace();
            return null;
        } finally {
            if (cursor != null)
                cursor.close();
        }
    }

Deleting records which are generated dynamically in android

I am working on a app which stores record. Until now i have successfully added the data into data base and retrieve it from data base.

Now my problem is deleting the records. I know the query of deleting a record but in which the record is being is displayed is AlertDialog.

Below is my code.

public class MainActivity extends ActionBarActivity {

EditText topic;
EditText description;
Button add;
SQLiteDatabase db;

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

    Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    topic = (EditText)findViewById(R.id.addTopic);
    description = (EditText)findViewById(R.id.addDescription);
    add = (Button)findViewById(R.id.addBtn);

   db = openOrCreateDatabase("RecordMaster",Context.MODE_PRIVATE,null);
    db.execSQL("CREATE TABLE IF NOT EXISTS records(topic VARCHAR,description VARCHAR)");

    add.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            if(v==add)
            {
                if(topic.getText().toString().trim().length()==0 || description.getText().toString().trim().length()==0)
                {
                    Toast.makeText(getApplicationContext(), "Please Enter Topic & Description",Toast.LENGTH_LONG).show();
                    return;
                }
            }
            db.execSQL(" INSERT INTO records VALUES('"+topic.getText()+"','"+description.getText()+"') ");
            Toast.makeText(getApplicationContext(), "Record Added Successfully", Toast.LENGTH_LONG).show();
            topic.setText("");
            description.setText("");
        }
    });


}

public void showMessage(String title,String message)
{
    Builder builder=new Builder(this);
    builder.setCancelable(true);
    builder.setTitle(title);
    builder.setMessage(message);
    builder.show();
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.

    int id = item.getItemId();

    if (id == R.id.exit) {
         Intent intent = new Intent(Intent.ACTION_MAIN);
         intent.addCategory(Intent.CATEGORY_HOME);
         intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
         intent.putExtra("Do You Wanna EXIT ?", true);
         startActivity(intent);
         finish();
         Toast.makeText(getApplicationContext(), "Thanks For Using My Application", Toast.LENGTH_LONG).show();
    }

    if(id == R.id.display_record){

        db = openOrCreateDatabase("RecordMaster",Context.MODE_PRIVATE,null);

     Cursor c = db.rawQuery("SELECT * FROM records",null);

        if(c.getCount()==0)
        {
            Toast.makeText(getApplicationContext(), "No records available", Toast.LENGTH_LONG).show();
        }

        StringBuffer buffer = new StringBuffer();
        while(c.moveToNext())
        {
            buffer.append("Topic: -"+c.getString(0)+"\n");
            buffer.append("Description: -"+c.getString(1)+"\n\n");
        }

        showMessage("Records",buffer.toString());

        db.close();
    }

    if(R.id.delete_record)
    {
        //what code i have to write to delete the records
    }
    return super.onOptionsItemSelected(item);
}

I am referring http://ift.tt/1ozHQjl. In this it is done on button click where we have to enter roll_no but i want that when i click on my menu item(delete) it should show all my records with check box so i can check one or multiple records to delete.