Call activity from Application - android

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

Related

How to use "onClickListener" in MPV in android?

I use mvp architecture.
I have the setupViews () method in which the buttons and ... are defined
how i can use setOnclickListener for Button in "presenter" and call it in SetupViews in "activity".
I do not want to use it directly in "view",I want to tell the presenter that the click is done and the presenter will do the job.
My interface:
public interface HomeContract {
interface View extends BaseView {
void showNews(List<News> newsList);
void showError(String error);
}
interface Presenter extends BasePresenter<View> {
void getNewsList();
} }
presenter class :
public class HomePresenter implements HomeContract.Presenter {
private HomeContract.View view;
private NewsDataSourse newsDataSourse;
CompositeDisposable compositeDisposable = new CompositeDisposable();
public HomePresenter(NewsDataSourse newsDataSourse) {
this.newsDataSourse = newsDataSourse;
}
#Override
public void getNewsList() {
newsDataSourse.getNews().subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new SingleObserver<List<News>>() {
#Override
public void onSubscribe(Disposable d) {
compositeDisposable.add(d);
}
#Override
public void onSuccess(List<News> news) {
view.showNews(news);
}
#Override
public void onError(Throwable e) {
view.showError(e.toString());
}
});
}
#Override
public void attachView(HomeContract.View view) {
this.view = view;
getNewsList();
}
#Override
public void detachView() {
this.view = null;
if (compositeDisposable != null && compositeDisposable.size() > 0) {
compositeDisposable.clear();
}
}}
my view :
public class HomeActivity extends BaseActivity implements HomeContract.View {
private HomeContract.Presenter presenter;
private NewsRepository newsRepository = new NewsRepository();
private RecyclerView recyclerView;
private RecyclerAdapter recyclerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
presenter = new HomePresenter(newsRepository);
}
#Override
public void setupViews() {
Button btn_Ok = (Button) findViewById(R.id.btn_Ok);
recyclerView = (RecyclerView) findViewById(R.id.recycler);
recyclerView.setLayoutManager(new LinearLayoutManager(getViewContext(), LinearLayout.VERTICAL, false));
// btn_Ok.setOnClickListener();
}
#Override
public void showNews(List<News> newsList) {
setupViews();
recyclerView.setAdapter(new RecyclerAdapter(newsList, getViewContext()));
if (newsList.size() > 0) {
Toast.makeText(getViewContext(), "ok", Toast.LENGTH_SHORT).show();
Toast.makeText(getViewContext(), newsList.get(0).getName(), Toast.LENGTH_SHORT).show();
} else
Toast.makeText(getViewContext(), "not Ok", Toast.LENGTH_SHORT).show();
}
#Override
public void showError(String error) {
Toast.makeText(getViewContext(), error, Toast.LENGTH_SHORT).show();
}
#Override
public Context getViewContext() {
return getApplicationContext();
}
#Override
protected void onStart() {
super.onStart();
presenter.attachView(this);
}
#Override
protected void onStop() {
super.onStop();
presenter.detachView();
}
}
i want to use btn_Ok.setOnClickListener(presenter....); in view Or any better solution you need to do this
In your presenter interface type a method :
interface Presenter extends BasePresenter<View> {
void getNewsList();
void onButtonClicked();
}
And than in your HomePresenter class use it :
#Override
public void onButtonClicked(){
// continue logic here
}
If you don't override it the class will show an error

how to write a variable from a singleton in firebase

There is a program where I can change a variable using a singleton. Created 2 activites, where users can change this variable. How to write the variable that is being changed to the Firebase database. I tried to use the addValueEventListener (new ValueEventListener () method.
Where do I use the firebase methods? In the main class or in singleton? And how to write a variable?
main activity
public class MainActivity extends AppCompatActivity {
private BubbleWrap bubbleWrap;
private TextView txtintent;
final int REQUEST_CODE_661_1 = 1;
private int bbbbb;
private TextView txt;
private String bubul;
FirebaseDatabase database=FirebaseDatabase.getInstance();
final DatabaseReference AllFacebase =database.getReference("всего").child("йй");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txt=findViewById(R.id.textView);
bubbleWrap=BubbleWrap.getInstance();
setupAddMoreButton();
setupPopActivityButton();
setupCocActivityButton();
txtintent=(TextView)findViewById(R.id.txtintent);
AllFacebase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
bubul=String.valueOf(dataSnapshot.getValue());
txtintent.setText(bubul);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
protected void onResume() {
super.onResume();
updateUI();
}
private void setupAddMoreButton(){
Button btn=findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
bubbleWrap.addMoreBubbles();
updateUI();
}
});
}
private void setupPopActivityButton(){
Button btn=findViewById(R.id.button2);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
private void setupCocActivityButton(){
Button btn=findViewById(R.id.buttoncoc);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
private void updateUI(){
txtintent.setText(String.format(Locale.getDefault(),"%d",
bubbleWrap.getNumBubbles()));
}
}
second activity
activity, where I change the variable, I want to write to Firebase
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pop);
bubbleWrap=BubbleWrap.getInstance();
final TextView txt=findViewById(R.id.textView2);
setupPopButton();
updateUI();
Intent intent=new Intent();
intent.putExtra("bubles", bubbleWrap.getNumBubbles());
}
private void setupPopButton(){
Button btn=findViewById(R.id.cocbtb);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
bubbleWrap.popBubble();
updateUI();
}
});
}
private void updateUI(){
TextView txt=findViewById(R.id.textView2);
txt.setText(String.format(Locale.getDefault(),
"Bubbles left: %d",
bubbleWrap.getNumBubbles()));
}
}
Singleton
public class BubbleWrap {
private static final int ADD_MORE_BUBBLES = 10;
private int numBubbles;
private static BubbleWrap instance;
private BubbleWrap(){
}
public static BubbleWrap getInstance(){
if(instance==null){
instance=new BubbleWrap();
}
return instance;
}
public int getNumBubbles() {
return numBubbles;
}
public void addMoreBubbles(){
numBubbles+=ADD_MORE_BUBBLES;
}
public void popBubble() {
numBubbles--;
}
public void saveintent(){
}
}

Post Data To Server Using MVP Android

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);
}

AccountAuthenticatorActivity for AppCompat

I'm making an authenticator following the tutorial: http://blog.udinic.com/2013/04/24/write-your-own-android-authenticator/
The login Activity requires to extend AccountAuthenticatorActivity, the issue starts here: AccountAuthenticatorActivity extends the regular Activity and not AppCompatActivity.
Using the regular Activity in AppCompat results in a Activity without ActionBar. I want to use AccountAuthenticatorActivity AND having an ActionBar.
I think that is not the real solution. If you are doing an app with support libraries, mixing AppCompatActivities, Fragments &c with the standard ones is not a good idea.
I´ve created an AccountAuthenticatorAppCompatActivity extending AppCompatActivity and then copy/paste the code from API AccountAuthenticatorActivity and it seems to work properly.
public class AccountAuthenticatorAppCompatActivity extends AppCompatActivity {
private AccountAuthenticatorResponse mAccountAuthenticatorResponse = null;
private Bundle mResultBundle = null;
public final void setAccountAuthenticatorResult(Bundle result) {
mResultBundle = result;
}
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
mAccountAuthenticatorResponse =
getIntent().getParcelableExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE);
if (mAccountAuthenticatorResponse != null) {
mAccountAuthenticatorResponse.onRequestContinued();
}
}
public void finish() {
if (mAccountAuthenticatorResponse != null) {
// send the result bundle back if set, otherwise send an error.
if (mResultBundle != null) {
mAccountAuthenticatorResponse.onResult(mResultBundle);
} else {
mAccountAuthenticatorResponse.onError(AccountManager.ERROR_CODE_CANCELED,
"canceled");
}
mAccountAuthenticatorResponse = null;
}
super.finish();
}
}
Hope it helps to someone.
The key is AppCompatDelegate, my code is based on the AppCompatPreferenceActivity class generated by Android Studio:
#SuppressWarnings("unused")
public class AppCompatAuthActivity extends AccountAuthenticatorActivity {
private AppCompatDelegate mDelegate;
#Override
protected void onCreate(Bundle savedInstanceState) {
getDelegate().installViewFactory();
getDelegate().onCreate(savedInstanceState);
super.onCreate(savedInstanceState);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
getDelegate().onPostCreate(savedInstanceState);
}
public ActionBar getSupportActionBar() {
return getDelegate().getSupportActionBar();
}
public void setSupportActionBar(#Nullable Toolbar toolbar) {
getDelegate().setSupportActionBar(toolbar);
}
#Override
#NonNull
public MenuInflater getMenuInflater() {
return getDelegate().getMenuInflater();
}
#Override
public void setContentView(#LayoutRes int layoutResID) {
getDelegate().setContentView(layoutResID);
}
#Override
public void setContentView(View view) {
getDelegate().setContentView(view);
}
#Override
public void setContentView(View view, ViewGroup.LayoutParams params) {
getDelegate().setContentView(view, params);
}
#Override
public void addContentView(View view, ViewGroup.LayoutParams params) {
getDelegate().addContentView(view, params);
}
#Override
protected void onPostResume() {
super.onPostResume();
getDelegate().onPostResume();
}
#Override
protected void onTitleChanged(CharSequence title, int color) {
super.onTitleChanged(title, color);
getDelegate().setTitle(title);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
getDelegate().onConfigurationChanged(newConfig);
}
#Override
protected void onStop() {
super.onStop();
getDelegate().onStop();
}
#Override
protected void onDestroy() {
super.onDestroy();
getDelegate().onDestroy();
}
public void invalidateOptionsMenu() {
getDelegate().invalidateOptionsMenu();
}
private AppCompatDelegate getDelegate() {
if (mDelegate == null) {
mDelegate = AppCompatDelegate.create(this, null);
}
return mDelegate;
}
}
The AppCompatDelegate is the key to add ActionBar to ANY regular Activity (for example PreferenceActivity).
Don't forget your activity must extend AppCompatAuthActivity.

retrieving data from the network

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.

Categories

Resources