jeudi 31 mars 2016

How can I create solution setup (.exe) with SQLite file

I try create setup from my test application with sqlite file. Code here:

 public void connection()
    {
        m_dbConnection = new SQLiteConnection(@"Data Source=C:\Program Files (x86)\mato\skuskaSetup\myDB.dat;Version=3;");
        m_dbConnection.Open();
    }

    public void select(string select)
    {
        string sql3 = select;
        SQLiteCommand command3 = new SQLiteCommand(sql3, m_dbConnection);
        command3.ExecuteNonQuery();
        SQLiteDataAdapter adapter = new SQLiteDataAdapter(command3);
        DataTable dt = new DataTable("table1");
        adapter.Fill(dt);
        dataGrid.ItemsSource = dt.DefaultView;
        adapter.Update(dt);
        m_dbConnection.Close();
    }

    private void button_Click(object sender, RoutedEventArgs e)
    {
        connection();
        select(selectFromTbl1);
    }
}

File myDB.dat is included in setup.

If I start app in VS all is OK, but after installation app can not find myDB.dat

I am trying to add single name in SQLite database of android , butt it adds multiple entries with same name

Hello everyone !

Dear all, I am trying to add one contact in database of android butt it add multiple entries with same name, kindly help me out as I am new in this filed. Thanks in advance for helping me out.

//Function to add single name/group name in database class
    public void createGroup(GroupsDetail gd){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        // put values in database
       values.put(group_NAME , gd.getName());
       db.insert(table_Group , null , values);
       // close database transaction
       db.close();
}

//Function to get all names/group names in database class
   public List<GroupsDetail> getallcontacts(){
       List<GroupsDetail> groupList = new ArrayList<GroupsDetail>();
       String query = "SELECT * From " + table_Group;
       //get referance of ContactAS database
       SQLiteDatabase db = this.getWritableDatabase();
       Cursor cursor = db.rawQuery(query, null);
       GroupsDetail group = null;
       if(cursor.moveToFirst()){
        do{
            group = new GroupsDetail();
            group.setId(Integer.parseInt(cursor.getString(0)));
            group.setName(cursor.getString(1));
            groupList.add(group);
          }while(cursor.moveToNext());  
    }

    return groupList;   
}

//Code of main class 
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.widget.ArrayAdapter; 
import android.widget.Button;
import android.widget.ListView;

 public class Groups extends Activity{
 Button Addgroup,Delgroup;
 ListView groupnames;
 GroupsDetail gd;
 ArrayList<String> listItems;
 List<GroupsDetail> gdlist;
 Groupsdb gdb;

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

    Addgroup = (Button)findViewById(R.id.addgroup);
    Delgroup = (Button)findViewById(R.id.deletegroup);
    groupnames = (ListView)findViewById(R.id.listofgroups);
    groupnames.setLongClickable(true);

    gdb = new Groupsdb(this);
    listItems = new ArrayList<String>();
    gdlist = new ArrayList<GroupsDetail>();

    gd = new GroupsDetail("Family");

    gdb.createGroup(gd);
    gdlist = gdb.getallcontacts();

    for(GroupsDetail cn : gdlist){
        listItems.add(cn.getName());
    }

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.text, listItems);
    groupnames.setAdapter(adapter);

     }

}

 //code of GroupDetails class

  public class GroupsDetail {

        private String Name;
        private int id;

public GroupsDetail(){}

public GroupsDetail(String name){
    super();
    this.Name = name;
}

public GroupsDetail(String name, int i){
    super();
    this.Name = name;
    this.id = i;    
}

public int getId(){
    return id;
}

public void setId(int i){
   this.id = i; 
}

public String getName(){
    return Name;
}

public void setName(String name){
    this.Name = name;
}

  public String toString(){
    return "Group [id = " + id + ", Name = "+ Name + "]";  
      }
}

Having trouble getting selected item _id

I am having trouble retriving the selected item's id from a listView. The logic of what i am doing is : i have a product displayed in a listView. When i click to edit this product it sends me to a details page of the product. Here the product name, price etc. are retrived ok execept for the ID. Can anyone tell me what i am doing wrong? Here is the code: Class DatabaseHandler

//addItemToDB
public void addItem(ItemModel item) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(Constants.PRODUCT_ID, item.getItemId());
    values.put(Constants.PRODUCT_NAME, item.getItemName());
    values.put(Constants.PRODUCT_PRICE, item.getItemPrice());
    db.insert(Constants.TABLE_NAME, null, values);
}

> //get all items
public ArrayList<ItemModel> getAllItems() {

    SQLiteDatabase db = getReadableDatabase();

    Cursor cursor = db.query(Constants.TABLE_NAME, new String[]{Constants.PRODUCT_ID, Constants.PRODUCT_NAME, Constants.PRODUCT_PRICE},
            null, null, null, null, Constants.PRODUCT_DATE + " DESC");

    if (cursor.moveToFirst()) {
        do {

            ItemModel model = new ItemModel();

            //format date
            java.text.DateFormat dateFormat = java.text.DateFormat.getDateInstance();
            String data = dateFormat.format(new Date(cursor.getLong(cursor.getColumnIndex(Constants.PRODUCT_DATE))));

            model.setItemId(cursor.getInt(cursor.getColumnIndex(Constants.PRODUCT_ID)));
            model.setItemName(cursor.getString(cursor.getColumnIndex(Constants.PRODUCT_NAME)));
            model.setItemPrice(cursor.getDouble(cursor.getColumnIndexOrThrow(Constants.PRODUCT_PRICE)));

            modelArrayList.add(model);

        } while (cursor.moveToNext());
    }
    return modelArrayList;

In the listViewAdapter i have the getView method:

 @Override
public View getView(final int position, View convertView, ViewGroup parent) {

    View row = convertView;
    final ViewHolder holder;

    if (row == null || (row.getTag()) == null){

        LayoutInflater inflater = LayoutInflater.from(activity);
        row = inflater.inflate(layoutResource,null);

        holder = new ViewHolder();

        holder.hItemName = (TextView) row.findViewById(R.id.custom_row_productName);
        holder.hItemPrice = (TextView) row.findViewById(R.id.custom_row_productPrice);

        holder.hItemEdit = (ImageView) row.findViewById(R.id.custom_row_edit);

        row.setTag(holder);
    } else {
        holder = (ViewHolder) row.getTag();
    }

    holder.hModel = getItem(position);

    holder.hItemName.setText(holder.hModel.getItemName());
    holder.hItemPrice.setText(String.valueOf(holder.hModel.getItemPrice()));

    holder.hItemEdit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int itemID = holder.hModel.getItemId();
            String itemName = holder.hModel.getItemName();
            String itemPrice = String.valueOf(holder.hModel.getItemPrice());

            Intent intent = new Intent(activity, ItemDetail.class);

            intent.putExtra("id", itemID);
            intent.putExtra("product", itemName);
            intent.putExtra("price", itemPrice);
            intent.putExtra("type", itemType);

            startActivity(activity, intent,null);
        }
    });

And in the details page of the product on the onCreate i have:

Bundle extras = getIntent().getExtras();
if (extras != null) {
            itemProductName.setText(extras.getString("product"));
            itemPrice.setText(extras.getString("price"));
            final int itemID = extras.getInt("id");

            saveButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                        dbHandler.updateItem(itemID);
                        Toast.makeText(ItemDetail.this, itemProductName.getText().toString() + " was modified", Toast.LENGTH_SHORT).show();

                        startActivity(new Intent(ItemDetail.this, MainActivity.class));
                    }
                }
            });
    }

SQLite database Insert query not working for ionic app

I am trying to add cordova SQLite database in my ionic project which is scanning qrcode & inserting details into local database.

My database initialization is this:

var db = null;
var app = angular.module('scanstarter', ['ionic', 'ionic-material', 'ngCordova']);

app.run(function ($ionicPlatform, $ionicLoading, $cordovaGeolocation, $cordovaSQLite) {
$ionicPlatform.ready(function () {

    document.addEventListener("deviceready", function () {
        // Sqlite database initialization
        db = $cordovaSQLite.openDB({name: 'scanstarter.db'});
        // create table for product scan
        $cordovaSQLite.execute(db, "CREATE TABLE IF NOT EXISTS productScan (id integer primary key, unique_id text, productName text, serialNo text, manufacturer text, department text, time text, latitude text, longitude text, actionRequired text, sync text)");
        // create table for comments
        $cordovaSQLite.execute(db, "CREATE TABLE IF NOT EXISTS comments (id integer primary key, unique_id text, comment text)");
    }, false);
});

})

My scan function flow is this:

    $scope.goToScan = function () {
    cordova.plugins.barcodeScanner.scan(
            function (result) {
                if (!result.cancelled)
                {
                    if (result.format == "QR_CODE")
                    {
                        var scannedData = result.text;

                        var posOptions = {enableHighAccuracy: true};
                        $cordovaGeolocation.getCurrentPosition(posOptions).then(function (position) {
                            //Get latitude and longitude
                            var latitude = position.coords.latitude;
                            var longitude = position.coords.longitude;
                            //Initial Split with #
                            var splitArray = scannedData.split("#");
                            var UniqueId = splitArray[0];
                            var ProductName = splitArray[1];
                            var SerialNo = splitArray[2];
                            var Manufacturer = splitArray[3];
                            var Department = splitArray[4];
                            //Individual Split with :
                            var UniqueIdArray = UniqueId.split(':');
                            var ProductNameArray = ProductName.split(':');
                            var SerialNoArray = SerialNo.split(':');
                            var ManufacturerArray = Manufacturer.split(':');
                            var DepartmentArray = Department.split(':');

                            if ((UniqueIdArray[0] == 'unique_id') && (ProductNameArray[0] == 'product_name') && (SerialNoArray[0] == 'serial_no') && (ManufacturerArray[0] == 'manufacturer') && (DepartmentArray[0] == 'department')) {
//Insert query part start
                                var query = "INSERT INTO productScan (unique_id, productName, serialNo, manufacturer, department, time, latitude, longitude, actionRequired, sync) VALUES (?,?,?,?,?,?,?,?,?,?)";
                                $cordovaSQLite.execute(db, query, [UniqueIdArray[1], ProductNameArray[1], SerialNoArray[1], ManufacturerArray[1], DepartmentArray[1], Math.floor(Date.now() / 1000), latitude, longitude, 'N', 'N']).then(function (res) {
                                    alert(JSON.stringify(res));

                                }, function (err) {
                                    alert(JSON.stringify(err));
                                });
//Insert query part end
                                $state.go('app.scan');

                            } else {
                                alert('Invalid QR-Code. This QR-Code is not part of Inventory!.');
                            }

                        }, function (err) {
                            $ionicLoading.show({template: 'Kindly check your mobile GPS. GPS must be on!.'});
                            $timeout(function () { // server replies when username or password is incorrect
                                $ionicLoading.hide();
                            }, 3000)
                        });

                    }
                }
            },
            function (error) {
                alert("Scanning failed: " + error);
            }
    );
}

what happens is when i comment the insert query part of cordovaSQLite and build the app and check it then it successfully scan and then navigates to next page. But when i uncomment it and build the apk and run it on my mobile it does not navigate me to next page. I saw the flow working by adding subsequent alerts after each modile of execution and then i found that i am getting stuck at the point where sqlite insert query code starts.

What is the error occuring here i am really not getting. Is there something i am missing?

Thanks in advance for quick response.

Sqlite error: illegal first argument to matchinfo

I've been struggling with this for quite some time and have to throw in the towel. Using SQLite with Tcl:

set _query [sq_handle eval {SELECT matchinfo(column7) FROM myftstable WHERE column7 MATCH 'raindrops keep falling in my hat';}]
puts $_query

I keep getting this: error: illegal first argument to matchinfo

I only have the problem with matchinfo, which I need. Ordinary SELECT queries work fine.

I googled, but couldn't find anything useful.

How to save selected items from a listview to SQlite then view them on another page with titles?

I am building an android application (new to this)

There are several topics such as Cars, Phones, and laptops each having sublistings such as Mercedes, Chevrolet; Iphone,Samsung; Dell ,Toshiba. They are set in Listviews.

Now when the user clicks on Mercedes let's say I want this input to be saved in another activity in a list called Cars.Then he would select a phone and it would be saved permenatly in the latter activity in a list called Phones etc.

I have researched alot about SQLite databases but i still didnt hit any wins Any quick help is appreciated.

how Create Database in SQLite Expert Professional 4 - 64bit?

I do not know how should I create SQL Lite database.

when chosen New database option و I do not know what to do. It Show Me This Window

please guide me .

My SQLite Version : SQLite Expert Professional 4 - 64bit