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>
Related
I want to create a login screen in android using Room/SQLLite.
Once my login activity is launched, a user object will be inserted in the database.
When pressing on the login button, I want to look for the user by the username I filled in.
Then I will check if the password that I gave in, is the correct password.
Based on that I will go to another activity or I will show an error message.
But this is going wrong, the next code is always returning NULL, so I will always end up showing the error message.
UserWithWorkorders userWithWorkorders = ie4ViewModel.getUserWithWorkorders(username.getText().toString()).getValue();
Here is the query in the UserDao. As you can see it returns LiveDate.
#Query("SELECT * FROM User WHERE username =:username")
LiveData<UserWithWorkorders> getUserWithWorkorders(String username);
Here is the onCreate() of my Login activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
IE4ViewModel ie4ViewModel = new ViewModelProvider(this).get(IE4ViewModel.class);
User user = new User("John", "Doe", "john", "doe");
ie4ViewModel.insertUser(user);
final Button loginButton = findViewById(R.id.loginButton);
final EditText username = findViewById(R.id.username);
final EditText password = findViewById(R.id.password);
final TextView errorMessage = findViewById(R.id.errorMessage);
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
UserWithWorkorders userWithWorkorders = ie4ViewModel.getUserWithWorkorders(username.getText().toString()).getValue();
if (userWithWorkorders != null) {
if(userWithWorkorders.user.getPassword().equals(password.getText().toString())){
Intent i = new Intent(LoginActivity.this, WorkordersActivity.class);
i.putExtra("userObject", userWithWorkorders);
startActivity(i);
}
else {
errorMessage.setVisibility(View.VISIBLE);
}
}
else {
errorMessage.setVisibility(View.VISIBLE);
}
}
});
ie4ViewModel.getUsersWithWorkorders().observe(this, new Observer<List<UserWithWorkorders>>() {
#Override
public void onChanged(List<UserWithWorkorders> usersWithWorkorders) {
if (usersWithWorkorders != null && usersWithWorkorders.size() > 0) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
}
});
}
}
});
}
What am I doing wrong? If there is any other code, you'd like to see, please let me know.
Or in other words: how do I retrieve an object in my android activity from a SQLLite database using Room if the Dao query is returning a LiveData object?
For this line of code, you dont need to make it return observable.
UserWithWorkorders userWithWorkorders = ie4ViewModel.getUserWithWorkorders(username.getText().toString()).getValue();
simply declare a method in your viewmodel like that.
public UserWithWorkorders getUserWithWorkorders(String value){
//get result from DAO.
}
Also make your DAO method return UserWithWorkorders
Now call this method in your activity as you are already doing it.
UserWithWorkorders userWithWorkorders = ie4ViewModel.getUserWithWorkorders(username.getText().toString()).getValue();
Be fully sure that your database has some data to return.
public void doSomething(View view) {
String url, link_url, pro;
url = textIn.getText().toString();
pro = spin.getSelectedItem().toString();
c1 = new ConnectInternetClass(this);
if (!url.isEmpty()) {
if (url.contains(".") && !(url.contains(" "))) {
if (url.split("\\.").length > 1) {
if (checkConnection()) {
link_url = pro+url;
c1.execute(link_url);
} else {
Toast.makeText(this, "check your internet connection", Toast.LENGTH_SHORT).show();
myText.setText("No Internet Connection");
}
} else {
myText.setText("Unknown domain");
}
} else {
myText.setText("Invalid URL");
}
} else {
myText.setText("URL can\'t empty");
}
}
I have that code to show a web page source. I want to show the result in another activity, but I don't know how. I use the create object from the first activity, but it's not method
public class ShowActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show);
MainActivity ma = new MainActivity();
}
Passing data from a activity , linkUrl is your variable which data you want to pass :
Intent intent = new Intent (YourActivity.this, ShowActivity.class) ;
intent.putExtra("KEY_LINK" , linkUrl);
startActivity(intent);
Receiving data from ShowActivity , Access the data by the key in onCreate():
String url = getIntent().getStringExtra("KEY_LINK");
Link : How do I pass data between Activities in Android application?
Link : https://developer.android.com/training/basics/firstapp/starting-activity.html
Why you use this kind of things. If you want to load a web page in an activity use webview for it. no need two activities to do that. Another way you can create a class which has your doSomething method (it should be public static) and call it from an activity by using that's class object. When you coding don't create unnecessary activities.
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.
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!
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.