How can i create a session in Android? - android

I'm building an app with a Login area. I'm using PHP to insert the Values from my Application into my database, I'm using parameters.
I would like to get the information from the user, when he logs in, so, i already got the the ID from the user, and I would like to put the ID inside a variable, and create a session to call everytime that the user visits his profile.
The user will do the Login inside the Mainactivity
Mainactivity
public void login(View view){
String username = usernameField.getText().toString();
String password = passwordField.getText().toString();
new SigninActivity(this,status,role,0).execute(username,password);
}
class Session {
public String username = "I WILL PUT THE USERNAME OR ID HERE";
}
class App extends Application {
Session session = new Session();
public String getUsername() {
return session.username;
}
public void setUsername(String username) {
session.username = username;
}
}
And now, I'm trying to call the string username in other activity named test.
test
public class test extends Activity{
private TextView get;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.teste);
get = (TextView)findViewById(R.id.get);
App app = (App) getApplication();
String username = app.getUsername();
if (username.equals("")) {
// the user is not logged in, do something
}
}
}
I inserted that in android manifest
<activity
android:name=".test"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
But when i open the test activity i receive multiple errors. What am i doing wrong?

[Duplicated Question] How to maintain session in android?
you can use SharedPreferences or you can store it in the database.

Related

Android: Why can't I move to another Acivity by using “Intent”?

I can't move to the LoginPageActivity.I think the problem is in my 'Intent' statement. Maybe, I gave wrong 'context'. Everything looks good. But application is crushing. I couldn't find the problem. Can you help me? What shall I give as a context in the MainActivity and ELSE statement?
I think the problem is Intent in Helper class.
I have an IF condition like this:
public void createNewUser(final Context context, String email, String password){
firebaseAuth = FirebaseAuth.getInstance();
firebaseAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener((Activity) context, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful()) {
ShortCut.displayMessageToast(context, "invalid info");
}else {
ShortCut.displayMessageToast(context, "Account created");
Intent loginIntent = new Intent(context, LoginPageActivity.class);
context.startActivity(loginIntent);
}
}
});
}
When I am trying to create a new account my else condition is works. But, why can't I move to LoginPageActivity?
And, I call from here in MainActivity:
#OnClick(R.id.createBtn)
void createButonClicked(){
String email = mEmail.getText().toString();
String password = mPassword.getText().toString();
String clientName = mClientName.getText().toString();
String clientSurname = mClientSurname.getText().toString();
String clientCity = mClientCity.getText().toString();
String clientPhone = mClientPhone.getText().toString();
if (TextUtils.isEmpty(email)
|| TextUtils.isEmpty(password)
|| TextUtils.isEmpty(clientName)
|| TextUtils.isEmpty(clientSurname)
|| TextUtils.isEmpty(clientCity)
|| TextUtils.isEmpty(clientPhone))
{
ShortCut.displayMessageToast(this, "You should fill empty fields!");
}else {
firebaseApplication = new FirebaseApplication();
firebaseApplication.createNewUser(this, email, password);
ShortCut.displayMessageToast(this, "just for a debug");
}
}
When you call the method "createNewUser()", you are inside of an onClickListener. When you pass in 'this' as your context, you are passing in the context of your listener. Instead, when calling createNewUser, use 'MainActivity.this' as your Context, so then your app knows that the context is the whole activity and not just the listener. That means the code should be
}else {
firebaseApplication = new FirebaseApplication();
firebaseApplication.createNewUser(MainActivity.this, email, password);
ShortCut.displayMessageToast(this, "just for a debug");
}
I found my fault(s):
Firstly, I need a code in MainActivity's ELSE statement like this:
((FirebaseApplication)getApplication()).createNewUser(MainActivity.this, email, password);
Secondly, I need change the content of AndroidManifest.xml LoginPageActivity must be declared in:
<application>
...
...-->Another activity...
...
<activity android:name=".LoginPageActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

Intent is not started through scanner when using emdk profile manager

I followed this tutorial to scan a bar code and display in the text view everything works fine but the scanned bar code is not displayed in the text view.As from the below you can see the handledata is never called when i scan the code through TC70 zebra device.As i expected the below code to create a new intent and call the handledata from new Intent method.
AndroidManifest.xml
<uses-permission android:name="com.symbol.emdk.permission.EMDK"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:launchMode="singleTask"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<uses-library android:name="com.symbol.emdk"/>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="com.lisec.emdktest.intentsample.RECVR"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>
</application>
MainActivity.java
package com.lisec.emdktest.intentsample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import android.widget.TextView;
import com.symbol.emdk.EMDKManager;
import com.symbol.emdk.EMDKResults;
import com.symbol.emdk.ProfileManager;
public class MainActivity extends AppCompatActivity implements EMDKManager.EMDKListener {
//Assign the profile name used in EMDKConfig.xml
private String profileName = "NewDataCapture";
//Declare a variable to store ProfileManager object
private ProfileManager mProfileManager = null;
//Declare a variable to store EMDKManager object
private EMDKManager emdkManager = null;
private TextView textViewBarcode = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//The EMDKManager object will be created and returned in the callback.
EMDKResults results = EMDKManager.getEMDKManager(getApplicationContext(), this);
//Check the return status of getEMDKManager
if(results.statusCode == EMDKResults.STATUS_CODE.FAILURE)
{
//Failed to create EMDKManager object
}
textViewBarcode = (TextView) findViewById(R.id.textViewBarcode);
Intent i = getIntent();
handleDecodeData(i);
}
//This function is responsible for getting
the data from the
intent
private void handleDecodeData(Intent i)
{
//Check the intent action is for us
if (i.getAction().contentEquals
("com.lisec.emdktest.intentsample.RECVR") ) {
String source =
i.getStringExtra
("com.motorolasolutions.emdk.datawedge.source");
//Check if the data has come from the Barcode scanner
if(source.equalsIgnoreCase("scanner"))
{
//Get the data from the intent
String data =
i.getStringExtra
("com.motorolasolutions.emdk.datawedge.data_string");
//Check that we have received data
if(data != null && data.length() > 0)
{
textViewBarcode.setText("Data = " + data);
}
}
}
}
#Override
public void onNewIntent(Intent i) {
handleDecodeData(i);
}
#Override
public void onOpened(EMDKManager emdkManager) {
this.emdkManager = emdkManager;
//Get the ProfileManager object to process the profiles
mProfileManager = (ProfileManager)
emdkManager.getInstance
(EMDKManager.FEATURE_TYPE.PROFILE);
if(mProfileManager != null)
{
try{
String[] modifyData = new String[1];
//Call processPrfoile with profile name
and SET flag to create
the profile.
The modifyData can be null.
EMDKResults results = mProfileManager.
processProfile(profileName,
ProfileManager.PROFILE_FLAG.SET, modifyData);
if(results.statusCode == EMDKResults.STATUS_CODE.FAILURE)
{
//Failed to set profile
}
}catch (Exception ex){
// Handle any exception
}
}
}
#Override
public void onClosed() {
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
//Clean up the objects created by EMDK manager
emdkManager.release();
}
}
I think you are confusing the different ways to retrieve scanned data. Intents are only sent from the DataWedge service (http://techdocs.zebra.com/datawedge/6-0/guide/about/) but you are also initialising the EMDK library (http://techdocs.zebra.com/emdk-for-android/6-0/guide/gettingstarted/). EMDK returns its data via callback.
If you choose the DataWedge route, I have an application which listens for DataWedge intents that might help: https://github.com/darryncampbell/DataWedge-API-Exerciser
If you choose the EMDK route, there are samples on Zebra's own site: http://techdocs.zebra.com/emdk-for-android/6-0/samples/barcode/
If you use the EMDK in your application it will automatically take priority over DataWedge so your application would never receive data via intents unless you delete the EMDK code.

Use of Shared Preferences and Intent - Setup and Settings application

I am currently developing an application that on the first time the application opens, shows the setup interface and the succeeding times the application is opened, it shows the settings interface. The way I achieved this is that once my application opens, it checks if the shared preferences is null. If the shared preferences is null, it means it was the first time that the application is opened and it will set a value in the shared preferences. Then the next time that the application is opened, when the shared preferences is checked, it isn't null anymore and will go to the settings interface. The problem is, When I run it the first time, it only shows a white screen with no status bar or anything. Below are code snippets of my application
private void saveSharedPref()
{
SharedPreferences preferences = getSharedPreferences(SHARED_PREFERENCES_FILE, 0);
SharedPreferences.Editor editor = preferences.edit();
//Save values from Edit Text Controls
editor.putString("firstTime", "1234");
editor.commit();
}
private void loadSharedPreferences()
{
SharedPreferences preferences = getSharedPreferences(SHARED_PREFERENCES_FILE, 0);
//Null check in case file does not exist
if(preferences != null) {
String checkFirst = preferences.getString("firstTime", "");
if (!checkFirst.equalsIgnoreCase("1234"))
{
Intent sendToSetup = new Intent (this, Setup.class);
startActivity(sendToSetup);
}
else
{
saveSharedPref();
}
}
}
I call loadSharedPreferences() in my onCreateMethod
public class Setup extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.setup_pg1);
}
This is where the app gets redirected when the user open it for the first time.
Any help would be greatly appreciated. Thanks in advance!
P.S. sorry if my english isnt good
EDIT:
here's the androidmanifest
<?xml version="1.0" encoding="utf-8"?>
<application
android:allowBackup="true"
android:icon="#drawable/icon1"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".SafeSwipe"
android:label="SafeSwipe-UI v.2"
android:theme="#style/AppTheme.NoActionBar">
</activity>
<activity
android:name=".MainActivity"
android:label=""
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".Setup" />
</application>
setup_pg1
<TextView
android:text="Setup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="102dp"
android:id="#+id/textView" />
<Button
android:text="Continue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView"
android:layout_alignRight="#+id/textView"
android:layout_alignEnd="#+id/textView"
android:layout_marginTop="71dp"
android:id="#+id/button7" />
setup file
public class Setup extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.setup_pg1);
}
}
First, if(preferences != null) will never be true because you'll always get a non-null value from getSharedPreferences()
I call loadSharedPreferences() in my onCreate Method
No you don't... here's your code
public class Setup extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.setup_pg1);
}
}
Try again. But use a boolean value rather than some random string.
public class MainActivity extends AppCompatActivity {
public static final String PREFS_NAME = "MyPrefsFile";
public static final String KEY_FIRST_TIME = "firstTime";
#Override
protected void onCreate(Bundle b){
super.onCreate(b);
setContentView(R.layout.activity_main);
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
boolean firstTime = prefs.getBoolean(KEY_FIRST_TIME, false);
if (!firstTime) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean(KEY_FIRST_TIME, true);
editor.commit();
} else {
Intent sendToSetup = new Intent (this, Setup.class);
startActivity(sendToSetup);
finish();
}
}
}
Try this:
Instead of checking preferences != null try this..
if (preferences.getString("firstTime","").equals("1234"))
{
Intent sendToSetup = new Intent (this, Setup.class);
startActivity(sendToSetup);
}
else
saveSharedPref();
Your if(preferences != null)is not working here, cause preferences is not null. It's just an empty preference. You can try out the below code:
private void loadSharedPreferences()
{
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String checkFirst = preferences.getString("firstTime", "");
if(!checkFirst.equals("")) {
Intent sendToSetup = new Intent (this, Setup.class);
startActivity(sendToSetup);
}
else
{
saveSharedPref();
}
}
saveSharedPref() method:
private void saveSharedPref()
{
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
//Save values from Edit Text Controls
preferences.edit().putString("firstTime", "1234").apply();
}
Call loadSharedPreferences() in onCreate() of Setup Activity:
Hope this helps.
I don't see any crucial problem in this code. But I have some assumption that you have already called the saveSharedPref() method while testing your program and value of firstTime is already exist. Because SharedPreferences are not deleted after recompiling the program this statement:
if (!checkFirst.equalsIgnoreCase("1234"))
gives false.
The best way to check this is to set a breakpoint in loadSharedPreferences() method and verify it.
If it is so try to remove sharedPreferences (see the answer https://stackoverflow.com/a/3687333/7677939 )
or simply give another file name in SHARED_PREFERENCES_FILE variable.
Also it can be a problem in place where you call loadSharedPreferences(), but I cannot see it in your source.
Update:
Notice, that you should not call loadSharedPreferences() in Setup activity, you should call it in your Main activity!

SharedPreferencesBackupHelper auto restore doesn't work

I'm trying to use SharedPreferencesBackupHelper to save my SharedPreferences value to cloud.
AndroidManifest.xml
<application
android:allowBackup="true"
android:backupAgent=".DataBackupAgent"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<meta-data android:name="com.google.android.backup.api_key" android:value="AEdPqrEAAAAIXMH86OqosQlXYuS0QbfyOaZT8fUadY1QUDzo2w" />
<activity
android:name=".MainActivity"
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>
DataBackupAgent.java:
public class DataBackupAgent extends BackupAgentHelper {
public static final String PREFS = "data_prefs";
public static final String PREFS_BACKUP_KEY = "myprefs";
#Override
public void onCreate() {
SharedPreferencesBackupHelper helper = new SharedPreferencesBackupHelper(this, PREFS);
addHelper(PREFS_BACKUP_KEY, helper);
}
}
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
backupManager = new BackupManager(this);
prefs = getSharedPreferences(DataBackupAgent.PREFS, Context.MODE_PRIVATE);
edit = prefs.edit();
text = (EditText)findViewById(R.id.editText);
String value = prefs.getString(DataBackupAgent.PREFS_BACKUP_KEY,"");
text.setText(value);
Button btnBackup = (Button)findViewById(R.id.button);
btnBackup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
edit.putString(DataBackupAgent.PREFS_BACKUP_KEY,text.getText().toString());
edit.commit();
backupManager.dataChanged();
}
});
}
My steps:
Write something at the EditText, click Backup button
Close app and open again. The saved value will be shown in EditText
Uninstall the app and reinstall again. The saved value is not shown in EditText at all.
Edit at 27/02/2015:
I added the following code to restore manually:
backupManager.requestRestore(new RestoreObserver() {
#Override
public void restoreFinished(int error) {
super.restoreFinished(error);
String value = prefs.getString(DataBackupAgent.PREFS_BACKUP_KEY,"");
text.setText(value);
}
#Override
public void restoreStarting(int numPackages) {
super.restoreStarting(numPackages);
}
#Override
public void onUpdate(int nowBeingRestored, String currentPackage) {
super.onUpdate(nowBeingRestored, currentPackage);
}
});
Unfortunately no callback functions are called.
This means back or auto restore doesn't work at all. Any idea? Thanks
My steps:
1. Write something at the EditText, click Backup button
2. Close app and open again. The saved value will be shown in EditText
3. Uninstall the app and reinstall again. The saved value is not shown in EditText at all.
To test your implementation there are others steps related to the use of bmgras we can see here.
Nevertheless I implemented this feature some days ago and following the steps in the documentation using a real device - Samsung SII - the automatic restore doesn't happen BUT using the emulator all was fine.
Logcat will show you all the operation output details.
IMO, the Android Data Backup feature is not reliable today. We can see some discussion about the implementation problems here and here.
Hope it helps!

Android starts correct activity from Eclipse - but not from the phone

When I launch my app from Eclipse to my phone, it launches the Launcher first and then my main activity. It successfully passes a variable to the main activity. I check that the username has been logged with a toast.
When I launch my app from my phone directly, it goes straight to the main activity; the main activity registers the variable as null.
I created a test app that performs EXACTLY the same function as the launcher in this one; their manifests are identical except for the activity names; and that test app functions correclty from the phone and when I install it from Eclipse.
this is a real brain-teaser.
Here is the code for the starter activity:
public class SecureAppStarter extends Activity {
TextView report;
WebView input;
Context thisContext = this;
String thisValue, url;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.starter);
initialize();
WebViewClient rclient = new WebViewClient(){
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url){
return false;
}
#Override
public void onLoadResource(WebView view, String url){
input.getSettings().setJavaScriptEnabled(true);
input.addJavascriptInterface(new CustomJavaScriptInterface(thisContext), "Android");
}
#Override
public void onPageFinished(WebView view, String url){
report.setText(""+thisValue);
if (thisValue!= null){
Intent passOn = new Intent("arbuckle.app.MainActivity");
passOn.putExtra("username", thisValue);
startActivity(passOn);
}
}
};
rclient.onPageFinished(input, url);
input.setWebViewClient(rclient);
input.loadUrl(url);
}
public class CustomJavaScriptInterface {
Context mContext;
CustomJavaScriptInterface(Context context) {
mContext = context;
}
public void getValue(String value){
thisValue = value;
}
}
private void initialize() {
report = (TextView) findViewById(R.id.tvViewName);
input = (WebView) findViewById(R.id.wbWebAuth);
url = "http://URL.of.data.com";
}
}
And here is the manifest:
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name="SecureAppStarter"
android:label="#string/app_name"
android:configChanges="keyboardHidden|orientation">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".ArbuckleAppActivity"
android:label="#string/app_name"
android:configChanges="keyboardHidden|orientation">
<intent-filter>
<action android:name="arbuckle.app.ArbuckleAppActivity" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
Well I figured it out.
I have been installing/uninstalling versions of the app for weeks where the main activity was the launcher. clearly that gets kept somewhere in Android cache and it was choosing the main activity to launch even though it wasn't the launcher anymore.
So I uninstalled the app completely; and reinstalled. Now it works.
Does anyone think I hacked at the problem instead of solving it? Should I expect further problems down the road?

Categories

Resources