samedi 30 janvier 2016

Fetch specific data from android database sqlite

I'm wondering if it is possible to fetch one specific type of data from an android database, based on sqlite.

Let's say I have a table with rows "Category" and "Title" and I want to get a String array containing the "Title" of those categories matching a given one.

For example:

Title    Category
A        spam
B        important
C        spam

And given "spam", I want to get a String array like

S = {A,C}

Is there a way to do this?

Please note that I'm very new to databases.

Thanks in advance.

EDIT:

I'm actually trying with a query

mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_TITLE,
            KEY_BODY, KEY_CATEGORY},  KEY_CATEGORY + "=" + category, null, null, null, KEY_CATEGORY);

But it returns a Cursor and I need a SimpleCursorAdapter like here for formatting

SimpleCursorAdapter notes =
            new SimpleCursorAdapter(this, R.layout.notes_row, notesCursor, from, to);
    mList.setAdapter(notes);

where from and to are:

String[] from = new String[] { NotesDbAdapter.KEY_TITLE };
int[] to = new int[] { R.id.text1 };

Linq query returns the same names even though they should be different

I am new to EF6 and I have set up the Chinook database and gotten it working with SqlLite .NET provider on .NET Framework 4.0.

When I execute the following query, it executes without problems but the track names are all the same. They should be different because they have different track IDs and I have looked up those track IDs and they have different names.

var result = context.Playlists.Include(p => p.Tracks)
                .Where(p => p.Name == "Brazilian Music")
                .SelectMany(p => p.Tracks);

foreach(var p in result)
{
  Console.WriteLine(p.Playlist.Name + ", " + p.TrackId + ", " + p.Track.Name);
}

Appreciate any help.

Here is the output of my result:

Console Output

about update data in Android Studio and SQlite

I have 2 questions want to ask about android studio and sqlite.

1) I am trying to run my project in emulator or phone. When I want to return to previous activity by pressing the return button(return function for phone) but it close all my project.But I saw my friend's can return to previous activity by pressing the return button.May I know how and why??

2) I had done update function for my project.The situation is when userA go to "view profile" activity and click edit info, another activity that call "updateinfo" will come out.Then after userA update his information by clicking update button.It's successful update and go back to "view profile" activity to see his updated profile.

But the problem I faced is it does not show out the updated information.It just show a blank "view profile" activity without any information that updated or haven updated.

What should I do?

here my database update function

     public boolean updateProfile(String username, String password, String email, String phone)
   {
       SQLiteDatabase db = this.getWritableDatabase();
       ContentValues values = new ContentValues();
       values.put (COL_2,username);
       values.put(COL_3,password);
       values.put(COL_4,email);
       values.put(COL_5,phone);

      db.update(Table_NAME,values,COL_2 + "=?",new String[]{username});
       db.close();
       return true;
   }

here is my updateinfo activity function

public class EditProfile extends AppCompatActivity {
EditText etEmail,etPhone,etPassword,etConPassword,etUsername;
String password,conpassword,Email,Phone;
Button bUpdate;
DatabaseOperations DB = new DatabaseOperations(this);

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_edit_profile);
    etEmail = (EditText) findViewById(R.id.etEmail);
    etPhone = (EditText) findViewById(R.id.etPhone);
    etPassword = (EditText) findViewById(R.id.etPassword);
    etConPassword = (EditText) findViewById(R.id.etConPassword);
    etUsername = (EditText) findViewById(R.id.etUsername);
    bUpdate = (Button) findViewById(R.id.bUpdate);

    Intent i = getIntent();
    String email = i.getStringExtra("email");
    etEmail.setText(email);
    String phone = i.getStringExtra("phone");
    etPhone.setText(phone);
    String username = i.getStringExtra("username");
    etUsername.setText(username);

    bUpdate.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            password = etPassword.getText().toString();
            conpassword = etConPassword.getText().toString();
            Email = etEmail.getText().toString();
            Phone = etPhone.getText().toString();

            if (!(password.equals(conpassword))) {
                Toast.makeText(getBaseContext(), "Passwords are not matching", Toast.LENGTH_LONG).show();
                etPassword.setText("");
                etConPassword.setText("");
                etEmail.setText("");
                etPhone.setText("");
            } else if (etPassword.length() == 0 || etConPassword.length() == 0 || etEmail.length() == 0 || etPhone.length() == 0) {
                etPassword.setError("Please complete all information");
                etConPassword.setError("Please complete all information");
                etEmail.setError("Please complete all information");
                etPhone.setError("Please complete all information");
            } else if (etPassword.length() < 6) {
                etPassword.requestFocus();
                etPassword.setError("Password at least 6 characters");
                etPassword.setText("");
                etConPassword.setText("");
                etEmail.setText("");
                etPhone.setText("");
            } else {
                boolean isUpdate = DB.updateProfile(etUsername.getText().toString(),etPassword.getText().toString(),etEmail.getText().toString(),etPhone.getText().toString());
                if(isUpdate == true) {
                    Toast.makeText(getBaseContext(), "Update Success", Toast.LENGTH_LONG).show();
                    Intent i = new Intent(EditProfile.this, MyProfile.class);
                    startActivity(i);
                    finish();
                }
                else
                {
                    Toast.makeText(getBaseContext(), "Data Not Updated", Toast.LENGTH_LONG).show();
                }
            }
        }
    });
}

and here is my viewprofile activity function

public class MyProfile extends AppCompatActivity {
EditText etName,etEmail,etPhone,etShow;
Button bEdit;
String fullname,email,phone;
DatabaseOperations db = new DatabaseOperations(this);
PersonalData profileInfo;

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



    etName = (EditText) findViewById(R.id.etName);
    etEmail = (EditText) findViewById(R.id.etEmail);
    etPhone = (EditText) findViewById(R.id.etPhone);
    bEdit = (Button) findViewById(R.id.bEdit);
    etShow = (EditText) findViewById(R.id.etShow);


    fullname = etName.getText().toString();
    email = etEmail.getText().toString();
    phone = etPhone.getText().toString();

    Intent i = getIntent();
    String username = i.getStringExtra("username");
    etShow.setText(username);
    profileInfo = db.getAllinfo(username);
    etName.setText(profileInfo.get_name());
    etEmail.setText(profileInfo.get_email());
    etPhone.setText(profileInfo.get_phone());


    bEdit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i = new Intent(MyProfile.this,EditProfile.class);
            i.putExtra("email", etEmail.getText().toString());;
            i.putExtra("phone", etPhone.getText().toString());;
            i.putExtra("username", etShow.getText().toString());
            startActivity(i);
            finish();

        }
    });
}

How to use Group in Sqlite database w.r.t. DateColoumn?

I have below coloumn in my SQLite table : DataType of ActivityDate is date provided by Sqlite.

ActivityDate
2016-01-28 07:38:41 +0000
2016-01-28 03:26:56 +0000
2016-01-29 02:22:40 +0000
2016-01-26 01:13:39 +0000

I wants to get uniqe date(Only w.r.t. Date), I do not wants to consider Time in this. So my desired result is :

ActivityDate
2016-01-28 07:38:41 +0000
2016-01-29 02:22:40 +0000
2016-01-26 01:13:39 +0000

So, Is there any way to acheive this using SQLite Query?

creating sqlite3 dump files with all table values

I can generate a sqlite3 dump file with

sqlite3 app.db .dump > app_dump.sql

however, if there is a row in that database which has no entry it is just left out in the dump file. This is a problem when using the dump file to read the data into another database. Is there a way to force the dump file to have all values defined in the table? So if there is no entry it just uses empty string '' or something like that? thanks carl

vendredi 29 janvier 2016

SQLite Update Statement error

for my update i want to search corrent pos using inspectionid, activityid, subactivityid but when calling update state ment im getting this error.can some one help.

public int updateSubActivityActivityComment(String comment, int rating, int subActivityId, int activityId, int inspectionId){
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();

    contentValues.put(KEY_RATING, rating);
    contentValues.put(KEY_COMMENT, comment);

    return db.updateWithOnConflict(TABLE_INSPECTION, contentValues,KEY_SUB_ACTIVITY_ID+ " = ? "+subActivityId+" AND "+KEY_INSPECTION_ID + " = ? "+inspectionId +" AND "+KEY_ACTIVITY_ID +" = ? "+activityId,new String[]{String.valueOf(subActivityId)} ,SQLiteDatabase.CONFLICT_IGNORE);
}

Log Cat-

java.lang.IllegalArgumentException: Too many bind arguments.  3 arguments were provided but the statement needs 2 arguments.
                                                     at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:68)
                                                     at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
                                                     at android.database.sqlite.SQLiteDatabase.updateWithOnConflict(SQLiteDatabase.java:1574)
                                                     at com.theavo.ck_app.DatabaseHelper.updateSubActivityActivityComment(DatabaseHelper.java:264)
                                                     at com.theavo.ck_app.FragmentSubInspectionComment.onClick(FragmentSubInspectionComment.java:470)
                                                     at android.view.View.performClick(View.java:4780)
                                                     at android.view.View$PerformClick.run(View.java:19866)
                                                     at android.os.Handler.handleCallback(Handler.java:739)
                                                     at android.os.Handler.dispatchMessage(Handler.java:95)
                                                     at android.os.Looper.loop(Looper.java:135)
                                                     at android.app.ActivityThread.main(ActivityThread.java:5254)
                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                     at java.lang.reflect.Method.invoke(Method.java:372)
                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

Flask SqlAlchemy : Records not displayed

Here is my code :

from flask import Flask
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from database_setup import Base, Restaurant, MenuItem

app = Flask(__name__)

engine = create_engine('sqlite:///restaurantmenu.db')
Base.metadata.bind = engine

DBSession = sessionmaker(bind=engine)
session = DBSession()


@app.route('/')
@app.route('/restaurants/<int:restaurant_id>/')
def restaurantMenu(restaurant_id):
    restaurant = session.query(Restaurant).filter_by(id=restaurant_id).one()
    items = session.query(MenuItem).filter_by(restaurant_id=restaurant.id)
    output = ''
    for i in items:
        output += i.name
        output += '</br>'
        output += i.price
        output += '</br>'
        output += i.description
        output += '</br>'
        output += '</br>'
    return output

if __name__ == '__main__':
    app.debug = True
    app.run(host='0.0.0.0', port=5000)

I run the file by entering the following URL :

localhost:5000/restaurants/2

And all I get is a blank page. I don't get any kind of error in my GitBash or browser or anywhere else.

I ran this simple code :

from flask import Flask
app = Flask(__name__)


@app.route('/')
@app.route('/hello')
def HelloWorld():
    return "Hello World"

if __name__ == '__main__':
    app.debug = True
    app.run(host='0.0.0.0', port=5000)

And this runs perfectly. What wrong am I doing ? TIA