vendredi 1 janvier 2016

How to implement database in PhoneGap App?

I'm a newbie in phonegap and i'm trying to figure out how to connect and configure my database and i've came across multiple same questions and they have been answered on stackoverflow such as

How to implement SQlite database in PhoneGap App

How to implement an SQLite database in Phonegap?

and other such questions but the problem is that i'm trying to figure out a way to implement my database in a wide sense for which i can get resources. So if you have any good ways to implement your app but for a big project what would you suggest? and please suggest any good ways to handle complexity of database in PhoneGap. Thanks in advance.

Using file picker save image in Windows Phone 8.1

I am adding Students and save Profile details to the SQLite database. Added Student Profiles are Shown in a Listview as below.

enter image description here enter image description here

I want to add a picture of the student using a file picker and save it. How can I achieve that?. Any suggestion or similar example would be more helpful.

So far My codes

   private string mruToken = null;   
    private NavigationHelper navigationHelper;
    public AddConatct()
    {
        this.InitializeComponent();
        this.navigationHelper = new NavigationHelper(this);
        this.Loaded += LoadSchoolToCombo;
        this.navigationHelper.LoadState += navigationHelper_LoadState;
        this.navigationHelper.SaveState += navigationHelper_SaveState;

    }
    private async void navigationHelper_LoadState(object sender, LoadStateEventArgs e)
    {

        if (e.PageState != null && e.PageState.ContainsKey("mruToken"))
        {
            object value = null;
            if (e.PageState.TryGetValue("mruToken", out value))
            {
                if (value != null)
                {
                    mruToken = value.ToString();

                    // Open the file via the token that you stored when adding this file into the MRU list.
                    Windows.Storage.StorageFile file =
                        await Windows.Storage.AccessCache.StorageApplicationPermissions.MostRecentlyUsedList.GetFileAsync(mruToken);

                    if (file != null)
                    {
                        // Open a stream for the selected file.
                        Windows.Storage.Streams.IRandomAccessStream fileStream =
                            await file.OpenAsync(Windows.Storage.FileAccessMode.Read);

                        // Set the image source to a bitmap.
                        Windows.UI.Xaml.Media.Imaging.BitmapImage bitmapImage =
                            new Windows.UI.Xaml.Media.Imaging.BitmapImage();

                        bitmapImage.SetSource(fileStream);
                        img.Source = bitmapImage;

                        // Set the data context for the page.
                        this.DataContext = file;
                    }
                }
            }
        }
    }
    private void navigationHelper_SaveState(object sender, SaveStateEventArgs e)
    {
        if (!string.IsNullOrEmpty(mruToken))
        {
            e.PageState["mruToken"] = mruToken;
        }

    }


   private async void PickPhoto_Click(object sender, RoutedEventArgs e){
        Windows.Storage.Pickers.FileOpenPicker openPicker = new Windows.Storage.Pickers.FileOpenPicker();
        openPicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary;
        openPicker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail;

        // Filter to include a sample subset of file types.
        openPicker.FileTypeFilter.Clear();
        openPicker.FileTypeFilter.Add(".bmp");
        openPicker.FileTypeFilter.Add(".png");
        openPicker.FileTypeFilter.Add(".jpeg");
        openPicker.FileTypeFilter.Add(".jpg");

        // Open the file picker.
        Windows.Storage.StorageFile file = await openPicker.PickSingleFileAsync();

        // file is null if user cancels the file picker.
        if (file != null)
        {
            // Open a stream for the selected file.
            Windows.Storage.Streams.IRandomAccessStream fileStream =
                await file.OpenAsync(Windows.Storage.FileAccessMode.Read);

            // Set the image source to the selected bitmap.
            Windows.UI.Xaml.Media.Imaging.BitmapImage bitmapImage =
                new Windows.UI.Xaml.Media.Imaging.BitmapImage();

            bitmapImage.SetSource(fileStream);
            img.Source = bitmapImage;
            this.DataContext = file;

            // Add picked file to MostRecentlyUsedList.
            mruToken = Windows.Storage.AccessCache.StorageApplicationPermissions.MostRecentlyUsedList.Add(file);
        }
    }

    private async void AddContact_Click(object sender, RoutedEventArgs e)
    {
        DatabaseHelperClass Db_Helper = new DatabaseHelperClass();//Creating object for DatabaseHelperClass.cs from ViewModel/DatabaseHelperClass.cs 
        if (NametxtBx.Text != "" & AgetxtBx.Text != "" & AddresstxtBx.Text != "" & SchoolComboBx.SelectedValue.ToString() != "" & GardienttxtBx.Text != "" & PhonetxtBx.Text != "" & LattxtBx.Text != "" & LongtxtBx.Text != "")
        {
            Db_Helper.Insert(new Contacts(NametxtBx.Text, AgetxtBx.Text, AddresstxtBx.Text, SchoolComboBx.SelectedValue.ToString(), GardienttxtBx.Text, PhonetxtBx.Text, LattxtBx.Text, LongtxtBx.Text));
            Frame.Navigate(typeof(ReadContactList));//after add contact redirect to contact listbox page 
        }
        else
        {
            MessageDialog messageDialog = new MessageDialog("Please fill all fields");//Text should not be empty 
            await messageDialog.ShowAsync();
        }
    }

Contacts.cs

public class Contacts
{
    //The Id property is marked as the Primary Key
    [SQLite.PrimaryKey, SQLite.AutoIncrement]
    public int Id { get; set; }
    public string Name { get; set; }
    public string Age { get; set; }
    public string Address { get; set; }
    public string School { get; set; }
    public string Gardient { get; set; }
    public string PhoneNumber { get; set; }
    public string Latitude { get; set; }
    public string Longitude { get; set; }
    public string CreationDate { get; set; }
    public Contacts()
    {
        //empty constructor
    }
    public Contacts( string name, string age, string address, string school, string gardient, string phone_no, string latitude, string longitude)
    {

        Name = name;
        Age = age;
        Address = address;
        School = school;
        Gardient = gardient;
        PhoneNumber = phone_no;
        Latitude = latitude;
        Longitude = longitude;
        CreationDate = DateTime.Now.ToString();
    }
}

data input not under column headers, i am trying to display the data in straight line columns...but its not working

hello am new at android development. am creating an app that has four columns. Student, age, number and class...but the data displayed under the columns is disorganized, how can i organize the data displayed in proper columns?

here is my code. my database name = schooldatabase

    String[] columns = new String[] { KEY_ROWID, KEY_STUDENT, KEY_AGE, 
            KEY_ID_NUMBER, KEY_CLASS };
    Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null,
            null, null);


String result =  "";
ArrayList<String> mArrayList = new ArrayList<String>();                



            int IROW = c.getColumnIndex(KEY_ROWID);
        int ISTUDENT = c.getColumnIndex(KEY_STUDENT);
    int IAGE = c.getColumnIndex(KEY_AGE);
    int INUMBER = c.getColumnIndex(KEY_ID_NUMBER);
    int ICLASS = c.getColumnIndex(KEY_CLASS);
    // ////////////////////////////////////////////////////////
    for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {


        // ////////////////////////////////////////////////////
        result = result + c.getString(IROW) + " " + c.getString(ISTUDENT)
                + " " + " " + c.getString(IAGE) + " " + " "
                + c.getString(INUMBER) + " " + "  " + c.getString(ICLASS)
                + "\n";
    }

    return result;

"WHERE IN" statement using greendao Android ORM

I am using greendao to work with sqlite database in my app.
I need to have such feature as where in condition
I am looking for such method or any other possible ways ,but without using raw query.

I need to perform such queries SELECT * FROM news WHERE id_company IN (SELECT id FROM company WHERE state=1.

Please suggest what is the best way to perform such query using GreenDAO ORM.

How to database(s) to choose, if you want to gather data from users of android application together for further analisys?

Hello everyone(and Happy new year),

I wanted to ask what is the best way do the thing I am planing. I was going to develop the application for android that has some user information stored on SQLite database, as it is the easiest and straight forward way to store data localy on the device. However recently another requirement poped up. My superviser asked to find a way to collect some of the data from the user's applications together and store it for further analisys.

I had several ideas:

1.Put SQLite on the server - however not sure its a good idea.

2.Run some SQL database(mysql maybe) on the server, and make the applications send the data from local SQLite db to external SQL db once there is internet connection.

What do you think is the best solution for this problem from your experience? Maybe you can suggest some tutorials or articles. I will be happy with any advice that you han give me on this (:

Thank you in advance.

How can I make Bussines Object Layer Automatically in Eclipse using database Tables like in Visual Studio

I am developing an android app in which local Db is used. I want to create some model classes for objects that will be used in whole program. I had already used Visual Studio 2013 and there was a support for such thing in it. I want to know that which will be the fastest way to create BOL(Bussines Object Layer) in eclipse.

Load data from sqlite to custom Listview but app stops

I have created an application to load name,phone from database auto and display as two textboxes in a listview. But nullpointer exception error occurs and app exits. My Logcat shows this.

01-01 03:52:04.267: W/dalvikvm(803): threadid=1: thread exiting with uncaught exception (group=0xb3a67ba8)
01-01 03:52:04.287: E/AndroidRuntime(803): FATAL EXCEPTION: main

01-01 03:52:04.287: E/AndroidRuntime(803): java.lang.RuntimeException: Unable to start activity ComponentInfo{}: java.lang.NullPointerException
01-01 03:52:04.287: E/AndroidRuntime(803):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2184)
01-01 03:52:04.287: E/AndroidRuntime(803):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
01-01 03:52:04.287: E/AndroidRuntime(803):  at android.app.ActivityThread.access$800(ActivityThread.java:135)
01-01 03:52:04.287: E/AndroidRuntime(803):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
01-01 03:52:04.287: E/AndroidRuntime(803):  at android.os.Handler.dispatchMessage(Handler.java:102)
01-01 03:52:04.287: E/AndroidRuntime(803):  at android.os.Looper.loop(Looper.java:136)
01-01 03:52:04.287: E/AndroidRuntime(803):  at android.app.ActivityThread.main(ActivityThread.java:5001)
01-01 03:52:04.287: E/AndroidRuntime(803):  at java.lang.reflect.Method.invokeNative(Native Method)
01-01 03:52:04.287: E/AndroidRuntime(803):  at java.lang.reflect.Method.invoke(Method.java:515)
01-01 03:52:04.287: E/AndroidRuntime(803):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
01-01 03:52:04.287: E/AndroidRuntime(803):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
01-01 03:52:04.287: E/AndroidRuntime(803):  at dalvik.system.NativeStart.main(Native Method)
01-01 03:52:04.287: E/AndroidRuntime(803): Caused by: java.lang.NullPointerException
01-01 03:52:04.287: E/AndroidRuntime(803):  at com.onemedia.koottam.SqlHandler.copyDataBase(SqlHandler.java:75)
01-01 03:52:04.287: E/AndroidRuntime(803):  at com.onemedia.koottam.SqlHandler.<init>(SqlHandler.java:30)
01-01 03:52:04.287: E/AndroidRuntime(803):  at com.onemedia.koottam.Auto.onCreate(Auto.java:37)
01-01 03:52:04.287: E/AndroidRuntime(803):  at android.app.Activity.performCreate(Activity.java:5231)
01-01 03:52:04.287: E/AndroidRuntime(803):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
01-01 03:52:04.287: E/AndroidRuntime(803):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148)

My SQLHandler.java

public class SqlHandler {

public static final String DATABASE_NAME = "koottam.sqlite3";
public static final int DATABASE_VERSION = 1;
public static String DB_PATH;

Context context;
SQLiteDatabase sqlDatabase;
SqlDbHelper dbHelper;

public SqlHandler(Context context) {

    dbHelper = new SqlDbHelper(context, DATABASE_NAME, null,
            DATABASE_VERSION);
    String packageName = context.getPackageName();
    DB_PATH = String.format("//data//data//%s//databases//", packageName);
    sqlDatabase = dbHelper.getWritableDatabase();
    try {
        copyDataBase();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

public void executeQuery(String query) {
    try {

        if (sqlDatabase.isOpen()) {
            sqlDatabase.close();
        }

        sqlDatabase = dbHelper.getWritableDatabase();
        sqlDatabase.execSQL(query);

    } catch (Exception e) {

        System.out.println("DATABASE ERROR " + e);
    }

}

public Cursor selectQuery(String query) {
    Cursor c1 = null;
    try {

        if (sqlDatabase.isOpen()) {
            sqlDatabase.close();

        }
        sqlDatabase = dbHelper.getWritableDatabase();
        c1 = sqlDatabase.rawQuery(query, null);

    } catch (Exception e) {

        System.out.println("DATABASE ERROR " + e);

    }
    return c1;

}

private void copyDataBase() throws IOException {
    InputStream externalDbStream = context.getAssets().open(DATABASE_NAME);

    String outFileName = DB_PATH + DATABASE_NAME;

    OutputStream localDbStream = new FileOutputStream(outFileName);
    byte[] buffer = new byte[1024];
    int bytesRead;
    while ((bytesRead = externalDbStream.read(buffer)) > 0) {
        localDbStream.write(buffer, 0, bytesRead);
    }
    localDbStream.close();
    externalDbStream.close();

}

}

SQLDBHelper.java

public class SqlDbHelper extends SQLiteOpenHelper {
public static String DB_PATH;
public static String DB_NAME="koottam.sqlite3";
public SQLiteDatabase database;

public final Context context;


public static final String DATABASE_TABLE = "auto";

public static final String COLUMN1 = "SNo";
public static final String COLUMN2 = "Name";
public static final String COLUMN3 = "Number";

public SqlDbHelper(Context context, String name, CursorFactory factory,
        int version) {
    super(context, name, factory, version);

    // TODO Auto-generated constructor stub
    this.context = context;
    String packageName = context.getPackageName();
DB_PATH = String.format("//data//data//%s//databases//", packageName);
//DB_NAME = databaseName;

}

@Override
public void onCreate(SQLiteDatabase db) {
    // TODO Auto-generated method stub
    //db.execSQL(SCRIPT_CREATE_DATABASE);
    try {
        copyDataBase();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // TODO Auto-generated method stub
    db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
    onCreate(db);
}
public void createDataBase() {
    boolean dbExist = checkDataBase();
    if (!dbExist) {
        this.getReadableDatabase();
        try {
            copyDataBase();
        } catch (IOException e) {
            Log.e(this.getClass().toString(), "Copying error");
            throw new Error("Error copying database!");
        }
    } else {
        Log.i(this.getClass().toString(), "Database already exists");
    }
}

private boolean checkDataBase() {
    SQLiteDatabase checkDb = null;
    try {
        String path = DB_PATH + DB_NAME;
        checkDb = SQLiteDatabase.openDatabase(path, null,
                SQLiteDatabase.OPEN_READONLY);
    } catch (SQLException e) {
        Log.e(this.getClass().toString(), "Error while checking db");
    }

    if (checkDb != null) {
        checkDb.close();
    }
    return checkDb != null;
}

private void copyDataBase() throws IOException {
    InputStream externalDbStream = context.getAssets().open(DB_NAME);

    String outFileName = DB_PATH + DB_NAME;

    OutputStream localDbStream = new FileOutputStream(outFileName);
    byte[] buffer = new byte[1024];
    int bytesRead;
    while ((bytesRead = externalDbStream.read(buffer)) > 0) {
        localDbStream.write(buffer, 0, bytesRead);
    }
    localDbStream.close();
    externalDbStream.close();

}

public SQLiteDatabase openDataBase() throws SQLException {
    String path = DB_PATH + DB_NAME;
    if (database == null) {
        createDataBase();
        database = SQLiteDatabase.openDatabase(path, null,
            SQLiteDatabase.OPEN_READWRITE);
    }
    return database;
}
@Override
public synchronized void close() {
    if (database != null) {
        database.close();
    }
    super.close();
}

}

Auto.java

public class Auto extends ListActivity {

SqlHandler sqlHandler;

private ListView listView;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_auto);
    // get action bar   
    ActionBar actionBar = getActionBar();

    // Enabling Up / Back navigation
    actionBar.setDisplayHomeAsUpEnabled(true);
      sqlHandler = new SqlHandler(this);
    showlist();

}


private void showlist() {

    ArrayList<listRowAuto> contactList = new ArrayList<listRowAuto>();
    contactList.clear();
    String query = "SELECT Name,Number FROM auto ";
    Cursor c1 = sqlHandler.selectQuery(query);
    if (c1 != null && c1.getCount() != 0) {
        if (c1.moveToFirst()) {
            do {
                listRowAuto contactListItems = new listRowAuto();

                contactListItems.setName(c1.getString(c1
                        .getColumnIndex("name")));
                contactListItems.setPhone(c1.getString(c1
                        .getColumnIndex("phone")));
                contactList.add(contactListItems);

            } while (c1.moveToNext());
        }
    }
    c1.close();

    listAdapterAuto contactListAdapter = new listAdapterAuto(
            Auto.this, contactList);
    listView.setAdapter(contactListAdapter);

}

}

I want to complete this application. I am new to the database and cursor adapters. Anyone help?