lundi 9 mai 2016

Adding button which can create data

i just join my job and the ask me to create an POS app. i did about most of thing but i am stuck in database. and also how to create same pattern they want. and a also a button which can create another button which had multi field.

Application is slow after install on another pc

I have build a WPF application with SQLite. After create setup project in visual studio and install it on my developer machine, app works perfect. But when my client install it on another computer it's works very slow. I added project output and SQLite.Interop.dll for database to setup project. Also one of my .dll is COM dll.

This application communicate only with SQLite database.

I have noticed that application works fine but with admin rights on client computer.

What can be the reason of this?

Would this RESTful iOS login system be secure?

So I have been thinking about a way to make a secure restful API for ios logins.

This is what my teacher and I have come up with:

  1. The Client (swift program) initializes the connection with the server.
  2. The Server returns a "shared secret" (ex. +40) and a hash of a random string of letters and numbers.
  3. The Client then hashes the Username and Password (separate) and sends it back with the hash of: hash + "the shared secret".
  4. After the Server sends data (step 2) the server hashes [hash + "shared secret"] and then updates it in the db
  5. The Server then receives the hashed value from the Client and checks the db to see if it matches
  6. The db will also have a timestamp that if not updated frequently enough there will be a function that runs through the db and drops the items that are no longer used.
  7. For every request after the login the bearer token is sent.

The bearer token will follow this formula: Request verification token = hash [ (original hash) + (shared secret) * (# of requests) ]

Only fetch date from datetime value of db sqlite android? Compare with current date and the then display time of the saved value?

I am trying to fetch date from my db, where its stored with time. I want to compare the date with in my adapter, if the date is equal to the current date then adapter fetch time only of the corresponding date, and if date is not equal to the current date then adapter display the date of the corresponding value,

This is how I am inserting date+time in DB:

long date = System.currentTimeMillis();
SimpleDateFormat sdf = new SimpleDateFormat("MMM-dd-yyyy h:mm:a");
String dateString = sdf.format(date);
s.setTime(dateString);
Log.i("result", s.getTime());
DatabaseHandler db = new DatabaseHandler(this);
db.creatScan(new Scan(s.getMsg().toString(), s.getTime().toString()));
db.close();

In my Adapter:

 TextView details = (TextView)convertView.findViewById(R.id.scandetails);

        TextView times = (TextView)convertView.findViewById(R.id.scanTime);

        times.setText(scan.getTime());

This is the Result:

enter image description here

What I want is: It should only display the time, if the date is equal to the current date, else it should only display the date.

I am trying this if/else statement but its not working, Your help would be very appreciated, thanks in advance

long date = System.currentTimeMillis();

SimpleDateFormat sdfDate = new SimpleDateFormat("MMM-dd-yyyy");

String dateString = sdfDate.format(date);

Log.i("date", dateString);

SimpleDateFormat sdfTime = new SimpleDateFormat("h:mm:a");

String timeString = sdfTime.format(date);

Log.i("date", timeString);

if(scan.getTime().equals(dateString)){

            times.setText(dateString);
    Log.i("data", timeString);
}else {
    String time =  scan.getTime().toString();
    Log.i("date", time);
    times.setText(scan.getTime());
}

Removing and creating PersistentStore and sqlite database

I'm working on an app that exchanges data with a server, and the mobile device has an option to wipe the database clean. I've looked around here and I found out I'm using the same code that's been suggested.

BOOL removedPS = [self.persistentStoreCoordinator removePersistentStore:store error:&error];
BOOL removedSqlite = [[NSFileManager defaultManager] removeItemAtURL:storeURL error:&error];

I use the two BOOLs to check if the operations have been made correctly and everything seems to be working smooth. Even the double check

[[NSFileManager defaultManager] fileExistsAtPath:[storeURL path]]

says the file has been deleted. After that, I want to re-create Persistent Store and sqlite:

NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
                                 [NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
                                 [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error])
{
   //ouch :/
}

but the addPersistentStoreWithType keeps on returning a "false" flag. Same goes with the sqlite: I try to copy a fresh .sqlite database, but I keep getting a "nil" for the NSString *param variable, and I can't understand why.

NSError* err = nil;
                NSBundle *bundle = [NSBundle mainBundle];
                NSString *path = @"BaseScope";
                NSString *type = @"sqlite";
                NSString *param = [bundle pathForResource:path ofType:type];

                //NSURL *preloadURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"BaseScope" ofType:@"sqlite"]];
                //NSURL *preloadURL = [NSURL fileURLWithPath:[bundle pathForResource:path ofType:type]];
                if (param != nil)
                {
                    NSURL *preloadURL = [NSURL fileURLWithPath:param isDirectory:false];

                    if (![[NSFileManager defaultManager] copyItemAtURL:preloadURL toURL:storeURL error:&err])
                    {

                    }
                }

I always worked in the .NET environment and this is really puzzling me, but knocking the head against the monitor won't work. Any help appreciated. Thanks in advance.

Using multiple cursor OR using same cursor for multiple queries

I want to fetch data from multiple table in my activity having 2 Listviews and some EditTexts.

I want to fetch data in EditText from Table 1 And fetch data in ListView1 from Table 2 and data from Table 3 into ListView2.

Problem is : i can fetch data through cursor from table 1. But I can't fetch data from table2 using same cursor OR new Cursor.

Table have data but Cursor.MoveToFirst returns false.

public class Details extends AppCompatActivity {

TextView name,num,cty,det;
Button btn_debit,btn_credit;
SQLiteDatabase db;
Cursor c;
int id;
ListView dbList,crList;
private ArrayList<HashMap<String,String>> arrayList;

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

    id = Integer.parseInt(getIntent().getExtras().getString("name"));

    name = (TextView)findViewById(R.id.textView6);
    num = (TextView)findViewById(R.id.textView7);
    cty = (TextView)findViewById(R.id.textView8);
    det = (TextView)findViewById(R.id.textView9);

    btn_debit = (Button)findViewById(R.id.jama);
    btn_credit = (Button)findViewById(R.id.udhar);

    dbList = (ListView)findViewById(R.id.ListDebit);
    crList = (ListView)findViewById(R.id.ListCredit);

    arrayList = new ArrayList<HashMap<String, String>>();

    // tv = (TextView)findViewById(R.id.textView6);
    //tv.setText(getIntent().getExtras().getString("name"));
    db = openOrCreateDatabase("AccountsDB", Context.MODE_PRIVATE,null);

    c=db.rawQuery("SELECT c_name , c_mno , c_detail , c_city FROM customers where c_id="+id,null);
    try {
        if (c!=null){
            if (c.moveToFirst()){
                name.setText(c.getString(0));
                num.setText(c.getString(1));
                cty.setText(c.getString(3));
                det.setText(c.getString(2));
            }
        }
    }catch (Exception e){

    }finally {
        c.close();
    }

    Cursor cursor = db.rawQuery("SELECT * FROM debit_master",null);
    try{
        if (cursor!=null){
            if (cursor.moveToFirst()){
                Map<String,String> tem  = new HashMap<String ,String>();
                tem.clear();
                arrayList.clear();
                dbList.setAdapter(null);
                int cnt = cursor.getCount();
                Toast.makeText(getApplicationContext(),""+cnt,Toast.LENGTH_SHORT).show();
                do {

                    tem = new HashMap<String,String>();
                    tem.clear();

                    tem.put(FIRST_COLUMN, cursor.getString(0));
                    tem.put(SECOND_COLUMN,cursor.getString(1));
                    tem.put(THIRD_COLUMN,cursor.getString(2));
                    arrayList.add((HashMap<String, String>) tem);
                }while (cursor.moveToNext());
            }
        }

    }catch (Exception ex){
        Toast.makeText(getApplicationContext(),""+ex,Toast.LENGTH_LONG).show();
    }


    ListViewAdapter adapter = new ListViewAdapter(this,arrayList);
    dbList.setAdapter(adapter);


    btn_debit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(Details.this,Debit.class);
            intent.putExtra("cid",id);
            Details.this.startActivity(intent);
        }
    });

}

}

What's meaning of this my code?

I hope your help the coding. Now i connect the android studio in database. But start a coding don't know error in my program. So I check a php file and check the programming coding isn't not error and Execute a program. enter image description here

Show the picture, Can you see the blue text code? Execute a program and writing a code in select part. But, alert a this word in my program

"05-09 13:32:44.533 325-333/? W/genymotion_audio: out_write() limiting sleep time 46802 to 39909".

What's meannig this code???

IN clause in objective c

Hi i am using "IN" clause in objective c but this is not able to get data.

SELECT * FROM database WHERE colum1!=0 AND colum2!=0 AND colum3 IN ('Allah','is');

for this query code is i am using

NSArray* serch = [NSArray arrayWithObjects:@"Allah",@"is",nil];
    str1=[NSString stringWithFormat:@"SELECT * FROM database WHERE colum1!=0 AND colum2!=0 AND colum3 IN ('%@')",[serch componentsJoinedByString:@"','"]]

FMResultSet return nil;

Update sqlite not working on android

I have a login and reset password activity. When I enter the new updated password and try to login again, I cannot do so with the new password. Logging in with the old password works fine. Basically, the password field is not getting updated/overwritten.

There is no error in the logcat. Just that the password is not updated.

Please help as I am new to android development.

Code for update( DataRegister is the class with GET AND SET functions):

public int updatePassword(DataRegister dataregister) {

db = dbHelper.getWritableDatabase();
ContentValues updated = new ContentValues();
updated.put("PASSWORD", dataregister.getPASSWORD());

return db.update(DataRegister.TABLE, updated, "EMAIL=?" , new String[]   {dataregister.getEMAIL()});

}

Code for retrieval:

public String getPass(DataRegister dataRegister) {

db = dbHelper.getWritableDatabase();

Cursor cursor = db.query(DataRegister.TABLE, null, "EMAIL=?",
        new String[]{dataRegister.getEMAIL()}, null, null, null, null);
if (cursor != null && cursor.moveToFirst())

{
    pass = cursor.getString(cursor.getColumnIndex("PASSWORD"));
    cursor.close();
}
return pass;


// return contact


}

Code for Login:

  String email = editTextUserName.getText().toString();
        dataRegister.setEMAIL(email);

        String password = editTextPassword.getText().toString();
        dataRegister.setPASSWORD(password);

        String storedPassword = loginDataBaseAdapter.getSinlgeEntry(dataRegister);

        Toast.makeText(Login.this, storedPassword,Toast.LENGTH_LONG).show();
        Boolean a=loginDataBaseAdapter.isExist(dataRegister.getEMAIL());
       validation = getSharedPreferences("myShaPreferences", Context.MODE_PRIVATE);

        if (password.equals(storedPassword)) {

            Toast.makeText(Login.this,
                    "Congrats: Login Successful", Toast.LENGTH_LONG)
                    .show();
        }

        else {

                Toast.makeText(Login.this,
                        "User Name or Password does not match",
                        Toast.LENGTH_LONG).show();


            }



    }
});

Code for reset password:

public class ResetPassword extends AppCompatActivity {


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

 email = (EditText) findViewById(R.id.em2);
 dataRegister=new DataRegister();

loginDataBaseAdapter = new DatabaseAdapter(this);
loginDataBaseAdapter = loginDataBaseAdapter.open();



pass = (EditText) findViewById(R.id.text12);
conpass = (EditText) findViewById(R.id.text13);

email1 = email.getText().toString();
dataRegister.setEMAIL(email1);
pass1 = pass.getText().toString();

conpass1 = conpass.getText().toString();
dataRegister.setPASSWORD(conpass1);

Button btnReset = (Button) findViewById(R.id.btnReset);
btnReset.setOnClickListener(new View.OnClickListener() {
    public void onClick(View view) {


        if (pass1.equals(conpass1)) {

         loginDataBaseAdapter.updatePassword(email1,pass1);
            String newpass =loginDataBaseAdapter.getPass(dataRegister);

Table with many columns or many small tables?

I created a table where it has 30 columns.

CREATE TABLE "SETTINGS" (
  "column1" INTEGER PRIMARY KEY,
  ...
  ...
  "column30"
)

However, I can group them and create different table where they can have foreign keys to the primary table. Which is the best way to follow? Or the number of the columns is small so it's the same which way I will follow?

android sqlight how to search string in like if string contains ' symbol

following is my query that I am trying to search name contain special character e.g. ' symbol

 SELECT * from  distributor where name like'%jeni's%'

when I tried to add backslash if work in MySQL but wont work in sq light database I also tried following query

SELECT * from distributor where name like'%jeni\'s%' can someone help me to how can i search if string contains ' symbol

what is the use of onUpgrade() in sqlite?

Anybody please help me regarding the correct use of onUpgrade() in sqliteopenhelper class.Thanks in advance.

How to copy displyed text of recent page and share in android?

I created database which is displayed on sliding page one by one like e1 slide e2. Now i want to copy e1 and share it with friends.How to perform this task in android?

green dao update column on play store update has taken place

this is my Generator class

public class Generator {
    public static void main(String[] args) throws Exception {
        Schema schema = new Schema(1, "app.abc.db.dao");
        createAbcDB(schema);

    }
    private static void createAbcDB(Schema schema) throws IOException, Exception {
        Entity abc = schema.addEntity("Abc");
        abc.addIdProperty();
        abc.addShortProperty("name");
    }
}

This is the code where i get abc dao from dao session. This works fine.

DaoMaster.DevOpenHelper devOpenHelper = new DaoMaster.DevOpenHelper(SurveyActivity.this, "abc.db", null);
        SQLiteDatabase db = devOpenHelper.getWritableDatabase();
        DaoMaster daoMaster = new DaoMaster(db);
        DaoSession daoSession = daoMaster.newSession(IdentityScopeType.None);
        abcDao = daoSession.getAbcDao();

I added one more column

abc.addShortProperty("email");

to createAbcDB in generator to new version of app. Once users get updated they are getting sql exception saying no column found. Because i am calling on new login

dropAllTables(db, true);
onCreate(db); 

But problem is i have given one time login that user will always come to landing screen on upgrade from play store. So i don't know whether the user is upgraded app or not in order to drop and create all tables.

So my question is how to know my table has altered?

Table has no column named xyz while inserting data into SQLite database

It says that the column name bmi does not exist. The resulting Error message is that the system cannot find a column called bmi. I checked it already a couple of times and I couldn't find a mistake in the code. Maybe you guys see one... The full Stack Dump is attached after the code.

public class MyDBHandler extends SQLiteOpenHelper{

private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "bmiwerte.db";

public static final String TABLE_BMIS = "bmis";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_NAME = "name";
public static final String COLUMN_BMI = "bmi";


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

private static final String CREATE_TABLE_BMIS = "CREATE TABLE "
        +TABLE_BMIS
        +" ("
        +COLUMN_ID
        +" INTEGER AUTOINCREMENT, "
        +COLUMN_NAME
        +" TEXT PRIMARY KEY"
        +COLUMN_BMI
        +" TEXT"
        +");";

@Override
public void onCreate(SQLiteDatabase db) {

    //Lässt Query in SQL laufen
    Log.i("exxxx", "Creating Check");
    db.execSQL(CREATE_TABLE_BMIS);
}

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

public void addValues(BMI_Werte wert){
    ContentValues values = new ContentValues();

    values.put(COLUMN_NAME, wert.get_name());
    values.put(COLUMN_BMI, wert.get_bmiWert().toString());
    Log.i("exxx", wert.get_name());
    Log.i("exxxx", wert.get_bmiWert().toString());

    SQLiteDatabase db = getWritableDatabase();
    db.insert(TABLE_BMIS, null, values);
    db.close();
}

public void deleteValues(String name){
    Log.i("exxxx", "deleteValuse");
    SQLiteDatabase db = getWritableDatabase();
    db.execSQL("DELETE FROM " + TABLE_BMIS + " WHERE " +
            COLUMN_NAME + "=\"" + name + "\";");
}

public String databaseToString(){
    String dbString = "";
    SQLiteDatabase db = this.getWritableDatabase();

    String query = "SELECT * FROM " + TABLE_BMIS;
    String test = "DESCRIBE " + TABLE_BMIS;

    Cursor c = db.rawQuery(query, null);

    c.moveToFirst();

    while(!c.isAfterLast()){
        if(c.getString(c.getColumnIndex("name")) != null){
            dbString += c.getString(c.getColumnIndex("name"));
            dbString += "\n";
        }
        c.moveToNext();
    }

    db.close();
    return dbString;
}

}

Error and Stack Dump:


Error

Android SQLite sending query as an email

I was wondering if it was possible to send a query via email that is created through my app as a text file, or similar format that can be viewed on a pc. The query i want to send is

public Cursor getExpiryData (){
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor expiry = db.rawQuery("select * from " + TABLE_NAME + " WHERE " + COL_4 + " BETWEEN datetime('now', 'localtime') AND datetime('now', '+30 days')", null );
    return expiry;
}

Unable to set data into database

In this below code im trying get and set data from the data base but during execution im unable set data in the data base ...

SettingUp

mWirelessRouters = WalletWirelessRouter.get(getActivity()).getWirelessRouter(uuid);

onTextChanged Listner

 mBaseStationName = (EditText) v.findViewById(R.id.base_station_name);
    mBaseStationName.setText(mWirelessRouters.getBaseStationName());
    mBaseStationName.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged
                (CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged
                (CharSequence s, int start, int before, int count) {
           mWirelessRouters.setBaseStationName(s.toString());
        }

        @Override
        public void afterTextChanged
                (Editable s) {

        }
    });

Note:- In the above code im trying take the base station name from the user and update it in database..There is no issue related view

getWirelessRouter(UUID uuid)

 public WirelessRouter getWirelessRouter(UUID id)
{
    WalletCursorWrapper cursor = queryWireless(
            WalletDbSchema.WirelessRouter.Cols.UUID + " =? "
            , new String[]
                    {
                            id.toString()
                    }
    );

    try {
        if (cursor.getCount() == 0) {
            return null;
        }

        cursor.moveToFirst();
        return cursor.getWirelessRouter();
    } finally {
        cursor.close();
    }
}

queryWireless

 private WalletCursorWrapper queryWireless (String whereClause, String[] whereArgs)
{
    Cursor cursor = mDatabase.query(
            WalletDbSchema.WirelessRouter.NAME,
            null, // Colums - null select all colums
            whereClause,
            whereArgs,
            null, //groupBy
            null, //having
            null // order

    );

    return new WalletCursorWrapper(cursor);
}

If you need any more data please let me know

Assign ID numbers according to groups

Button blue can add blue item, red button adding red button, etc. one button can be clicked more than once, hence there can be more than one blue or red item.

the table is as below

item     id      details    size
blue             cheap      small
blue             expensive  big
blue             cheap      small
red              cheap      small
red              ok         average

how can i assign the id for each of them so that the table is as below

item     id      details    size
blue      1      cheap      small
blue      2      expensive  big
blue      3      cheap      small
red       1      cheap      small
red       2      ok         average

Android sync text and audio notes

In one activity the user will get quotes from him daily in text format. I am thinking the older quotes should be stored in his mobile whereas the user should be able to download new quotes as an when available. The same requirement with audio quotes in the second activity.

I want someone to point me the right direction. Currently, my confusion are:

  1. As in website do I need to make a purchase for the database space online. If yes provider recommendations please.
  2. How should I store the quote in text and audio format in the user mobile.
  3. How will I do the syncing with my online database and user database.
  4. What are the options which I can give my friend to upload new text and audio files.

SQLITE strftime() function issue

SELECT strftime('%W', 'Week'), sum(income) FROM tableOne GROUP BY Week;

Format for date is a simple date: YYYY-MM-DD

PROBLEM: When run no value for the Week column is provided. Any suggestions?

There is data in the table and when the query is run the income is summarized by the date in the week column. Thing is, this column contains a date that may be any day of the week and often multiple different days of the same week. I need to summarize the income by week.