andbook!.pdf - Learning Android Get an anddev.org - Android-Shirt Back to index
anddev.org Header Logo
FAQ Search Top rated articles Browse Feeds anddev.org - Authors Contact Details Register Log in

Working with the SQLite-Database - Cursors

Goto page Previous  1, 2, 3, 4, 5, 6, 7  Next
 
       anddev.org - Android Development Community | Android Tutorials | Index -> Novice Tutorials
Author Message
dhaiwat
Developer
Developer


Joined: 10 Feb 2009
Posts: 26

PostPosted: Mon Feb 23, 2009 12:15 pm    Post subject: date print on mobile screen Reply with quote

hello friend

i am new with android

i want to print current date on mobile screen

what i do.

i want to take today's date from sqlite query

any one help me how i get date in textview from query result..
Back to top
View user's profile Send private message Send e-mail
dhaiwat
Developer
Developer


Joined: 10 Feb 2009
Posts: 26

PostPosted: Tue Feb 24, 2009 11:47 am    Post subject: database query problem Reply with quote

hello friends

i have two table

1. Student --- fields (RollNo,StudentName)

2. Marks ----- fields (RollNo,Sub1,Sub2,Sub3)



if write join or inner query in sqlie> prompt it is work

select s.StudentName,m.sub1,m.sub2,m.sub3 from Student s,Marks m where s.RollNo = m.RollNo;


-------------------------------------------------------------------------------------------

but when i write it in to application it is not working



Cursor c = mydb.rawQuery("SELECT s.StudentName,m.sub1,m.sub2,m.sub3 FROM Student s,Marks m WHERE s.RollNo = m.RollNo LIMIT 7;", null);

int namecolumn = c.getColumnIndex("StudentName");
int rollnocolumn = c.getColumnIndex("RollNo");

if (c != null) {

if (c.moveToFirst()) {
int i = 0;
do {
i++;
int Sub1m = c.getInt(rollnocolumn);
int Sub2m = c.getInt(sub2column);
int Sub3m = c.getInt(sub3column);
String Name = c.getString(namecolumn);
// String stucolumName = c.getColumnName(namecolumn);

results.add("" + i + ":" + Name + ":" + Sub1m + ":" + sub2m + ":" + sub3m);

} while (c.moveToNext());
}
}

plz help how it done?
Back to top
View user's profile Send private message Send e-mail
nuggetgtr
Freshman
Freshman


Joined: 06 Jan 2009
Posts: 5

PostPosted: Wed Feb 25, 2009 3:34 am    Post subject: Reply with quote

Hi All,

hope someone can help me. I have a program which loads a spinner with a preset lot of values and then I will have people adding extra items which I will store in a database. but for now just testing it I am manully putting in some data. Im new to sql so im not quiet sure what im doing Very Happy

here is my function

Java:
private void populatespinner(){
          ArrayAdapter<String> saa=new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, spentonitems);
          saa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
          spentonspin.setAdapter(saa);
          
     SQLiteDatabase mydb = null;
          try {
     mydb = this.openOrCreateDatabase(MY_DATABASE_NAME, MODE_PRIVATE, null);
          mydb.execSQL("CREATE TABLE IF NOT EXISTS "+ MY_DATABASE_TABLE + "(spent VARCHAR, num INT(2));");
          mydb.execSQL("INSERT INTO " + MY_DATABASE_TABLE + " (spent, num)" + " VALUES ('TESTING', 2)Wink");

          Cursor c = mydb.rawQuery("SELECT spent,num" + " FROM " + MY_DATABASE_TABLE + " WHERE num > 1;", null);
          
          int spentcol = c.getColumnIndex("spent");
          int numcol = c.getColumnIndex("num");
          String spentonvar;
          if (c != null) {
               if (c.moveToFirst()) {
                    int i = 0;

                    do {
                         i++;
                         spentonvar = c.getString(spentcol);
                         saa.add(spentonvar);
                    } while (c.moveToNext());
               }
          }
      }  finally {
          if (mydb != null)
              mydb.close(); }

}


Im getting application stopped unexpectedly If I comment the DB stuff out and just have the first arrayadaper part, the program works fine with the set values.

hope someone can shead some light on this for me..

Cheers
Back to top
View user's profile Send private message
Klian
Freshman
Freshman


Joined: 18 Feb 2009
Posts: 2

PostPosted: Wed Feb 25, 2009 12:11 pm    Post subject: Reply with quote

Hi Smile

I have a problem with this simple testing code.

The problem with:

Java:
this.createDatabase(MY_DATABASE_NAME, 1, MODE_PRIVATE, null);


It says:
"the method createDatabase is undefined"

Im noob at java...so any help would be appreciated Smile

The code:

Java:
package org.klian.android.Hello_World;

import java.io.FileNotFoundException;
import java.util.ArrayList;

import android.app.ListActivity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.util.Log;

public class Hello_World extends ListActivity {
     private final String MY_DATABASE_NAME = "LoginDB";
    private final String MY_DATABASE_TABLE = "Login1";
    private final String tag="Klian";
   
    public void onCreate(Bundle icicle) {
     super.onCreate(icicle);
     
     ArrayList<String> results = new ArrayList<String>();
        SQLiteDatabase myDB = null;
       
        try{
         
          this.createDatabase(MY_DATABASE_NAME, 1, MODE_PRIVATE, null);
          Log.i(tag,"Base de datos creada");
         
        }catch(Exception e){
          Log.i(tag,"------"+e.getMessage());
            Log.i(tag,"++++++"+e);
        }
    }
}
Back to top
View user's profile Send private message
nuggetgtr
Freshman
Freshman


Joined: 06 Jan 2009
Posts: 5

PostPosted: Wed Feb 25, 2009 11:28 pm    Post subject: Reply with quote

Kilan try
Java:
this.openOrCreateDatabase(MY_DATABASE_NAME, MODE_PRIVATE, null);


Think I had the same issue when using
Java:
this.createDatabase(MY_DATABASE_NAME, 1, MODE_PRIVATE, null);
Back to top
View user's profile Send private message
pippo
Freshman
Freshman


Joined: 04 Mar 2009
Posts: 3

PostPosted: Wed Mar 04, 2009 1:04 pm    Post subject: Reply with quote

hi @ all,

first of all sorry for my english..and thanks for posting tutorials like this.

i tried it but when i run the application all i get is a black screen. could anyone help me please (should i post my code for that?)
thanks in advance,

greets,
pippo
Back to top
View user's profile Send private message
pippo
Freshman
Freshman


Joined: 04 Mar 2009
Posts: 3

PostPosted: Fri Mar 06, 2009 9:00 pm    Post subject: Reply with quote

hey,

i solved my problem. but i have another question: how can i clear the result list?
thx to all,

greets
pippo
Back to top
View user's profile Send private message
[XJrE]
Freshman
Freshman


Joined: 08 Mar 2009
Posts: 2

PostPosted: Sun Mar 08, 2009 4:49 am    Post subject: DB error... Reply with quote

Hi people, i have a problem with my DB.

I have this code:
DB.java
Java:

package com.android.database;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Map;

import android.app.ListActivity;

import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.os.Bundle;


import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import java.io.FileNotFoundException;

import com.android.Parametros;
import com.android.WsMetodos;
import com.android.WsServicos;

import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;


public class DB extends Activity{
     
     private Context dbContext;
     private static final String DATABASE_NAME = "DViewDB";
     private static final int DATABASE_VERSION = 1;
    private SQLiteDatabase dbDView;
     private WsServicos auxServico = new WsServicos();
     private WsMetodos auxMetodos = new WsMetodos();
     private Parametros auxParametros = new Parametros();
     private Parametros auxReturns = new Parametros();
     
     /**
    * Comandos SQL para criação das tabelas
    */

     private static final String TABLE_SERVICES =
          "CREATE TABLE IF NOT EXISTS tbSERVICES " +
          "(ID_SERVICE integer primary key autoincrement, " +
          "NAME text not null, " +
          "LOCATION text not null);";
     
     private static final String TABLE_METHODS =
          "CREATE TABLE IF NOT EXISTS tbMETHODS " +
          "(ID_METHOD integer primary key autoincrement, " +
          "ID_SERVICE integer not null, " +
          "NAME text not null, " +
          "DESCRIPTION text not null);";
     
     private static final String TABLE_PARAMS =
          "CREATE TABLE IF NOT EXISTS tbPARAMETERS " +
          "(ID_PARAMETER integer primary key autoincrement, " +
          "ID_METHOD integer not null, " +
          "NAME text not null, " +
          "TYPE text not null);";
     
     private static final String TABLE_RETURNS =
          "CREATE TABLE IF NOT EXISTS tbRETURNS " +
          "(ID_RETURN integer primary key autoincrement, " +
          "ID_METHOD integer not null, " +
          "NAME text not null, " +
          "TYPE text not null);";
     
    public DB(Context context) {
     this.dbContext = context;
     
        dbDView = dbContext.openOrCreateDatabase(DATABASE_NAME, MODE_PRIVATE, null);
       
     dbDView.execSQL(TABLE_SERVICES);
     dbDView.execSQL(TABLE_METHODS);
     dbDView.execSQL(TABLE_PARAMS);
     dbDView.execSQL(TABLE_RETURNS);
    }
   
    public void closeDB(){
     dbDView.close();
    }
   
    /**
     * Create a new note using the title and body provided. If the note is successfully created
     * return the new rowId for that note, otherwise return a -1 to indicate failure.
     * @param title the title of the note
     * @param body the body of the note
     * @return rowId or -1 if failed
     */


     public long createElement(String dbTable, ContentValues values) {
          return dbDView.insert(dbTable, null, values);
     }
     
    /**
     * Update the note using the details provided. The note to be updated is specified using
     * the rowId, and it is altered to use the title and body values passed in
     * @param rowId id of note to update
     * @param title value to set note title to
     * @param body value to set note body to
     * @return true if the note was successfully updated, false otherwise
     */

    public boolean updateElement(String dbTable, ContentValues values, String selection) {
        return dbDView.update(dbTable, values, selection, null) > 0;
    }
   
    /**
     * Return a Cursor over the list of all elements in the database
     * @return Cursor over all elements
     */

     public Cursor fetchAllElements(String dbTable, String[] column) {
        return dbDView.query(dbTable, column, null, null, null, null, null);
    }

    /**
     * Return a Cursor positioned at the element that matches the given selection
     * @param
     * @return Cursor positioned to matching element, if found
     * @throws SQLException if element could not be found/retrieved
     */

    //public Cursor fetchElementSQL(String dbTable, String[] column, String selection, String[] selectionArgs) {
   
     public Cursor fetchElementSQL(String sql) {
     return dbDView.rawQuery(sql, null);
    }
     
    /**
     * Return a Cursor positioned at the element that matches the given selection
     * @param
     * @return Cursor positioned to matching element, if found
     * @throws SQLException if element could not be found/retrieved
     */

    public Cursor fetchElement(String dbTable, String[] column, String selection, String[] selectionArgs) {
     
     SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
     qb.setTables(dbTable);
     qb.appendWhere(selection);
     
     Cursor c = qb.query(dbDView, null, null, selectionArgs, null, null, null);
     return c;
     /*
     Cursor result = mDb.query(dbTable, column, selection, selectionArgs, null, null, null);
        if ((result.getCount() == 0) || !result.isFirst()) {
            throw new SQLException("No element matching ID: " + column);
        }
        return result;
        */

    }
   
    public Boolean saveServices(Map services){
     
     ContentValues values = new ContentValues();
     int qntd = 0;
     long rowID = 0;
     
     try {
          for (int q = 0; q<=services.size(); q++){
               auxServico = (WsServicos) services.get(q);
               values.put("NAME", auxServico.getNome());
               values.put("LOCATION", auxServico.getAddressLocation());
               
               rowID = this.createElement(TABLE_SERVICES, values);
          }
          } catch (Exception e) {
               // TODO: handle exception
               return false;
          }
          return false;
    }
}


...and log error is:
Code:

03-08 01:31:03.096: WARN/dalvikvm(450): threadid=3: thread exiting with uncaught exception (group=0x40010e28)
03-08 01:31:03.104: ERROR/AndroidRuntime(450): Uncaught handler: thread main exiting due to uncaught exception
03-08 01:31:03.295: ERROR/AndroidRuntime(450): java.lang.NullPointerException
03-08 01:31:03.295: ERROR/AndroidRuntime(450):     at android.content.ContextWrapper.openOrCreateDatabase(ContextWrapper.java:181)
03-08 01:31:03.295: ERROR/AndroidRuntime(450):     at com.android.database.DB.openOrCreateDB(DB.java:77)
03-08 01:31:03.295: ERROR/AndroidRuntime(450):     at com.android.SearchServices.<init>(SearchServices.java:22)
03-08 01:31:03.295: ERROR/AndroidRuntime(450):     at com.android.DView$3.onClick(DView.java:80)
03-08 01:31:03.295: ERROR/AndroidRuntime(450):     at android.view.View.performClick(View.java:2109)
03-08 01:31:03.295: ERROR/AndroidRuntime(450):     at android.view.View.onTouchEvent(View.java:3523)
03-08 01:31:03.295: ERROR/AndroidRuntime(450):     at android.widget.TextView.onTouchEvent(TextView.java:4410)
03-08 01:31:03.295: ERROR/AndroidRuntime(450):     at android.view.View.dispatchTouchEvent(View.java:3178)
03-08 01:31:03.295: ERROR/AndroidRuntime(450):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:857)
03-08 01:31:03.295: ERROR/AndroidRuntime(450):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:857)
03-08 01:31:03.295: ERROR/AndroidRuntime(450):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:857)
03-08 01:31:03.295: ERROR/AndroidRuntime(450):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:857)
03-08 01:31:03.295: ERROR/AndroidRuntime(450):     at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:1561)
03-08 01:31:03.295: ERROR/AndroidRuntime(450):     at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1085)
03-08 01:31:03.295: ERROR/AndroidRuntime(450):     at android.app.Activity.dispatchTouchEvent(Activity.java:1873)
03-08 01:31:03.295: ERROR/AndroidRuntime(450):     at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:1545)
03-08 01:31:03.295: ERROR/AndroidRuntime(450):     at android.view.ViewRoot.handleMessage(ViewRoot.java:1140)
03-08 01:31:03.295: ERROR/AndroidRuntime(450):     at android.os.Handler.dispatchMessage(Handler.java:88)
03-08 01:31:03.295: ERROR/AndroidRuntime(450):     at android.os.Looper.loop(Looper.java:123)
03-08 01:31:03.295: ERROR/AndroidRuntime(450):     at android.app.ActivityThread.main(ActivityThread.java:3742)
03-08 01:31:03.295: ERROR/AndroidRuntime(450):     at java.lang.reflect.Method.invokeNative(Native Method)
03-08 01:31:03.295: ERROR/AndroidRuntime(450):     at java.lang.reflect.Method.invoke(Method.java:515)
03-08 01:31:03.295: ERROR/AndroidRuntime(450):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:739)
03-08 01:31:03.295: ERROR/AndroidRuntime(450):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:497)
03-08 01:31:03.295: ERROR/AndroidRuntime(450):     at dalvik.system.NativeStart.main(Native Method)


Can help me?

Sorry for my bad english.

Jr.
Back to top
View user's profile Send private message
isaackearl
Junior Developer
Junior Developer


Joined: 25 Nov 2008
Posts: 20

PostPosted: Mon Mar 09, 2009 1:22 am    Post subject: Reply with quote

Hey,

I got really excited when I found this tutorial. I've worked with databases before, but am having trouble getting one going in android. I downloaded the source you have here and I couldn't get it working. none of the layouts etc and resources you refer to are there.. and I think the tutorial is to old for the current build of android. I could really use some help on this, so if you could update this tutorial that would be fantastic.

thanks,
Isaac
Back to top
View user's profile Send private message
desuvinodkumar
Senior Developer
Senior Developer


Joined: 23 Mar 2009
Posts: 100
Location: India

PostPosted: Tue Mar 24, 2009 8:13 am    Post subject: Re: Plz help Reply with quote

cybersat wrote:
hi,
Please attach full working source code, i am unable to view database details.
1. Kindly attach full source code.zip
2. How can we view databases and tables using command prompt.






i'm getting the error while i'm running the databasework project
ERROR org.anddev.android.databasework.DataBaseWork does not extend android.app.Activity

Code iS
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.anddev.android.databasework">
<application android:icon="@drawable/icon"
android:label="@string/app_name">
<activity android:name=".DataBaseWork"
android:label="@string/app_name">

<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

Can i know where is the Problem

_________________
Vinod...
Back to top
View user's profile Send private message Send e-mail Visit poster's website Yahoo Messenger MSN Messenger
cjules86
Freshman
Freshman


Joined: 15 Apr 2009
Posts: 5

PostPosted: Wed Apr 15, 2009 8:53 pm    Post subject: Saving Reply with quote

Hi,

Can anyone tell me if the sqlite DB is automatically saved (i.e. you close the application and then load it and work with the database again)? Currently I have a working sqlite db but when i close the application (this.finish()) and then start the app up again it does not load data.

Example:
1) I insert a value of 3 into a table, then do a query to retrieve information from that table and it returns 3.
2) I insert a value of 3 into a table, then quit the application with this.finish(), then start the application again and do the same query and it returns a value of 0.

Am I closing the application incorrectly? Any help is appreciated.

Here is basically what I do in my "loadDB" function:
Java:

myDB = a.openOrCreateDatabase("gstock_user_data", MODE_PRIVATE, null);
               
               //Get money info
               Cursor c = myDB.query("Money", new String[] {"banktransactions", "bankaccount"}, null, null, null, null, null);
               if(c != null)
               {
                    if(c.getCount() == 1)
                    {
                         banktransactions = Integer.parseInt(c.getString(c.getColumnIndex("banktransactions")));
                         bankaccount = Integer.parseInt(c.getString(c.getColumnIndex("bankaccount")));
                    }
               }
               return banktransactions;
Back to top
View user's profile Send private message
ddtdpro
Freshman
Freshman


Joined: 02 May 2009
Posts: 6

PostPosted: Thu Jun 25, 2009 4:22 am    Post subject: Reply with quote

pippo wrote:
hi @ all,

first of all sorry for my english..and thanks for posting tutorials like this.

i tried it but when i run the application all i get is a black screen. could anyone help me please (should i post my code for that?)
thanks in advance,

greets,
pippo


i also have the same problem with you. I run and i have a blank screen. I did change something is the code, some functions don't exist like (myDB.createDatabase, c.first(), c.next() ) so i change to (myDB.openOrCreateDatabase, c.isFirst(), c.moveToNext() ). Is it correct or did i change anything wrong? can you help me plz? I have to do something with the database but i can't find any other good examples but this

Thanks
Back to top
View user's profile Send private message
CoCo
Freshman
Freshman


Joined: 15 Jul 2009
Posts: 2

PostPosted: Wed Jul 15, 2009 10:25 pm    Post subject: Reply with quote

Hey PlusMimus,

Thank you so much for showing how to create a SQLite database. I am new Android user and I am currently working on my first Android game. Now I am trying to figure out how to create a high score table that would display the top 10 scores and store data in the SQLite database( instead of using a service like many game developers do). I read many tutorials on high score lists and SqLite database but they were not very helpful. Can you please help with this issue.

Thanks kindly
Back to top
View user's profile Send private message
nmc
Senior Developer
Senior Developer


Joined: 27 Nov 2008
Posts: 154
Location: Germany

PostPosted: Thu Jul 16, 2009 1:44 am    Post subject: Reply with quote

Quote:

Now I am trying to figure out how to create a high score table that would display the top 10 scores and store data in the SQLite database

Create:
create table hi (player: text, score: integer)


Display:
select player, score
from hi
order by score desc
limit 10
Back to top
View user's profile Send private message
Rashi
Junior Developer
Junior Developer


Joined: 10 Sep 2009
Posts: 20

PostPosted: Fri Sep 11, 2009 3:05 pm    Post subject: Reply with quote

I am having some errors when i run this code which are:

1.openDatabase(MY_DATABASE_NAME, null);
2.createDatabase(MY_DATABASE_NAME, 1, MODE_PRIVATE, null);

It says to create these gunctions and then use it.

Rashi.
Back to top
View user's profile Send private message
Display posts from previous:   
       anddev.org - Android Development Community | Android Tutorials | Index -> Novice Tutorials All times are GMT + 1 Hour
Goto page Previous  1, 2, 3, 4, 5, 6, 7  Next
Page 5 of 7

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum
You cannot attach files in this forum
You can download files in this forum


© 2007, Android Development Community
All rights reserved.
Powered by phpBB.