mercredi 22 avril 2015

obtaining user prefs specifically for an account

We are trying to make an application in which the user can register their account and then log on with said account. However, right now we are trying to save the user's inputted data to their account.

Basically, when I change something in my settings screen while logged on my account, I want those settings to be saved for that account only.

The Login Activity:

public class LoginActivity extends Activity {
// LogCat tag
private static final String TAG = RegisterActivity.class.getSimpleName();
private Button btnLogin;
private Button btnLinkToRegister;
private EditText inputEmail;
private EditText inputPassword;
private ProgressDialog pDialog;
private SessionManager session;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    inputEmail = (EditText) findViewById(R.id.email);
    inputPassword = (EditText) findViewById(R.id.password);
    btnLogin = (Button) findViewById(R.id.btnLogin);
    btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);

    // Progress dialog
    pDialog = new ProgressDialog(this);
    pDialog.setCancelable(false);

    // Session manager
    session = new SessionManager(getApplicationContext());

    // Check if user is already logged in or not
    if (session.isLoggedIn()) {
        // User is already logged in. Take him to main activity
        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
        startActivity(intent);
        finish();
    }

    // Login button Click Event
    btnLogin.setOnClickListener(new View.OnClickListener() {

        public void onClick(View view) {
            String email = inputEmail.getText().toString();
            String password = inputPassword.getText().toString();

            // Check for empty data in the form
            if (email.trim().length() > 0 && password.trim().length() > 0) {
                // login user
                checkLogin(email, password);
            } else {
                // Prompt user to enter credentials
                Toast.makeText(getApplicationContext(),
                        "Please enter the credentials!", Toast.LENGTH_LONG)
                        .show();
            }
        }

    });

    // Link to Register Screen
    btnLinkToRegister.setOnClickListener(new View.OnClickListener() {

        public void onClick(View view) {
            Intent i = new Intent(getApplicationContext(),
                    RegisterActivity.class);
            startActivity(i);
            finish();
        }
    });

}

/**
 * function to verify login details in mysql db
 * */
private void checkLogin(final String email, final String password) {
    // Tag used to cancel the request
    String tag_string_req = "req_login";

    pDialog.setMessage("Logging in ...");
    showDialog();

    StringRequest strReq = new StringRequest(Method.POST,
            AppConfig.URL_REGISTER, new Response.Listener<String>() {

        @Override
        public void onResponse(String response) {
            Log.d(TAG, "Login Response: " + response.toString());
            hideDialog();

            try {
                JSONObject jObj = new JSONObject(response);
                boolean error = jObj.getBoolean("error");

                // Check for error node in json
                if (!error) {
                    // user successfully logged in
                    // Create login session
                    session.setLogin(true);

                    // Launch main activity
                    Intent intent = new Intent(LoginActivity.this,
                            MainActivity.class);
                    startActivity(intent);
                    finish();
                } else {
                    // Error in login. Get the error message
                    String errorMsg = jObj.getString("error_msg");
                    Toast.makeText(getApplicationContext(),
                            errorMsg, Toast.LENGTH_LONG).show();
                }
            } catch (JSONException e) {
                // JSON error
                e.printStackTrace();
            }

        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e(TAG, "Login Error: " + error.getMessage());
            Toast.makeText(getApplicationContext(),
                    error.getMessage(), Toast.LENGTH_LONG).show();
            hideDialog();
        }
    }) {

        @Override
        protected Map<String, String> getParams() {
            // Posting parameters to login url
            Map<String, String> params = new HashMap<String, String>();
            params.put("tag", "login");
            params.put("email", email);
            params.put("password", password);

            return params;
        }

    };

    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}

private void showDialog() {
    if (!pDialog.isShowing())
        pDialog.show();
}

private void hideDialog() {
    if (pDialog.isShowing())
        pDialog.dismiss();
}}

The SQLite handler:

public class SQLiteHandler extends SQLiteOpenHelper {

private static final String TAG = SQLiteHandler.class.getSimpleName();

// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;

// Database Name
private static final String DATABASE_NAME = "android_api";

// Login table name
private static final String TABLE_LOGIN = "login";

// Login Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_EMAIL = "email";
private static final String KEY_UID = "uid";
private static final String KEY_CREATED_AT = "created_at";

public SQLiteHandler(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
    String CREATE_LOGIN_TABLE = "CREATE TABLE " + TABLE_LOGIN + "("
            + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
            + KEY_EMAIL + " TEXT UNIQUE," + KEY_UID + " TEXT,"
            + KEY_CREATED_AT + " TEXT" + ")";
    db.execSQL(CREATE_LOGIN_TABLE);

    Log.d(TAG, "Database tables created");
}

// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // Drop older table if existed
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_LOGIN);

    // Create tables again
    onCreate(db);
}

/**
 * Storing user details in database
 * */
public void addUser(String name, String email, String uid, String created_at) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(KEY_NAME, name); // Name
    values.put(KEY_EMAIL, email); // Email
    values.put(KEY_UID, uid); // Email
    values.put(KEY_CREATED_AT, created_at); // Created At

    // Inserting Row
    long id = db.insert(TABLE_LOGIN, null, values);
    db.close(); // Closing database connection

    Log.d(TAG, "New user inserted into sqlite: " + id);
}

/**
 * Getting user data from database
 * */
public HashMap<String, String> getUserDetails() {
    HashMap<String, String> user = new HashMap<String, String>();
    String selectQuery = "SELECT  * FROM " + TABLE_LOGIN;

    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);
    // Move to first row
    cursor.moveToFirst();
    if (cursor.getCount() > 0) {
        user.put("name", cursor.getString(1));
        user.put("email", cursor.getString(2));
        user.put("uid", cursor.getString(3));
        user.put("created_at", cursor.getString(4));
    }
    cursor.close();
    db.close();
    // return user
    Log.d(TAG, "Fetching user from Sqlite: " + user.toString());

    return user;
}

/**
 * Getting user login status return true if rows are there in table
 * */
public int getRowCount() {
    String countQuery = "SELECT  * FROM " + TABLE_LOGIN;
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(countQuery, null);
    int rowCount = cursor.getCount();
    db.close();
    cursor.close();

    // return row count
    return rowCount;
}

/**
 * Re crate database Delete all tables and create them again
 * */
public void deleteUsers() {
    SQLiteDatabase db = this.getWritableDatabase();
    // Delete All Rows
    db.delete(TABLE_LOGIN, null, null);
    db.close();

    Log.d(TAG, "Deleted all user info from sqlite");
}}

The settings Activity:

public class SettingsActivity extends ActionBarActivity implements View.OnClickListener {

CheckBox notificationsCheckbox;
private SeekBar volumeSeekbar = null;
private AudioManager audioManager = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setVolumeControlStream(AudioManager.STREAM_MUSIC);
    setContentView(R.layout.activity_settings);      
    volumeSeekbar = (SeekBar) findViewById(R.id.seekBar);
    Button accountSettingsButton = (Button) findViewById(R.id.accSettingsBtn);

    accountSettingsButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startActivity(new Intent (SettingsActivity.this, AccountSettingsActivity.class));
        }
    });

    Button tagSettingsButton = (Button) findViewById(R.id.tagSettingsbtn);

    tagSettingsButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startActivity(new Intent (SettingsActivity.this, TagsSettingsActivity.class));
        }
    });

    Button bluetoothSettingsButton = (Button) findViewById(R.id.bluetoothBtn);

    bluetoothSettingsButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startActivity(new Intent (SettingsActivity.this, DeviceScanActivity.class));
        }
    });



    volumeSeekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener(){

        public void onStopTrackingTouch(SeekBar seekBar) {
            // TODO Auto-generated method stub
            loadSavedSlider();
        }
        public void onStartTrackingTouch(SeekBar seekBar) {
            // TODO Auto-generated method stub

        }
        public void onProgressChanged(SeekBar seekBar, int progress,boolean fromUser) {
            // TODO Auto-generated method stub
            saveSlidePreferences();



        }
    });
    seekbarVolume();
    notificationsCheckbox = (CheckBox) findViewById(R.id.notifCheckbox);
    notificationsCheckbox.setOnClickListener(this);
    loadSavedCheckbox();
}

private void loadSavedCheckbox() {

SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
boolean checkBoxValue = sharedPreferences.getBoolean("CheckBox_Value", false);



    if (checkBoxValue) {
    notificationsCheckbox.setChecked(true);

    } else {
    notificationsCheckbox.setChecked(false);

    }} private void loadSavedSlider() {
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

    int mProgress = sharedPreferences.getInt("mMySeekBarProgress", 0);
    volumeSeekbar.setProgress(mProgress);
}
private void savePreferences(String key, boolean value) {
 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
  SharedPreferences.Editor editor = sharedPreferences.edit();
   editor.putBoolean(key, value);

   editor.commit();

  }

private void seekbarVolume() {
    try {
        volumeSeekbar = (SeekBar) findViewById(R.id.seekBar);
        audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        volumeSeekbar.setMax(audioManager
                .getStreamMaxVolume(AudioManager.STREAM_MUSIC));
        volumeSeekbar.setProgress(audioManager
                .getStreamVolume(AudioManager.STREAM_MUSIC));


        volumeSeekbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
            @Override
            public void onStopTrackingTouch(SeekBar arg0) {
            }

            @Override
            public void onStartTrackingTouch(SeekBar arg0) {
            }

            @Override
            public void onProgressChanged(SeekBar arg0, int progress, boolean arg2) {
                audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
                        progress, 0);
            }
        });
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
}
private void saveSlidePreferences() {
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    int mProgress = volumeSeekbar.getProgress();
    editor.putInt("mMySeekBarProgress", mProgress).commit();

    editor.commit();} @Override public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_settings, menu);
    return true;
}
public void sendNotification(View view) {

    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
    builder.setAutoCancel(true);
    builder.setContentTitle("Notifications Activaded");
    builder.setContentText("You can now receive notifications");
    builder.setSmallIcon(R.drawable.ic_action_new_event);

    Notification notification = builder.build();
    NotificationManager manager = (NotificationManager)this.getSystemService(NOTIFICATION_SERVICE);
    manager.notify(8, notification);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }


    return super.onOptionsItemSelected(item);
}
public void onClick(View v) {
savePreferences("CheckBox_Value", notificationsCheckbox.isChecked());
  }

}

in the settings menu, you only have a slider and a checkbox that can be changed. For now I' like to know how you can save the changes of these two only to be saved for the account that the user is logged in to.

My programming knowledge of android studio is somewhat low, and I cannot explain much about the SQLite database, as it was created by another teammate.

Aucun commentaire:

Enregistrer un commentaire