Home Menu

Menu



Programación y Desarrollo para Android Subforo exclusivo para temas de programación de software para PDAs y desarrollo de aplicaciones, interfaces, etc bajo Android


 
Herramientas
  #1  
Viejo 30/08/15, 15:05:16
Avatar de deth
deth deth no está en línea
Usuario poco activo
Mensajes: 3
 
Fecha de registro: ago 2015
Mensajes: 3
Tu operador: Movistar
Mencionado: 0 comentarios
Tagged: 0 hilos
como hacer consulta en android

hola amigos necesito saber como hacer un boton que yo haga click y me aparezcan todos los usuarios y claves guardados en Sqlite aqui les dejo mi codigo:

LoginDataBaseAdapter.java

Código:
package com.techblogon.loginexample;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class LoginDataBaseAdapter 
{
    
    
        static final String DATABASE_NAME = "login.db";
        static final int DATABASE_VERSION = 1;
        public static final int NAME_COLUMN = 1;
        // TODO: Create public field for each column in your table.
        // SQL Statement to create a new database.
        static final String DATABASE_CREATE = "create table "+"LOGIN"+
                                     "( " +"ID"+" integer primary key autoincrement,"+ "USERNAME  text,PASSWORD text); ";
        // Variable to hold the database instance
        public  SQLiteDatabase db;
        // Context of the application using the database.
        private final Context context;
        // Database open/upgrade helper
        private DataBaseHelper dbHelper;
        public  LoginDataBaseAdapter(Context _context) 
        {
            context = _context;
            dbHelper = new DataBaseHelper(context, DATABASE_NAME, null, DATABASE_VERSION);
        }
        public  LoginDataBaseAdapter open() throws SQLException 
        {
            db = dbHelper.getWritableDatabase();
            return this;
        }
        public void close() 
        {
            db.close();
        }

        public  SQLiteDatabase getDatabaseInstance()
        {
            return db;
        }

        public void insertEntry(String userName,String password)
        {
           ContentValues newValues = new ContentValues();
            // Assign values for each row.
            newValues.put("USERNAME", userName);
            newValues.put("PASSWORD",password);
            
            // Insert the row into your table
            db.insert("LOGIN", null, newValues);
            ///Toast.makeText(context, "Reminder Is Successfully Saved", Toast.LENGTH_LONG).show();
        }
        public int deleteEntry(String UserName)
        {
            //String id=String.valueOf(ID);
            String where="USERNAME=?";
            int numberOFEntriesDeleted= db.delete("LOGIN", where, new String[]{UserName}) ;
           // Toast.makeText(context, "Number fo Entry Deleted Successfully : "+numberOFEntriesDeleted, Toast.LENGTH_LONG).show();
            return numberOFEntriesDeleted;
        }    
        public String getSinlgeEntry(String userName)
        {
            Cursor cursor=db.query("LOGIN", null, " USERNAME=?", new String[]{userName}, null, null, null);
            if(cursor.getCount()<1) // UserName Not Exist
            {
                cursor.close();
                return "NOT EXIST";
            }
            cursor.moveToFirst();
            String password= cursor.getString(cursor.getColumnIndex("PASSWORD"));
            cursor.close();
            return password;                
        }
        public void  updateEntry(String userName,String password)
        {
            // Define the updated row content.
            ContentValues updatedValues = new ContentValues();
            // Assign values for each row.
            updatedValues.put("USERNAME", userName);
            updatedValues.put("PASSWORD",password);
            
            String where="USERNAME = ?";
            db.update("LOGIN",updatedValues, where, new String[]{userName});               
        }        
}
DataBaseHelper.java

Código:
package com.techblogon.loginexample;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DataBaseHelper extends SQLiteOpenHelper
{
    public DataBaseHelper(Context context, String name,CursorFactory factory, int version) 
    {
               super(context, name, factory, version);
    }
    // Called when no database exists in disk and the helper class needs
    // to create a new one.
    @override
    public void onCreate(SQLiteDatabase _db) 
    {
            _db.execSQL(LoginDataBaseAdapter.DATABASE_CREATE);
            
    }
    // Called when there is a database version mismatch meaning that the version
    // of the database on disk needs to be upgraded to the current version.
    @override
    public void onUpgrade(SQLiteDatabase _db, int _oldVersion, int _newVersion) 
    {
            // Log the version upgrade.
            Log.w("TaskDBAdapter", "Upgrading from version " +_oldVersion + " to " +_newVersion + ", which will destroy all old data");
    
    
            // Upgrade the existing database to conform to the new version. Multiple
            // previous versions can be handled by comparing _oldVersion and _newVersion
            // values.
            // The simplest case is to drop the old table and create a new one.
            _db.execSQL("DROP TABLE IF EXISTS " + "TEMPLATE");
            // Create a new one.
            onCreate(_db);
    }
    

}
muchas gracias de antemano.
Responder Con Cita


  #2  
Viejo 30/08/15, 16:09:19
Avatar de mocelet
mocelet mocelet no está en línea
Desarrollador
Mensajes: 2,203
 
Fecha de registro: may 2011
Localización: Madrid
Mensajes: 2,203
Tu operador: -
Mencionado: 17 comentarios
Tagged: 2 hilos
http://www.sgoliver.net/blog/bases-d...rar-registros
Responder Con Cita
  #3  
Viejo 31/08/15, 13:24:27
Avatar de pozako
pozako pozako no está en línea
Usuario poco activo
Mensajes: 48
 
Fecha de registro: sep 2011
Mensajes: 48
Tu operador: Movistar
Mencionado: 0 comentarios
Tagged: 0 hilos
Debes de recoger los datos de la BD mediante un cursor ,junto con su consulta, recorriendolo mediante un while, ya que vas a recuperar dos datos relacionados entre ellos, crearía un objeto en el cual almacenaría dicha información con lo que quedaría un nombre y contraseña por objeto,el cual lo vamos a añadir a un ArrayList donde guardaremos toda esta información para luego mediante un ArrayAdapter presentar estos datos dentro de nuestro ListView.
Responder Con Cita
Respuesta

Estás aquí
Regresar   HTCMania > Todo sobre Android > Programación y Desarrollo para Android


Reglas de Mensajes
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Las caritas están On
Código [IMG] está On
Código HTML está Off

Saltar a Foro



Hora actual: 12:11:48 (GMT +2)

Cookies
Powered by vBulletin™
Copyright © vBulletin Solutions, Inc. All rights reserved.
 
HTCMania: líderes desde el 2007