Here is my code I am getting Error: error: not an enclosing class: MainActivity. Please help me what is the issue in my code.
public class MyFirebaseMessagingSerivce extends FirebaseMessagingService {
#Override
public void onNewToken(String s) {
super.onNewToken(s);
Log.e("NEW_TOKEN", s);
}
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
}
public void onCreate() {
super.onCreate();
FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener( MainActivity.this, new OnSuccessListener<InstanceIdResult>() {
#Override
public void onSuccess(InstanceIdResult instanceIdResult)
{
String updatedToken = instanceIdResult.getToken();
Log.e("Updated Token",updatedToken);
}
});
}
}
Can we use this one in FirebaseMessagingService?
No the FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener() method is used to get token inside activity
The onNewToken() method is used to get token inside FirebaseMessagingService
For more information check this answer of Frank van Puffelen how onNewToken and FirebaseInstanceId.getInstance().getInstanceId() will work
Also check this for FirebaseMessagingService
SAMPLE CODE
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener( MainActivity.this, new OnSuccessListener<InstanceIdResult>() {
#Override
public void onSuccess(InstanceIdResult instanceIdResult)
{
String updatedToken = instanceIdResult.getToken();
Log.e("Updated Token",updatedToken);
}
});
}
}
Related
I am learning MVP design for the Android , I am new to it so need your valuable time . I went to the basics of the MVP how it work , Now i got stuck so need your help , I have to post the data to the server , when i hard code the value in presenter then i get the response correct but i need the data that is in the LoginActivity view when user press then that value should pass to the presenter and presenter pass that value to the Retrofit and bring back the result . Here is my try :
My LoginActvity:
public class LoginActivity extends BaseActivity implements LoginView {
#BindView(R.id.company_name)
protected EditText companyName_et;
#BindView(R.id.email)
protected EditText email_et;
#BindView(R.id.password)
protected EditText password_et;
#BindView(R.id.submit)
protected Button submit_btn;
#Inject
LoginPresenter loginPresenter;
#Override
protected int getContentView() {
return R.layout.login_activity;
}
#Override
protected void onViewReady(Bundle savedInstanceState, Intent intent) {
super.onViewReady(savedInstanceState, intent);
submit_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String company=companyName_et.getText().toString();
String username=email_et.getText().toString();
String password=password_et.getText().toString();
/*
I have to put the above String data
to my model class then i have to post the data to the server
*/
loginPresenter.passLoginDataToServer();
}
});
}
#Override
public void onError(String s) {
Toast.makeText(this, s, Toast.LENGTH_SHORT).show();
}
#Override
public void onSuccess(String s) {
}
#Override
public void onResponse(Login login) {
Log.e("-----",""+login.getUserId());
}
#Override
protected void resolveDaggerDependency() {
DaggerLoginComponent.builder().applicationComponent(getApplicationComponent()).loginModule(new LoginModule(this)).build().inject(this);
}
}
Here is Login Presenter :
public class LoginPresenter extends BasePresenter<LoginView> implements Observer<Login>{
#Inject
CreateApiService createApiService;
#Inject
public LoginPresenter(){};
public void passLoginDataToServer(){
/*
when i hard code the data , i get the successful response.Like :
String user="raj";
String check="true";
Map<String,String> headers=new HashMap();
headers,put("xyz","pqr");
Login loginObject = new Login("xyzs", "pqr","Qtch","mvp");
*/
/*
But I need the data here from my LoginActivity ? Dunno how to pass the data from LoginActivity to presenter
*/
Observable<Login> loginObservable=createApiService.loginUser(user, check, headers, loginObject);
subscribeToLogin(loginObservable,this);
}
#Override
public void onSubscribe(Disposable d) {
}
#Override
public void onNext(Login login) {
getmView().onResponse(login);
}
#Override
public void onError(Throwable e) {
getmView().onError("Error "+e);
Log.e("---",""+e);
}
#Override
public void onComplete() {
getmView().onSuccess("Successfully Loaded");
}
}
Here is My Interface :
public interface LoginView extends BaseView {
void onError(String s);
void onSuccess(String s);
void onResponse(Login login);
}
Could you add the parameters to the method?
In your activity:
#Override public void onClick(View view) {
String company=companyName_et.getText().toString();
String username=email_et.getText().toString();
String password=password_et.getText().toString();
loginPresenter.passLoginDataToServer(compay, username, password);
}
In your presenter:
public void passLoginDataToServer(String company, String username, String password){
// Now create your request from the dynamic parameters
Observable<Login> loginObservable=createApiService.loginUser(username, check, headers, loginObject);
subscribeToLogin(loginObservable,this);
}
I am trying to refactor my Android Firebase project, to move code for inserting data into database and for displaying UI from MainActivity to MessageDao class.
This is my MessageDao class:
public class MessageDao {
private FirebaseDatabase mFirebaseDatabase = FirebaseDatabase.getInstance();
private DatabaseReference mMessagesDatabaseRef = mFirebaseDatabase.getReference().child("messages");;
private List<Message> messages = new ArrayList<>();
private MessageAdapter mMessageAdapter = new MessageAdapter(messages);
public void write(Message message){
mMessagesDatabaseRef.push().setValue(message);
}
public void updateList(){
mMessagesDatabaseRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
messages.add(dataSnapshot.getValue(Message.class));
mMessageAdapter.notifyDataSetChanged();
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
Message msg = dataSnapshot.getValue(Message.class);
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
And MainActivity class:
public class MainActivity extends AppCompatActivity {
.....
private MessageDao mesageDao;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSendButton = (Button) findViewById(R.id.sendButton);
mesageDao = new MessageDao();
.....
// Send button sends a message and clears the EditText
mSendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Message message = new Message(mMessageEditText.getText().toString(), mUsername, null);
mesageDao.write(message);
mMessageEditText.setText("");
}
});
mesageDao.updateList();
}
}
When I click mSendButton button, it writes into database, but it's not displaying in my UI. When childEventListener is in MainActivity it all works fine, but when I move it to MessageDao and call it in MainActivity onCreate method with mesageDao.updateList() it's not working. So, what am I missing here ?
To solve this, your MessageDao class in which you have moved the code, needs to extends Application like this:
public class MessageDao extends Application {...}
Hope it helps.
I am trying to use Digits from Twitter.
The AuthCallBack is not fired when used from activity and the recent document saying to use the AuthCallBack from the Application class.
Now I have the AuthCallBack working correctly and onSuccess I need to call a method from my MainActivity. How do I achieve it from the Application class. Kindly help. I have given the code below.
public class MyApplication extends Application {
private AuthCallback authCallback;
#Override
public void onCreate() {
super.onCreate();
authCallback = new AuthCallback() {
#Override
public void success(DigitsSession session, String phoneNumber) {
//call myFunction() from MainActivity here
}
#Override
public void failure(DigitsException exception) {
}
};
}
public AuthCallback getAuthCallback(){
return authCallback;
}
}
You can use BroadcastManager to archive the same.
Below is sample code you can use
From Application:
#Override
public void success(DigitsSession session, String phoneNumber) {
Intent intent = new Intent(Constants.FILTER_LOGIN_SUCCESS);
intent.putExtra(Constants.EXTRA_PHONE_NUMBER, phoneNumber);
LocalBroadcastManager.getInstance(mInstance).sendBroadcast(intent);
}
Activity Class :
#Override
protected void onResume() {
super.onResume();
LocalBroadcastManager.getInstance(SignUpActivity.this).registerReceiver(broadcastReceiver,
new IntentFilter(Constants.FILTER_LOGIN_SUCCESS));
}
#Override
protected void onDestroy() {
super.onDestroy();
LocalBroadcastManager.getInstance(SignUpActivity.this).unregisterReceiver(broadcastReceiver);
}
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String phoneNumber = intent.getStringExtra(Constants.EXTRA_PHONE_NUMBER);
navigateToAnotherActivty();
}
};
Using interface you can achieve this
Write an interface something like this
public interface onSuccessListner {
void onSuccess(DigitsSession session,String phoneNumber);
}
Implement this interface in your Main Activity
public class MainActivity extends AppCompatActivity implements onSuccessListner{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public void onSuccess(DigitsSession session,String phoneNumber) {
//write your method calling or operations here
}
}
In your application class implement Application.ActivityLifecycleCallbacks to check main activity is created or not,If main activity created apply context of main activity to the listner
In on create inside your callback method call the success method of the MainActivity
public class MyApplctn extends Application implements Application.ActivityLifecycleCallbacks {
onSuccessListner onSuccessListner;
#Override
public void onCreate() {
super.onCreate();
registerActivityLifecycleCallbacks(this);
authCallback = new AuthCallback() {
#Override
public void success(DigitsSession session, String phoneNumber) {
//call myFunction() from MainActivity here
if(onSuccessListner!=null){
onSuccessListner.onSuccess(session,phoneNumber);
}
}
#Override
public void failure(DigitsException exception) {
}
};
}
#Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
if (activity instanceof MainActivity) {
onSuccessListner= (com.mmadapps.myapplication.onSuccessListner) activity;
}
}
#Override
public void onActivityStarted(Activity activity) {
}
#Override
public void onActivityResumed(Activity activity) {
}
#Override
public void onActivityPaused(Activity activity) {
}
#Override
public void onActivityStopped(Activity activity) {
}
#Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}
#Override
public void onActivityDestroyed(Activity activity) {
}
}
Hope this will help you
I am trying to play around with Firebase, I have this piece of code but the user is not getting created.
I've enabled email and password auth on Firebase. The Firebase url is correct.
public class RegisterActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
Firebase.setAndroidContext(this);
Button BCreate;
BCreate=(Button)findViewById(R.id.Createbutton);
BCreate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.e("URL", "Before firebase url");
go();
}
});
}
private void go() {
final Firebase ref=new Firebase("https://testingbasee.firebaseio.com");
Log.e("GOOOOOO!", "gooooooo!");
ref.createUser("aa#bb.com", "12345", new Firebase.ResultHandler() {
#Override
public void onSuccess() {
Log.e("GOOOOOO!","gooooooo!");
}
#Override
public void onError(FirebaseError firebaseError) {
Log.e("NOPOOOOOOOO!","noooo!!1!");
}
});
}
}
I've had an interview and I was given the following code, so that the UserAPI is a utility class for retrieving data from the network.
Assume it operate with its own threading mechanism with no respect to the caller thread.
And I had to find what's wrong with the code:
public class NetworkTestActvitiy extends Activity {
private TextView userNameTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chegg_test_layout);
userNameTextView = (TextView)findViewById(R.id.userName);
}
#Override
protected void onStart() {
super.onStart();
loadUserName();
}
private void loadUserName() {
UserAPI.getInstance().getUserName(new NetworkListener() {
#Override
public void onError(ErrorMessage error) {
Logger.e("Failed to get user use: " + error.getMessage());
}
#Override
public void onSuccess(String userName) {
userNameTextView.setText(userName);
}
});
}
}
My guess would be that the call to userNameTextView.setText can not be from UI thread and has to be marshalled.