mardi 30 juin 2015

How to retrieve existing number from column and update it

I am trying to make this simple app which calculates likes. Every-time you click on like button, it updates the counter in DB. The problem is, when I click it 5 times in one session, close and open again, it starts from 1 instead of 6 and shows 1,2,3,4,5,1. The value is lost once the session ends. I want it to be 6 and continue. How can I retrieve values from Database. Also, the rows are increasing. I want it to update the count in a single row and not add a new row every time I click the button.

This is my Main Activity:

public class MainActivity extends AppCompatActivity {
//declare
TextView showCounts;
MyDBHandler dbHandler;
Calculate obj;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //initialize objects
    showCounts = (TextView) findViewById(R.id.showCounts);
    dbHandler = new MyDBHandler(this, null, null, 1);
    obj = new Calculate();

}

public void likeButtonClicked(View view) //when like button is clicked
{
    obj.set_likes(1); //clicked 1 time
    boolean isLiked = dbHandler.incrementLikes(); //increment like in database
    printDatabase(); //show db
    if(isLiked) { //if like goes into db
        Toast.makeText(MainActivity.this, "Liked successfully", Toast.LENGTH_LONG).show();
    }
    else
        Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_LONG).show();
}

public void dislikeButtonClicked(View view)//dislike button is clicked
{
    obj.set_dislikes(1);
    boolean isInserted = dbHandler.incrementDislikes();
    printDatabase();
    if (isInserted) {
        Toast.makeText(MainActivity.this, "Added successfully", Toast.LENGTH_LONG).show();
    } else
        Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_LONG).show();
}

// print database
public void printDatabase()
{
    Cursor res = dbHandler.dbToString();
    if(res.getCount() == 0) //if table is empty
    {
        showCounts.setText("Error Nothing Found!");
        return;
    }

    StringBuffer str = new StringBuffer(); //if not empty
    while(res.moveToNext())
    {
        str.append("Likes: "+res.getString(0)+"\n");
    }
    showCounts.setText(str.toString()); //display database in textview
}

This is my Calculate class which has getters and setters:

public class Calculate {
private static int _likes;
private static int _dislikes;

public Calculate() 
{    }

public int get_likes() {
    return this._likes;
}

public void set_likes(int likes) {
    _likes += likes;

}

public int get_dislikes() {
    return this._dislikes;
}

public void set_dislikes(int dislikes) {
    _dislikes += dislikes;
} }//class ends

This is my DBHandler

public class MyDBHandler extends SQLiteOpenHelper{
//Declarations
private static final int DATABASE_VERSION = 4; 
private static final String DATABASE_NAME = "likeCalci.db";
public static final String TABLE_LIKECALCULATOR = "likeCalculator";
public static final String COLUMN_LIKE = "_likes";
public static final String COLUMN_DISLIKE = "_dislikes";
int like_count = 0;
int dislike_count = 0;

//Constructor
public MyDBHandler(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
    super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db)
{
    //create table
    String query = "CREATE TABLE " + TABLE_LIKECALCULATOR + "("+
            COLUMN_LIKE + " INTEGER " + COLUMN_DISLIKE + " INTEGER " + ");";
    db.execSQL(query);
}

@Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) //upgrade db
{
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_LIKECALCULATOR);
    onCreate(db);
}

//call when like button is clicked
public boolean incrementLikes()
{
    Calculate obj = new Calculate(); //obj
    like_count = obj.get_likes(); //get number of likes and store it
    ContentValues values = new ContentValues(); 
    values.put(COLUMN_LIKE, like_count); //put values in column
    SQLiteDatabase db = getWritableDatabase();
    long result = db.insert(TABLE_LIKECALCULATOR, null, values); //insert likes in db
    db.close();
    if(result == -1) //if insert is unsuccessful
        return false;
    else //if insert is successful
        return true;
}

public boolean incrementDislikes()
{
    Calculate obj = new Calculate();
    dislike_count = obj.get_dislikes();
    ContentValues values = new ContentValues();
    values.put(COLUMN_DISLIKE, dislike_count);
    SQLiteDatabase db = getWritableDatabase();
    long result = db.insert(TABLE_LIKECALCULATOR, null, values);
    db.close();
    if(result == -1)
        return false;
    else
        return true;
}

//print database
public Cursor dbToString() 
{
  SQLiteDatabase db  = this.getWritableDatabase();
    Cursor res = db.rawQuery("select * from "+TABLE_LIKECALCULATOR,null);
    return res;
}} //Class dbhandler ends

This is how the program runs: http://ift.tt/1R1vfrr

The dislike column is also not created. I started learning android few days back and this is taking a lot of time. Any times while dealing with Databases?

Populate ListView in android from SQLite database

I am just learning android programming and now i am making an app that uses database. For now i am using SQLite to store the data.

I have successfully created app which can stored/insert data in a database. Its working and i have checked my database using root Explorer.

Now on 2nd activity lets say DisplayRecords, i want to display my records into list view which will populate dynamically. How can i achieve that through programming.

here is my code of 2nd activity.

public class SearchResult extends ActionBarActivity {

ListView ls;
SQLiteDatabase db;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.search_result);

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


     ls = (ListView)findViewById(R.id.displayListView);

}

Can anyone please help me

Thanks

Need filtered result Optimised query

I have one table Called Device

        Device Table
id    deviceName     genId       description               overview 
1      PV motor       5       motor capacity  5        motor load is good
2      puf pannel     6       puf capacity  2          puf is for small load
3      gd motor       5       motor capacity 7         motor load is very good
4      rg motor       5       capacity is 3            low capacity

Now suppose this table has thousands of records , i need to add searching of rows like , genId=5 and description Like='%motor%' OR Overview Like='%motor%'

Search result will be 
1      PV motor       5       motor capacity  5        motor load is good

3      gd motor       5       motor capacity 7         motor load is very good

I need to construct query like first it search for genId 5 from table , then after it search for description and overview having text like motor because if my table had 100 records and then only 5 records of genSet=5 then my text search query will be executed on those 5 rows instead of 100 rows .

My Search query :
Select * From Device where (genId=5) And (description Like '%motor%' Or overview Like '%motor%') 

Can any one help me to create optimized query ?

ActiveAndroid abstract class table

Does anyone know if it is possible to create a table for an abstract class in ActiveAndroid. For example i could have an abstract class Animal with two concrete classes Dog and Cat. I want to be able to do something like:

List<Animal> animals = new Select().from(Animals.class).execute();

which would result in 'animals' containing all of the saved Cats and Dogs. Or:

Animal animal = new Select().from(Animals.class).where("name = ?", name).executeSingle();

Where 'animal' could be either a Cat or a Dog. Unfortunately when I do this I get an exception because no table is created for the abstract class Animal. Does anyone know how I might go about this using ActiveAndroid?

SQlite Calculation with same Values different Results

My Database contains this Values

  1. ROW: productName = Product 1, purchasePrice = 5099 , tax = 16, price = 10099
  2. ROW: productName = Product 1, purchasePrice = 5099 , tax = 16, price = 10099
  3. ROW: productName = Product 1, purchasePrice = 5099 , tax = 16, price = 10099
  4. ROW: productName = Product 1, purchasePrice = 5099 , tax = 16, price = 10099

  5. ROW: productName = Product 2, purchasePrice = 5099 , tax = 19, price = 10099

  6. ROW: productName = Product 2, purchasePrice = 5099 , tax = 19, price = 10099
  7. ROW: productName = Product 2, purchasePrice = 5099 , tax = 19, price = 10099

My Calculation for the Total Profit is this

SUM( price- ( price * tax/100.0  + purchasePrice)) as Profit

Result as Profit = 22780.210000000006

My Calculation for the Profit of every Product is this

SUM(price- (price*TAX/100.0 + purchasePrice)) as Profit GROUP BY productName

Result as Profit for Product 1 = 13536,6

Result as Profit for Product 2 = 9243,57

Total 22780,17

I have to round this Values and divide them by /100.0 because I've read that it is better to not store the values with floating points in Sqlite.

I do the rounding and /100.0 like this

Round for Total with the Result of = 227.8

ROUND((SUM( price- ( price * tax/100.0  + purchasePrice)))/100 ,2) as Profit

Round for every Product

ROUND((SUM( price- ( price * tax/100.0  + purchasePrice)))/100 ,2) as Profit

Product 1 result = 135,37

Product 2 result = 92,44

Total 227,81 but the Round for Total gives me the Result of = 227.8

Any ideas?

Moving C# SQLite Program to new Machine

I have a SQLite Database already filled with tables and data, my program reads and writes from this table already.

However I need to deploy this Program on other machines and when I do I get the error

"SQL Logic Error or missing database no such table: Customer"

The SQLite database is saved in the root of the C Drive, and it is there on the machines I have tested on.

This is my Connection String

 Data Source= "C:\EpasSqLite.db"; Version = 3;

How do I resolve this?

How to full text search in SQLite without tokenizing, but rather looking for substrings

I would like to utilize the full-text search features (FTS3 or FTS4 extensions) of SQLite to search through biological (DNA, protein) sequences. Unlike what seems to be the designer use-case for FTS, I'd like my search to match any substring of a specific column, with no regard to delimiters or tokens.

I saw I can limit the columns being indexed by using the notindexed= option, and that I can use prefix matching by using the prefix= option. Since my sequences don't include any delimiters (they only include latin alphabet characters), I can regard each of the sequences as a single token, and set up a prefix search. This has two problems, though. The first is that I'd like to search through substrings, not only prefixes. The second is that each sequence will be stored twice, if I'm not mistaken - once as the contents, and the second time as a token. I could create a contentless table to overcome the second caveat, but I don't know how to address the first.

To conclude, my question is: is there a way to full-text search (using an index) on substrings which aren't prefixes in SQLite?

Thanks!