vendredi 26 février 2016

Fetch data using sqlite in android with special parameters

Hello I need to made registeration where user fill all information then login activity using sqlite.Then I should fetch all user information if user sign in succesfully but only thing that I fetch is name and password when I tried to make also fetch additional information it comes with null.Firstly user sign up then sign in in that moment I check if username and password are correct but in this moment I want to fetch also a job and description in String that user fill in registration screen and pass to second activity if user succesfully sign in

ACtivity:

import android.content.Intent;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MainActivity extends AppCompatActivity {
    private DatabaseAdapter dbHelper;
    private EditText theUsername;
    private EditText thePassword;
    private Button loginButton;
    private Button registerButton;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        dbHelper = new DatabaseAdapter(this);
        dbHelper.open();
        setContentView(R.layout.activity_login);
        theUsername = (EditText) findViewById(R.id.email);
        thePassword = (EditText) findViewById(R.id.password);
        loginButton = (Button) findViewById(R.id.btnLogin);
        registerButton = (Button) findViewById(R.id.btnLinkToRegisterScreen);


        loginButton.setOnClickListener(new Button.OnClickListener(){
            public void onClick (View v){
                LogMeIn(v);
            }
        });

        registerButton.setOnClickListener(new Button.OnClickListener(){
            public void onClick (View v){
                Register(v);
            }
        });
    }


    private void LogMeIn(View v) {
        //Get the username and password
        String thisUsername = theUsername.getText().toString();
        String thisPassword = thePassword.getText().toString();

        //Assign the hash to the password
        thisPassword = md5(thisPassword);

        // Check the existing user name and password database
        Cursor theUser = dbHelper.fetchUser(thisUsername, thisPassword);
        if (theUser != null) {
            String[] text = dbHelper.getData();

            Log.i("AAAAA------------------","a"+text);



            startManagingCursor(theUser);
            if (theUser.getCount() > 0) {
                //saveLoggedInUId(theUser.getLong(theUser.getColumnIndex(DatabaseAdapter.COL_ID)), thisUsername, thePassword.getText().toString());
                stopManagingCursor(theUser);
                theUser.close();
               // String text = dbHelper.getYourData();
                Intent i = new Intent(v.getContext(), InfoActivity.class);
                startActivity(i);
            }

            //Returns appropriate message if no match is made
            else {
                Toast.makeText(getApplicationContext(),
                        "You have entered an incorrect username or password.",
                        Toast.LENGTH_SHORT).show();
               // saveLoggedInUId(0, "", "");
            }
            stopManagingCursor(theUser);
            theUser.close();
        }

        else {
            Toast.makeText(getApplicationContext(),
                    "Database query error",
                    Toast.LENGTH_SHORT).show();
        }
    }
    private void Register(View v)
    {
        Intent i = new Intent(v.getContext(), Register.class);
        startActivity(i);
    }

    private String md5(String s) {
        try {
            MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
            digest.update(s.getBytes());
            byte messageDigest[] = digest.digest();

            StringBuffer hexString = new StringBuffer();
            for (int i=0; i<messageDigest.length; i++)
                hexString.append(Integer.toHexString(0xFF & messageDigest[i]));

            return hexString.toString();
        }

        catch (NoSuchAlgorithmException e) {
            return s;
        }
    }
}

DbHelper:

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

/**
 * This class creates the relation with the SQLite Database Helper
 * through which queries can be SQL called.         
 * @author Andrei
 *
 */
public class DatabaseHelper extends SQLiteOpenHelper {
    // The database name and version
    private static final String DB_NAME = "login";
    private static final int DB_VERSION = 3;
    // The database user table
    private static final String DB_TABLE = "create table user (id integer primary key autoincrement, " 
                                            + "username text not null, password text not null, tel text not null, info text not null, job text);";
    /**
     * Database Helper constructor. 
     * @param context
     */
    public DatabaseHelper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
    }
    /**
     * Creates the database tables.
     */
    @Override
    public void onCreate(SQLiteDatabase database) {
        database.execSQL(DB_TABLE);
    }
    /**
     * Handles the table version and the drop of a table.   
     */         
    @Override
    public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {
        Log.w(DatabaseHelper.class.getName(),
                "Upgrading databse from version" + oldVersion + "to " 
                + newVersion + ", which will destroy all old data");
        database.execSQL("DROP TABLE IF EXISTS user");
        onCreate(database);
    }

}

DBAdapter:

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

/**
 * Adapts the database to deal with the front end.
 * 
 * @author Andrei
 *
 */
public class DatabaseAdapter {
    //Table name
    private static final String LOGIN_TABLE = "user";
    //Table unique id
    public static final String COL_ID = "id";
    //Table username and password columns 
    public static final String COL_USERNAME = "username";
    public static final String COL_PASSWORD = "password";
    private static final String KEY_PHONE = "tel";
    private static final String INFO = "info";
    private static final String JOB = "info";


    private Context context;
    private SQLiteDatabase database;
    private DatabaseHelper dbHelper;

    /**
     * The adapter constructor. 
     * @param context
     */
    public DatabaseAdapter(Context context) {
        this.context = context;
    }

    /**
     * Creates the database helper and gets the database. 
     * 
     * @return
     * @throws SQLException
     */
    public DatabaseAdapter open() throws SQLException {
        dbHelper = new DatabaseHelper(context);
        database = dbHelper.getWritableDatabase();
        return this;
    }

    /**
     * Closes the database.
     */
    public void close() {
        dbHelper.close();
    }

    /**
     * Creates the user name and password.
     * 
     * @param username The username.
     * @param password The password.
     * @return
     */
    public long createUser(String username, String password, String tel, String info,String job) {
        ContentValues initialValues = createUserTableContentValues(username, password,tel,info,job);
        return database.insert(LOGIN_TABLE, null, initialValues);
    }

    /**
     * Removes a user's details given an id.
     * 
     * @param rowId Column id. 
     * @return
     */
    public boolean deleteUser(long rowId) {
        return database.delete(LOGIN_TABLE, COL_ID + "=" + rowId, null) > 0;
    }

//  public boolean updateUserTable(long rowId, String username, String password) {
//      ContentValues updateValues = createUserTableContentValues(username, password);
//      return database.update(LOGIN_TABLE, updateValues, COL_ID + "=" + rowId, null) > 0;
//  }

    /**
     * Retrieves the details of all the users stored in the login table.
     * 
     * @return
     */
    public Cursor fetchAllUsers() {
        return database.query(LOGIN_TABLE, new String[] { COL_ID, COL_USERNAME, 
                COL_PASSWORD }, null, null, null, null, null);
    }

    /**
     * Retrieves the details of a specific user, given a username and password.
     * 
     * @return
     */
    public Cursor fetchUser(String username, String password) {
        Cursor myCursor = database.query(LOGIN_TABLE, 
                new String[] { COL_ID, COL_USERNAME, COL_PASSWORD }, 
                COL_USERNAME + "='" + username + "' AND " + 
                COL_PASSWORD + "='" + password + "'", null, null, null, null);

        if (myCursor != null) {
            myCursor.moveToFirst();
        }
        return myCursor;
    }


    /**
     * Returns the table details given a row id.
     * @param rowId The table row id. 
     * @return
     * @throws SQLException
     */
    public Cursor fetchUserById(long rowId) throws SQLException {
        Cursor myCursor = database.query(LOGIN_TABLE, 
                new String[] { COL_ID, COL_USERNAME, COL_PASSWORD }, 
                COL_ID + "=" + rowId, null, null, null, null);
        if (myCursor != null) {
            myCursor.moveToFirst();
        }
        return myCursor;
    }


    public String[] getData() {

        final String TABLE_NAME = "user";

        String selectQuery = "SELECT  * FROM " + TABLE_NAME;
        //SQLiteDatabase db  = this.getReadableDatabase();
        Cursor cursor      = database.rawQuery(selectQuery, null);
        String[] data      = null;

        if (cursor.moveToFirst()) {
            do {
                // get the data into array, or class variable
            } while (cursor.moveToNext());
        }
        cursor.close();
        return data;
    }
    /**
     * Stores the username and password upon creation of new login details.
     * @param username The user name.
     * @param password The password.
     * @param tel
     * @return The entered values.
     */
    private ContentValues createUserTableContentValues(String username, String password, String tel, String info, String job) {
        ContentValues values = new ContentValues();
        values.put(COL_USERNAME, username);
        values.put(COL_PASSWORD, password);
        values.put(KEY_PHONE, tel);
        values.put(INFO, info);
        values.put(JOB, job);
        return values;
    }
}

Sign in:

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:orientation="vertical"
            android:paddingLeft="20dp"
            android:paddingRight="20dp" >

            <EditText
                android:id="@+id/email"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="10dp"
                android:background="@color/white"
                android:hint="Nickname"
                android:inputType="textEmailAddress"
                android:padding="10dp"
                android:singleLine="true"
                android:textColor="@color/input_login"
                android:textColorHint="@color/input_login_hint" />

            <EditText
                android:id="@+id/password"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="10dp"
                android:background="@color/white"
                android:hint="@string/hint_password"
                android:inputType="textPassword"
                android:padding="10dp"
                android:singleLine="true"
                android:textColor="@color/input_login"
                android:textColorHint="@color/input_login_hint" />

            <!-- Login Button -->

            <Button
                android:id="@+id/btnLogin"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="20dip"
                android:background="@color/btn_login_bg"
                android:text="@string/btn_login"
                android:textColor="@color/btn_login" />

            <!-- Link to Login Screen -->

            <Button
                android:id="@+id/btnLinkToRegisterScreen"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="40dip"
                android:background="@null"
                android:text="Регистрация"
                android:textAllCaps="false"
                android:textColor="@color/white"
                android:textSize="15dp" />
        </LinearLayout>

    </LinearLayout>

register:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://ift.tt/nIICcg"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@color/bg_main"
    android:gravity="center"
    android:orientation="vertical"
    android:padding="10dp" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:orientation="vertical"
        android:paddingLeft="20dp"
        android:paddingRight="20dp" >

        <EditText
            android:id="@+id/name"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dp"
            android:background="@color/input_register_bg"
            android:hint="@string/hint_name"
            android:padding="10dp"
            android:singleLine="true"
            android:inputType="textCapWords"
            android:textColor="@color/input_register"
            android:textColorHint="@color/input_register_hint" />

        <EditText
            android:id="@+id/password"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dp"
            android:background="@color/input_register_bg"
            android:hint="@string/hint_password"
            android:inputType="textPassword"            android:padding="10dp"
            android:singleLine="true"
            android:textColor="@color/input_register"
            android:textColorHint="@color/input_register_hint" />

        <EditText
            android:id="@+id/tel"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dp"
            android:background="@color/input_register_bg"
            android:hint="Telephone"
            android:inputType="phone"
            android:padding="10dp"
            android:singleLine="true"
            android:textColor="@color/input_register"
            android:textColorHint="@color/input_register_hint" />

        <!-- Login Button -->

        <Spinner
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/spinner"/>
        <EditText
                android:id="@+id/info"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="10dp"
                android:background="@color/input_register_bg"
                android:hint="Info"
                android:padding="10dp"
                android:singleLine="true"
                android:inputType="textCapWords"
                android:textColor="@color/input_register"
                android:textColorHint="@color/input_register_hint" />


        <Button
            android:id="@+id/btnRegister"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="100dip"
            android:background="#402187"
            android:text="@string/btn_register"
            android:textColor="@color/white" />

        <!-- Link to Login Screen -->

    </LinearLayout>

</LinearLayout>

Aucun commentaire:

Enregistrer un commentaire