jeudi 1 octobre 2015

android listview doesn't update

I am having a problem with using date range with a listView populated from a sqlite database, The code works perfectly however the issue i'm having is that the listView doesn't be updated (refreshed) when i choose another date range (when i touch the 'search' button again) , although the data adapter indeed gets the data from the database (made sure of that by using logcat)but doesn't print it in the listView. I can't use function notifyDataSetChanged(), it is not working, and whenever i use it after add() the app crashes.

Here is the code :-

public class ProductionCommentsActivity extends Activity implements View.OnClickListener {
private DBHandler dbHandler;
private ListView listView;
private Context context;
private ArrayList<String> results = new ArrayList<String>();
private ArrayAdapter adapter;
private static String newline = System.getProperty("line.separator");//a variable for line break
private EditText editTextFrom, editTextTo;
private DatePickerDialog datePickerDialogFrom, datePickerDialogTo;
private SimpleDateFormat simpleDateFormat;
private String fromDate,toDate ; // variables to store the chosen dates

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

    dbHandler = new DBHandler(this, dbHandler.DATABASE_NAME_PRODUCTION, null, 1);
    try {
        dbHandler.copyDataBase();
        Log.d("copydb", dbHandler.getDatabaseName());
    } catch (IOException e) {
        e.printStackTrace();
        Log.d("copydb",e.getMessage());
    }

    //defining list view
    listView = (ListView) findViewById(R.id.listView);

    //defining edit texts properties
    editTextFrom = (EditText) findViewById(R.id.editTextFrom);
    editTextFrom.setInputType(InputType.TYPE_NULL);
    editTextFrom.requestFocus();

    editTextTo = (EditText) findViewById(R.id.editTextTo);
    editTextTo.setInputType(InputType.TYPE_NULL);

    //setting up the date format
    simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
    setDateTimeField();
    context = this;
}

//method to handle the date pickers properties
private void setDateTimeField() {
    editTextFrom.setOnClickListener((View.OnClickListener) ProductionCommentsActivity.this);
    editTextTo.setOnClickListener((View.OnClickListener) ProductionCommentsActivity.this);

    //creating a new instance of the calendar
    Calendar newCalendar = Calendar.getInstance();

    //creating a pop up date picker
    datePickerDialogFrom = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {

        //getting the chosen date and setting its format
        //and writing the chosen date in the edit text
        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
            Calendar newDate = Calendar.getInstance();
            newDate.set(year, monthOfYear, dayOfMonth);
            editTextFrom.setText(simpleDateFormat.format(newDate.getTime()));
            fromDate = editTextFrom.getText().toString();
        }

    },newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH),
            newCalendar.get(Calendar.DAY_OF_MONTH));

    datePickerDialogTo = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {

        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
            Calendar newDate = Calendar.getInstance();
            newDate.set(year, monthOfYear, dayOfMonth);
            editTextTo.setText(simpleDateFormat.format(newDate.getTime()));
            toDate = editTextTo.getText().toString();
        }

    },newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH),
            newCalendar.get(Calendar.DAY_OF_MONTH));
}

// on click method to handle which edit text was touched
// and show the appropriate pop up calendar
@Override
public void onClick(View view) {
    if(view == editTextFrom) {
        datePickerDialogFrom.show();
    } else if(view == editTextTo) {
        datePickerDialogTo.show();
    }
}

//method to set format of date and attach the array adapter to the list view
public void searchDates(View view){
    if(!editTextFrom.getText().toString().matches("From:")
            && !editTextTo.getText().toString().matches("To:")) {
            setDateTimeField();
            getProductionComments(fromDate, toDate);
            adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, results);
            listView.setAdapter(adapter);
        Log.d("fire",adapter.toString());
    }else{
        Toast.makeText(this,"Please enter valid dates", Toast.LENGTH_LONG).show();
    }
}

//get production comments data
public void getProductionComments(String from, String to) {
    try {
        SQLiteDatabase db = dbHandler.getReadableDatabase();

        String query = "SELECT Date,Item,Comments FROM ProductionCommentData WHERE Date " +
                "BETWEEN ? AND ? ORDER BY Date DESC";
        Cursor cursor = db.rawQuery(query,new String[]{from,to});

        if (cursor != null) {
            if (cursor.moveToFirst()) {
                do {
                    String date = cursor.getString(cursor.getColumnIndex("Date"));
                    String item = cursor.getString(cursor.getColumnIndex("Item"));
                    String comments = cursor.getString(cursor.getColumnIndex("Comments"));
                    results.add("Date: " + date.substring(0, 10) + newline + newline +
                            "Item: " + item + newline + newline + comments);
                } while (cursor.moveToNext());
            }else{
                Toast.makeText(this,"No Data was found for the chosen dates",Toast.LENGTH_LONG).show();
            }
        }
    } catch (SQLiteException se){
        Log.e(getClass().getSimpleName(), se.getMessage());
    }
}

Here is the layout code:-

<RelativeLayout xmlns:android="http://ift.tt/nIICcg"
xmlns:tools="http://ift.tt/LrGmb4" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context="com.qarun.qpcbeta.ProductionCommentsActivity"
android:id="@+id/relativeLayout">


<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:text="Production Comments"
    android:id="@+id/textView6"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true" />

<EditText
    android:layout_width="100dp"
    android:layout_height="wrap_content"
    android:inputType="date"
    android:ems="10"
    android:id="@+id/editTextFrom"
    android:layout_below="@+id/textView6"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_marginTop="29dp"
    android:editable="false"
    android:textSize="13sp"
    android:text="From:"
    android:focusable="false"/>

<EditText
    android:layout_width="100dp"
    android:layout_height="wrap_content"
    android:inputType="date"
    android:ems="10"
    android:id="@+id/editTextTo"
    android:layout_alignTop="@+id/editTextFrom"
    android:layout_toLeftOf="@+id/btnSearch"
    android:layout_toStartOf="@+id/btnSearch"
    android:textSize="13sp"
    android:textIsSelectable="false"
    android:text="To:"
    android:focusable="false"/>

<ListView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/listView"
    android:layout_below="@+id/editTextTo"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"/>

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Search"
    android:id="@+id/btnSearch"
    android:onClick="searchDates"
    android:layout_above="@+id/listView"
    android:layout_alignRight="@+id/listView"
    android:layout_alignEnd="@+id/listView"/>

thanks in advance

when i restart my emulator i cannot retrieve database values in sqlite windows phone 8.1

I designed a login and registration page using Sqlite database in windows phone 8.1. With the following code I can successfully insert and retrieve the values from sqlite database. But it happens only once. When I restart my emualator I cannot retrieve the values from database.

 protected async override void OnNavigatedTo(NavigationEventArgs e)
    {
        var dbpath = ApplicationData.Current.LocalFolder.Path + "/ebook.db";
        var con = new SQLiteAsyncConnection(dbpath);
        await con.CreateTableAsync<Register>();
    }
    private async void Button_Click(object sender, RoutedEventArgs e)
    {
        var dbpath = ApplicationData.Current.LocalFolder.Path + "/ebook.db";
        var con = new SQLiteAsyncConnection(dbpath);
        await con.CreateTableAsync<Register>();
        Register m = new Register();

        m.Name = text_reg.Text;
        m.Password = text_password.Password;
        string rd = "";
        if (radio_male.IsChecked == true)
        {
            rd = "Male";

        }
        else
        {
            rd = "Female";

        }
        m.Gender = rd;
        m.State = ((ComboBoxItem)combo_box.SelectedItem).Content.ToString();


        await con.InsertAsync(m);

        MessageDialog md = new MessageDialog("success");
        await md.ShowAsync();
    }

    private async void Button_Click_1(object sender, RoutedEventArgs e)
    {

        var dbpath = ApplicationData.Current.LocalFolder.Path + "/ebook.db";
        var con = new SQLiteAsyncConnection(dbpath);

        Register t = new Register();
        string query = string.Format("select Name,Password from Register where Name='{0}' and Password='{1}'", text_user.Text, text_pass.Password);
        List<Register> mylist = await con.QueryAsync<Register>(query);
        if (mylist.Count == 1)
        {
            t = mylist[0];
        }

        if (t.Name == text_user.Text && t.Password == text_pass.Password)
        {

            this.Frame.Navigate(typeof(MainPage));
        }
        else
        {
            var messagedialog = new MessageDialog("Unsuccessful").ShowAsync();
        }
    }
}

How to add a row at first position in SQlite Database Android?

I have a list of chat component which i need to update depending on the last element that i clicked. So when i access the data from my local db table i want this element as the first element.

Row Contains: id-primary key user name date image link

Thanks.

convert output from sqlite from tuple to list

I am new to programming and am writing a simple script that will gather some information from a PC for forensic purposes. Some of the information I want is the Chrome history. Basically I need to read the data from the history sqlite database, perform a calculation to convert the time stamp to a human readable format, and then write the data to a CSV file. I have the following code:

connection = sqlite3.connect('c:\history')### need correct path
connection.text_factory = str
cur = connection.cursor()
output_file = open('chrome_history2.csv', 'wb')
csv_writer = csv.writer(output_file,)
headers = ('URL', 'Title', 'Visit Count', 'Last Visit')
csv_writer.writerow(headers)
epoch = datetime(1601, 1, 1)
for row in (cur.execute('select url, title, visit_count, last_visit_time from urls limit 10')): #selects data
        list(row) #convert to list - does not work
        url_time = epoch + timedelta(microseconds=row[3]) #calculates time
        row[3] = url_time #changes value in row to readable time
        csv_writer.writerow(row)
connection.close()

This code returns the error:

TypeError: 'tuple' object does not support item assignment

I understand that I can't manipulate the data in a tuple but I am explicitly converting each row to a list. Can anyone explain a) why list (row) does not work, and b) a better way to do it?

Thanks in advance!

Reload View and Controller in Ionic Framework

I am building up an mobile application using Ionic Framework and Cordova Sqlite. I am displaying the data from the sqlite database in an ionic list. Each of the ionic list item has a button to delete the corresponding item from the database. On the click of the button, the data gets deleted from the database, but it continues to appear in the ionic list, until I go back to some other view and come back to it. I need to refresh the view immediately and remove that item from the list also. Also, all my SQL codes are in controller, so I also need to reload the controller, it seems.

app.js

.state('app.cart', {
    url: '/cart',
    views: {
      'menuContent': {
        cache: false,
        templateUrl: 'templates/cart.html',
        controller: 'NFController'
      }
    }
  })

controller.js

.controller('NFController', ['$scope', '$cordovaSQLite','$cordovaToast','$state','$stateParams', function($scope, $cordovaSQLite, $cordovaToast, $state,$stateParams) {


        $scope.listItems= [];
        $cordovaSQLite.execute(db, 'SELECT * FROM cart ORDER BY id DESC')
            .then(
                function(res) {

                    $scope.cartTotal=0;
                    $scope.crtPP=0;
                    if (res.rows.length > 0) {
                      for (var i=0; i<res.rows.length; i++) {
                        $scope.listItems.push(res.rows.item(i));
                      }
                    }
                    else{
                          $scope.status = "No Products in the Cart";
                    }
                },
                function(error) {
                    $scope.statusMessage = "Error on loading: " + error.message;
                }
            );


    $scope.remove = function(id) {

          $cordovaSQLite.execute(db, 'DELETE from cart WHERE id=?', [id])
            .then(function(res) {

                    //$state.go($state.current, {}, {reload: true});
                    var current = $state.current;
                    var params = angular.copy($stateParams);
                    $state.transitionTo(current, params, { reload: true, inherit: true, notify: true });  
                    $cordovaToast.show('Removed from Cart','short','bottom');

            }, function(error) {
                  console.log(error.message);
            })


    }
}])

remove() is called on the button click.

A simple architecture of distributed messenger

In general, how to construct a distributed architecture is the messenger? It can be forgiven. P.S. I would like to study the WCF technology and SQLite by creating their own distributed messenger. Sincerely.

Android Studio Terminal - SQLite Command (Up and Down Key not working)

I'm using terminal in Android Studio and normally it's working proper. But when I enter SQLite command mode by "adb shell" and (Up, Down, Left, Right) Keys are not working to navigate to call recently used sqlite command. When I press those keys, the symbols like the following are appeared. Please help.

enter image description here