My MainAcivity hosts 2 fragments, login and register. I have a LiveData observer on LoginFragment that observes user login live data, after which if user is authenticated MainMenuActivity intent will start. On main menu there's logout button that would start MainActivity and load LoginFragment.
But here's the problem, the observer on LoginFragment triggered immediately after loading the fragment, which straight up start MainMenuActivity intent again.
My LoginFragment:
public class LoginFragment extends Fragment {
public static LoginFragment newInstance(){
return new LoginFragment();
}
private LoginViewModel mLoginViewModel;
private LiveData<UserModelJSONPlaceholder> mUserModelLiveData;
private static final String TAG = "FragLogin";
private Button mBtnLogin;
private EditText mTxtUsername, mTxtPass;
private TextView mTxtRegister;
private CheckBox mCheckBoxRemember;
private TextView mTxtInvalid;
private Callbacks mCallbacks = null;
private ProgressBar mProgressBar;
private UserApiInterface mAPIInterface;
private SharedPreferences mSharedPreferences;
private SharedPreferences.Editor mPreferencesEditor;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_login,container,false);
mBtnLogin = view.findViewById(R.id.btnLogin_login);
mTxtUsername = view.findViewById(R.id.txtUsername);
mTxtPass = view.findViewById(R.id.txtPass);
mCheckBoxRemember = view.findViewById(R.id.checkBoxRememberMe);
mTxtRegister = view.findViewById(R.id.txtRegister_login);
mProgressBar = view.findViewById(R.id.progressBar);
mTxtInvalid = view.findViewById(R.id.txtInvalid);
mProgressBar.setVisibility(View.GONE);
mTxtInvalid.setVisibility(View.GONE);
mAPIInterface = APIClient.getClient().create(UserApiInterface.class);
mSharedPreferences = getContext().getSharedPreferences("login",Context.MODE_PRIVATE);
mPreferencesEditor = mSharedPreferences.edit();
setListener();
return view;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mLoginViewModel = new ViewModelProvider(this).get(LoginViewModel.class);
mUserModelLiveData = mLoginViewModel.getUserModelLiveData();
//observer would be triggered right after loading fragment after logout
mUserModelLiveData.observe(this, new Observer<UserModelJSONPlaceholder>() {
#Override
public void onChanged(UserModelJSONPlaceholder userModel) {
Log.d(TAG, "onChanged: Observer: "+userModel.getResponse());
mProgressBar.setVisibility(View.GONE);
String loginAuth = userModel.getResponse();
if(loginAuth.equals("OK")){
mPreferencesEditor.putString("name",userModel.getUserModel().getName());
mCallbacks.login_goMainMenu(userModel.getUserModel().getName());
}else{
mTxtInvalid.setVisibility(View.VISIBLE);
}
}
});
}
private void doLogin(){
mProgressBar.setVisibility(View.VISIBLE);
final String username = mTxtUsername.getText().toString().trim();
final String password = mTxtPass.getText().toString().trim();
mLoginViewModel.authLogin(username,password);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
mCallbacks = (Callbacks) context;
}
private void setListener(){
mBtnLogin.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
doLogin();
}
});
mTxtRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCallbacks.login_goRegister();
}
});
mCheckBoxRemember.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(buttonView.isChecked()){
mPreferencesEditor.putBoolean("rememberMe", true).apply();
Log.d(TAG, "onCheckedChanged: Checked");
}else{
mPreferencesEditor.putBoolean("rememberMe", false).apply();
Log.d(TAG, "onCheckedChanged: Unchecked");
}
}
});
}
public interface Callbacks{
void login_goMainMenu(String name);
void login_goRegister();
}
}
My MainMenuActivity:
public class MainMenuActivity extends AppCompatActivity {
private static final String ARG_NAME = "arg_name";
private Button mBtnEnterQ,mBtnCreateQ;
private TextView mTxtName;
private Toolbar mToolbar;
private SharedPreferences mSharedPreferences;
private SharedPreferences.Editor mEditor;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu);
mBtnEnterQ = findViewById(R.id.btnEnterQ);
mBtnCreateQ = findViewById(R.id.btnCreateQ);
mTxtName = findViewById(R.id.txtUsername);
mToolbar = findViewById(R.id.toolbar);
mSharedPreferences = getSharedPreferences("login",MODE_PRIVATE);
mEditor = mSharedPreferences.edit();
setSupportActionBar(mToolbar);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.toolbar_menu,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.itemLogout:
doLogout();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void doLogout(){
mEditor.remove("rememberMe");
mEditor.apply();
Intent i = new Intent(this, MainActivity.class);
startActivity(i);
finish();
}
}
and here's my ViewModel and Repo for LoginFragment:
public class LoginViewModel extends ViewModel {
private static final String TAG = "LoginVM";
private UserRepository mUserRepository;
LiveData<UserModelJSONPlaceholder> mUserModelLiveData;
public LoginViewModel() {
mUserRepository = UserRepository.getInstance();
}
public void authLogin(String username, String password){
mUserRepository.authLogin(username,password);
}
public LiveData<UserModelJSONPlaceholder> getUserModelLiveData() {
return mUserRepository.getUserModelLiveData();
}
}
public class UserRepository {
private static UserRepository instance;
private static final String TAG = "RepoUser";
private UserApiInterface mUserApiInterface;
MutableLiveData<UserModelJSONPlaceholder> userModelLiveData;
public static UserRepository getInstance(){
if(instance==null){
instance=new UserRepository();
}
return instance;
}
private UserRepository(){
mUserApiInterface = APIClient.getClient().create(UserApiInterface.class);
Log.d(TAG, "UserRepository: repoInit");
}
public void authLogin(String username, String password){
Log.d(TAG, "authLogin: REQUEST INIT");
Log.d(TAG, "authLogin: SERVER: "+ CONFIG.SERVER);
mUserApiInterface.getUser(username,password).enqueue(new Callback<UserModelJSONPlaceholder>() {
#Override
public void onResponse(Call<UserModelJSONPlaceholder> call, Response<UserModelJSONPlaceholder> response) {
if(response.isSuccessful()){
UserModelJSONPlaceholder r = response.body();
userModelLiveData.postValue(response.body());
}else{
Log.d(TAG, "onResponse: FAILED. "+response.errorBody());
}
}
#Override
public void onFailure(Call<UserModelJSONPlaceholder> call, Throwable t) {
Log.d(TAG, "onFailure: "+t.getMessage());
}
});
}
public LiveData<UserModelJSONPlaceholder> getUserModelLiveData() {
if(userModelLiveData == null)
userModelLiveData = new MutableLiveData<>();
return userModelLiveData;
}
}
Your problems is you make UserRepository is Singleton instance and always keep value of userModelLiveData easy way to fix it change method to this
public LiveData<UserModelJSONPlaceholder> getUserModelLiveData() {
userModelLiveData = new MutableLiveData<>();
return userModelLiveData;
}
Related
I am trying to read data from Firebase Database and using the database fields to initialize an object but it is returning null.
Model class.
public class Event {
private String Nome;
private String data;
private String descrizione;
private String luogo;
private String mese;
private String ora_fine;
private String ora_inizio;
private String type;
private String programma;
private String img ;
public Event()
{
}
public Event(String nome, String data, String descrizione, String luogo, String mese, String ora_fine, String ora_inizio, String type, String mprogramma, String mimg) {
Nome = nome;
this.data = data;
this.descrizione = descrizione;
this.luogo = luogo;
this.mese = mese;
this.ora_fine = ora_fine;
this.ora_inizio = ora_inizio;
this.type = type;
this.programma=mprogramma;
this.img=mimg;
}
public String getNome() {
return Nome;
}
public String getData() {
return data;
}
public String getDescrizione() {
return descrizione;
}
public String getLuogo() {
return luogo;
}
public String getMese() {
return mese;
}
public String getOra_fine() {
return ora_fine;
}
public String getOra_inizio() {
return ora_inizio;
}
public String getType() {
return type;
}
public String getProgramma() {
return programma;
}
public String getImg() {
return img;
}
public Date toDate()
{
DateFormat format = new SimpleDateFormat("dd/MM/yyyy", Locale.ITALIAN);
Date date = null;
try {
date = format.parse(data);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
}
main Activity
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener
{
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mToggle;
private ImageView vangelo;
private ImageView santo;
private ImageView evento;
private ImageView notizia;
private DatabaseReference vangeloRef;
private DatabaseReference santoRef;
private DatabaseReference eventoRef;
private DatabaseReference notiziaRef;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDrawerLayout= (DrawerLayout) findViewById(R.id.drawer_layout); //finds the drawer layout view
mToggle= new ActionBarDrawerToggle(this, mDrawerLayout,R.string.Open, R.string.Close); //creates the action bar
mDrawerLayout.addDrawerListener(mToggle); //adds the action bat to the layout
mToggle.syncState(); //syncs the toggle state with the actual drawer layout
DatabaseReference RootRef=FirebaseDatabase.getInstance().getReference();
eventoRef=RootRef.child("MainEvent");
vangelo=(ImageView)findViewById(R.id.vangelo);
santo=(ImageView)findViewById(R.id.santo);
evento=(ImageView)findViewById(R.id.evento);
notizia=(ImageView)findViewById(R.id.notizia);
vangelo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
santo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
evento.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
notizia.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
ActionBar actionBar = getSupportActionBar();
if (actionBar != null)
actionBar.setDisplayHomeAsUpEnabled(true);
NavigationView mNavigationView = (NavigationView) findViewById(R.id.nav_view);
if (mNavigationView != null) {
mNavigationView.setNavigationItemSelectedListener(this);
}
}
#Override
public void onStart()
{
super.onStart();
eventoRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Event ev= dataSnapshot.getValue(Event.class);
Log.v("Done",ev.getData());
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem Item)
{
if(mToggle.onOptionsItemSelected(Item))
{
return true;
}
return super.onOptionsItemSelected(Item);
}
#Override
public boolean onNavigationItemSelected(MenuItem Item)
{
int id = Item.getItemId();
Intent intent;
if (id == R.id.preghiere)
{
intent= new Intent(this, Preghiere.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
this.startActivity(intent);
}
else if ( id== R.id.bans)
{
intent= new Intent(this, Bans.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
this.startActivity(intent);
}
else if (id== R.id.canzoni)
{
intent= new Intent(this, Canzoni.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
this.startActivity(intent);
}
else if (id==R.id.calendario)
{
intent= new Intent(this, Calendario.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
this.startActivity(intent);
}
else if (id== R.id.per_riflettere)
{
intent= new Intent(this, perRiflettere.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
this.startActivity(intent);
}
else if( id== R.id.home)
{
intent= new Intent(this, this.getClass());
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
this.startActivity(intent);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Database tree
tree
I am trying to instantiate a single event object with the fields of "MainEvent" in the database but the code is returning null. How can I solve?
You have to retrieve data as follow:
eventoRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Event ev= snapshot.getValue(Event.class);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I'm making random chat app where every 2 users are in 1 room. My app worked well if I don't rotate the device, but I just tried to rotate several times right after app is launched to make app robust. Then, the app crashed right away
how can I log in anonymously to firebase authentication and add onCompleteListener when user rotates his/her while the firebase authentication is in progress?
When I first launch the app, a dialog is showed up which is used to announce the user that the app is initializing something and during the dialog is showed in onCreateView of a fragment, app tries to log in to firebase authentication anonymously and set onCompleteListener because when authentication is completed,
I have to insert to firebase database '/user_state/{uid}/"home"' with uid and dismiss dialog to make user possible to push button which is used to find another user to chat where the uid is needed too.
Because the uid is needed in both jobs, I need to do these jobs right after the authentication is completed.
I just thought that I could implement inserting '/user_state/{uid}/"home"' by cloud functions for firebase, but I didn't know how I could know the time when I dismiss the initializing dialog that I showed before because I have to know when the authentication is completed and I need callback function. So I added onCompleteListener like this
FirebaseAuth.getInstance().signInAnonymously().addOnCompleteListener(getActivity(), new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Log.d(TAG, "signInAnonymously:success");
mAuthInitDialog.dismiss();
mCurrentUser = mAuth.getCurrentUser();
UserState state = new UserState(STATE_HOME);
mFirebaseDatabase
.getReference("user_state/" + mCurrentUser.getUid())
.setValue(state);
} else {
Log.w(TAG, "signInAnonymously:failure", task.getException());
mAuthInitDialog.dismiss();
Toast.makeText(getActivity(), "Authentication Failed", Toast.LENGTH_SHORT).show();
}
}
});
But when I rotate the device, the activity is destroyed and listener has gone for sure. So, I just thought that how about changing my code like below
Task mTask = FirebaseAuth.getInstance().signInAnonymously();
mTask.addOnCompleteListener( ...
and I used onSaveInstanceState method and Gson to save my Task Object like below
bundle.putString(BUNDLE_TASK_AUTH, new Gson().toJson(mTaskAuth));
and restored like below
if(savedInstanceState != null) {
mTask = new Gson().fromJson(savedInstanceState.getString(BUNDLE_TASK_AUTH), Task.class);
mTask.setOnCompleteListener( ...
}
But, I'm not sure if the listener could catch the authentication complete event even though the listener is retored after the fragment is recreated every time
Because I thought that authentication complete event can occur when after the activity is destroyed and before the activity is recreated.
I just want to make robust app even though there are several device rotations using firebase authentication. What should I do?
Code for MainFragment.java
public class MainFragment extends Fragment {
private static final String TAG = "sgc109.MainFragment";
private static final String DIALOG_PROGRESS = "DialogProgress";
private static final String BUNDLE_IS_WAITING = "bundle_is_waiting";
private static final String BUNDLE_TASK_AUTH = "bundle_task_auth";
private static final String CMD_START_WAITING = "start_waiting";
private static final String CMD_STOP_WAITING = "stop_waiting";
private static final String CMD_EXIT = "exit";
private static final String CMD_SEND = "send";
private static final String STATE_HOME = "home";
private static final String STATE_WAITING = "waiting";
private static final String STATE_MATCHED = "matched";
private static final String STATE_PENDING = "pending";
private static final int REQUEST_CHAT_ROOM = 0;
private boolean isWaiting;
private boolean hasRequestedAuth;
private Task mTaskAuth;
private FirebaseAuth mAuth;
private Button mEnterTheRoomButton;
private ProgressDialog mProgressDialog;
private ProgressDialog mAuthInitDialog;
private FirebaseDatabase mFirebaseDatabase;
private FirebaseUser mCurrentUser;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (savedInstanceState != null) {
Log.i(TAG, "retore savedInstanceState!");
isWaiting = savedInstanceState.getBoolean(BUNDLE_IS_WAITING, false);
mTaskAuth = new Gson().fromJson(savedInstanceState.getString(BUNDLE_TASK_AUTH), Task.class);
}
if (isWaiting) {
showProgressDialog();
}
View view = inflater.inflate(R.layout.fragment_main, container, false);
mAuth = FirebaseAuth.getInstance();
mCurrentUser = mAuth.getCurrentUser();
mFirebaseDatabase = FirebaseDatabase.getInstance();
if (mCurrentUser == null) {
mAuthInitDialog = new ProgressDialog(getActivity());
mAuthInitDialog.setTitle("첫 실행 초기화 중");
mAuthInitDialog.setCanceledOnTouchOutside(false);
mAuthInitDialog.setCancelable(false);
mAuthInitDialog.show();
if (mTaskAuth == null) {
mTaskAuth = mAuth.signInAnonymously();
}
mTaskAuth.addOnCompleteListener(getActivity(), new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Log.d(TAG, "signInAnonymously:success");
mAuthInitDialog.dismiss();
mCurrentUser = mAuth.getCurrentUser();
UserState state = new UserState(STATE_HOME);
mFirebaseDatabase
.getReference("user_state/" + mCurrentUser.getUid())
.setValue(state);
} else {
Log.w(TAG, "signInAnonymously:failure", task.getException());
mAuthInitDialog.dismiss();
Toast.makeText(getActivity(), "Authentication Failed", Toast.LENGTH_SHORT).show();
}
}
});
}
else {
mFirebaseDatabase
.getReference()
.child("user_state")
.child(mCurrentUser.getUid())
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
UserState state = dataSnapshot.getValue(UserState.class);
if (state.state.equals(STATE_MATCHED)) {
enterChatRoom();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "onCancelled");
}
});
}
mEnterTheRoomButton = (Button) view.findViewById(R.id.activity_main_enter_the_room_button);
mEnterTheRoomButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mCurrentUser == null) {
return;
}
if (!isWaiting) {
startWaitingForOtherUser();
isWaiting = true;
}
showProgressDialog();
}
});
return view;
}
#Override
public void onStop() {
super.onStop();
if (mProgressDialog != null) mProgressDialog.dismiss();
if (mAuthInitDialog != null) mAuthInitDialog.dismiss();
}
#Override
public void onSaveInstanceState(Bundle outState) {
Log.i(TAG, "onSavedInstaneState()");
super.onSaveInstanceState(outState);
outState.putBoolean(BUNDLE_IS_WAITING, isWaiting);
outState.putString(BUNDLE_TASK_AUTH, new Gson().toJson(mTaskAuth));
}
public void showProgressDialog() {
mProgressDialog = new ProgressDialog(getActivity());
mProgressDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
#Override
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
isWaiting = false;
dialog.cancel();
stopWaitingForOtherUser();
return true;
}
return false;
}
});
mProgressDialog.setCanceledOnTouchOutside(false);
mProgressDialog.setTitle(R.string.find_other_user_progress_dialog_text);
mProgressDialog.show();
}
public void stopWaitingForOtherUser() {
CommandSender.sendCommand(CMD_STOP_WAITING);
}
public void startWaitingForOtherUser() {
CommandSender.sendCommand(CMD_START_WAITING);
}
public void enterChatRoom() {
isWaiting = false;
Intent intent = ChatRoomActivity.newIntent(getActivity());
startActivityForResult(intent, REQUEST_CHAT_ROOM);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != Activity.RESULT_OK) {
return;
}
switch (requestCode) {
case REQUEST_CHAT_ROOM:
boolean reEnter = data.getBooleanExtra(ChatRoomActivity.EXTRA_RE_ENTER_ROOM, false);
if (reEnter){
showProgressDialog();
startWaitingForOtherUser();
}
default:
return;
}
}
}
I solved this by using ViewModel. I found from here that ViewModel holds our data even though Activity is destroyed because of configuration change such as device rotation.
My changed code is below.
MainFragment.java
public class MainFragment extends Fragment {
private static final String TAG = "sgc109.MainFragment";
private static final String DIALOG_PROGRESS = "DialogProgress";
private static final String BUNDLE_IS_WAITING = "bundle_is_waiting";
private static final String BUNDLE_IS_AUTH_COMPLETE = "bundle_is_auth_complete";
private static final String CMD_START_WAITING = "start_waiting";
private static final String CMD_STOP_WAITING = "stop_waiting";
private static final String CMD_EXIT = "exit";
private static final String CMD_SEND = "send";
private static final String STATE_HOME = "home";
private static final String STATE_WAITING = "waiting";
private static final String STATE_MATCHED = "matched";
private static final String STATE_PENDING = "pending";
private static final int REQUEST_CHAT_ROOM = 0;
private boolean mIsWaiting;
private boolean mIsAuthComplete;
private Button mEnterTheRoomButton;
private ProgressDialog mProgressDialog;
private ProgressDialog mAuthInitDialog;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (savedInstanceState != null) {
Log.i(TAG, "retore savedInstanceState!");
mIsWaiting = savedInstanceState.getBoolean(BUNDLE_IS_WAITING, false);
mIsAuthComplete = savedInstanceState.getBoolean(BUNDLE_IS_AUTH_COMPLETE, false);
}
if (mIsWaiting) {
showProgressDialog();
}
View view = inflater.inflate(R.layout.fragment_main, container, false);
if (mIsAuthComplete) {
showAuthInitDialog();
MyViewModel model = ViewModelProviders.of(this).get(MyViewModel.class);
model.getTask().addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
mAuthInitDialog.dismiss();
if (task.isSuccessful()) {
Log.d(TAG, "signInAnonymously:success");
mIsAuthComplete = true;
UserState state = new UserState(STATE_HOME);
FirebaseDatabase
.getInstance()
.getReference("user_state/" + FirebaseAuth.getInstance().getCurrentUser().getUid())
.setValue(state);
} else {
Log.w(TAG, "signInAnonymously:failure", task.getException());
getActivity().finish();
}
}
});
} else {
FirebaseDatabase
.getInstance()
.getReference()
.child("user_state")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
UserState state = dataSnapshot.getValue(UserState.class);
if (state.state.equals(STATE_MATCHED)) {
enterChatRoom();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "onCancelled");
}
});
}
mEnterTheRoomButton = (Button) view.findViewById(R.id.activity_main_enter_the_room_button);
mEnterTheRoomButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (FirebaseAuth.getInstance().getCurrentUser() == null) {
Toast.makeText(getActivity(), "Shit Fuck!", Toast.LENGTH_SHORT).show();
return;
}
showProgressDialog();
startWaitingForOtherUser();
mIsWaiting = true;
}
});
return view;
}
private void showAuthInitDialog() {
mAuthInitDialog = new ProgressDialog(getActivity());
mAuthInitDialog.setTitle("첫 실행 초기화 중");
mAuthInitDialog.setCanceledOnTouchOutside(false);
mAuthInitDialog.setCancelable(false);
mAuthInitDialog.show();
}
#Override
public void onStop() {
super.onStop();
if (mProgressDialog != null) mProgressDialog.dismiss();
if (mAuthInitDialog != null) mAuthInitDialog.dismiss();
}
#Override
public void onSaveInstanceState(Bundle outState) {
Log.i(TAG, "onSavedInstaneState()");
super.onSaveInstanceState(outState);
outState.putBoolean(BUNDLE_IS_WAITING, mIsWaiting);
outState.putBoolean(BUNDLE_IS_AUTH_COMPLETE, mIsAuthComplete);
}
public void showProgressDialog() {
mProgressDialog = new ProgressDialog(getActivity());
mProgressDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
#Override
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
mIsWaiting = false;
dialog.cancel();
stopWaitingForOtherUser();
return true;
}
return false;
}
});
mProgressDialog.setCanceledOnTouchOutside(false);
mProgressDialog.setTitle(R.string.find_other_user_progress_dialog_text);
mProgressDialog.show();
}
public void stopWaitingForOtherUser() {
CommandSender.sendCommand(CMD_STOP_WAITING);
}
public void startWaitingForOtherUser() {
CommandSender.sendCommand(CMD_START_WAITING);
}
public void enterChatRoom() {
mIsWaiting = false;
Intent intent = ChatRoomActivity.newIntent(getActivity());
startActivityForResult(intent, REQUEST_CHAT_ROOM);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != Activity.RESULT_OK) {
return;
}
switch (requestCode) {
case REQUEST_CHAT_ROOM:
boolean reEnter = data.getBooleanExtra(ChatRoomActivity.EXTRA_RE_ENTER_ROOM, false);
if (reEnter) {
showProgressDialog();
startWaitingForOtherUser();
}
default:
return;
}
}
}
MyViewModel.java
public class MyViewModel extends ViewModel {
private Task task;
public Task getTask(){
if (task == null){
task = FirebaseAuth.getInstance().signInAnonymously();
}
return task;
}
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I'm using Model View Presenter in my application, and i try to save a value token in SharedPreferences. But, I got the SharedPreferences null, the error is SharedPreferences.edit() is a null object references. Please, help me to solve this. Thank you
This is my Fragment
public class SignUpFragment extends BaseFragment {
#NotEmpty(messageResId = R.string.rules_no_empty)
#Bind(R.id.Name)
EditText etName;
#NotEmpty(messageResId = R.string.rules_no_empty)
#Bind(R.id.email)
EditText etEmail;
#NotEmpty(messageResId = R.string.rules_no_empty)
#Bind(R.id.phone)
EditText etPhone;
#Bind(R.id.btnSignUp)
Button btnSignUp;
public static final String TAG = SignUpFragment.class.getSimpleName();
private SignUpPresenter presenter;
SharedPreferences sharedpreferences;
public static final String MyPREFERENCES = "MyPrefs" ;
public static void showFragment(BaseActivity sourceActivity) {
if (!sourceActivity.isFragmentNotNull(TAG)) {
FragmentTransaction fragmentTransaction = sourceActivity.getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.content_question, new SignUpFragment(), TAG);
fragmentTransaction.commit();
}
}
#Override
protected int getLayout() {
return R.layout.activity_sign_up;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
presenter = new SignUpPresenter(this);
sharedpreferences = getActivity().getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
initview();
}
#Override
public void onResume() {
super.onResume();
}
private void initview (){
btnSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!validate()) {
onSignupFailed();
return;
} else {
presenter.signup();
}
}
});
}
#Override
public void onValidationSucceeded() {
super.onValidationSucceeded();
presenter.signup();
}
public void onSignupFailed() {
Toast.makeText(getContext(), "Login failed", Toast.LENGTH_LONG).show();
btnSignUp.setEnabled(true);
}
public boolean validate() {
boolean valid = true;
String name = etName.getText().toString();
String email = etEmail.getText().toString();
String password = etPhone.getText().toString();
if (name.isEmpty() || name.length() < 3) {
etName.setError("at least 3 characters");
valid = false;
} else {
etName.setError(null);
}
if (email.isEmpty() || !android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
etEmail.setError("enter a valid email address");
valid = false;
}
if (password.isEmpty() || password.length() < 4 || password.length() > 10) {
etPhone.setError("between 4 and 10 alphanumeric characters");
valid = false;
} else {
etPhone.setError(null);
}
return valid;
}
public void gotoQuestionActivity(String email, String name, String phone) {
QuestionActivity.startActivity((BaseActivity) getActivity(), email, name, phone);
getActivity().finish();
}
}
and this my Presenter
public class SignUpPresenter {
private SignUpFragment fragment;
public String token = "token";
SharedPreferences sharedpreferences;
private Context mContext;
public static final String MyPREFERENCES = "MyPrefs" ;
public SignUpPresenter(SignUpFragment fragment) {
this.fragment = fragment;
}
public SignUpRequest constructSignUpRequest() {
SignUpRequest request = new SignUpRequest();
request.setName(getAndTrimValueFromEditText(fragment.etName));
request.setEmail(getAndTrimValueFromEditText(fragment.etEmail));
request.setMobile(getAndTrimValueFromEditText(fragment.etPhone));
return request;
}
private String getAndTrimValueFromEditText(EditText e) {
return e.getText().toString().trim();
}
public SharedPreferences getSharedPreferences() {
return sharedpreferences;
}
void signup (){
this.register(constructSignUpRequest());
}
void register(final SignUpRequest signUpRequest) {
fragment.showProgressDialog(fragment.loading);
fragment.getApi().regsiterCustomer(constructSignUpRequest())
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(new Observer<GenericResponse>() {
#Override
public void onCompleted() {
}
#Override
public void onError(Throwable e) {
fragment.dismissProgressDialog();
Timber.e(e.getLocalizedMessage());
Toast.makeText(fragment.getContext(), fragment.connectionError, Toast.LENGTH_SHORT).show();
}
#Override
public void onNext(GenericResponse signUpResponse) {
fragment.dismissProgressDialog();
Toast.makeText(fragment.getContext(), signUpResponse.getInfo(), Toast.LENGTH_SHORT).show();
if (signUpResponse.getCode() == fragment.successCode) {
/*fragment.gotoActivationCodeActivity(SignUpRequest.getEmail(), SignUpRequest.get());*/
fragment.gotoQuestionActivity(signUpRequest.getEmail(), signUpRequest.getName(), signUpRequest.getMobile());
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(token, signUpResponse.getData().getToken());
editor.commit();
}
}
});
}
}
You missed to define the sharedpreferences in the second class like this, the way you did in the first class.
sharedpreferences = fragment.getActivity().getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
Place this line, just above the code,
SharedPreferences.Editor editor = sharedpreferences.edit();
inside onNext()
I'm buliding a simple android app, and i got this error when i try to send data to API. I use RxJava and Retrofit, and I use Model View Presenter.
I got this error "btnservice is a null object reference"
I always got btnservice null, please help to solve this.
Thank you
This the JSON
request:
{
name: '',
mobile: '',
email: ''
}
This my BaseActivtiy
public abstract class BaseActivity extends AppCompatActivity {
#BindString(R.string.loading)
public String loading;
#BindInt(R.integer.success_code)
public int successCode;
#BindInt(R.integer.success_activication_code)
public int activicationSuccessCode;
protected BTNService btnService;
protected abstract int getLayout();
private ProgressDialog progressDialog;
private CompositeSubscription subscriptions;
protected RxBus bus;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(getLayout());
Icepick.restoreInstanceState(this, savedInstanceState);
ButterKnife.bind(this);
this.progressDialog = new ProgressDialog(this);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Icepick.saveInstanceState(this, outState);
}
#Override
protected void onStart() {
super.onStart();
this.subscriptions = new CompositeSubscription();
}
#Override
public void onStop() {
super.onStop();
}
#Override
protected void onDestroy() {
super.onDestroy();
this.progressDialog.dismiss();
}
public BTNService getBTNService() {
return btnService;
}
public RxBus getBus() {
return bus;
}
public void showProgressDialog(String message) {
if (progressDialog != null) {
progressDialog.setMessage(message);
progressDialog.show();
}
}
public void dismissProgressDialog() {
progressDialog.hide();
}
public boolean isFragmentNotNull(String tag) {
if (getSupportFragmentManager().findFragmentByTag(tag) != null) {
return true;
} else {
return false;
}
}
public boolean isFragmentVisible(String tag) {
if (isFragmentNotNull(tag)
&& getSupportFragmentManager().findFragmentByTag(tag).isVisible()) {
return true;
} else {
return false;
}
}
}
This my BaseFragment
public abstract class BaseFragment extends Fragment implements Validator.ValidationListener {
#BindString(R.string.loading)
public String loading;
#BindInt(R.integer.success_code)
public int successCode;
#BindInt(R.integer.success_activication_code)
public int activicationSuccessCode;
#BindString(R.string.connection_error)
public String connectionError;
protected abstract int getLayout();
protected Validator validator;
private CompositeSubscription subscriptions;
protected RxBus bus;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
this.bus = ((BaseActivity) getActivity()).getBus();
}
#Override
public void onStart() {
super.onStart();
this.subscriptions = new CompositeSubscription();
/* this.subscriptions
.add(bus.toObserverable()
.subscribe(new Action1<Object>() {
#Override
public void call(Object event) {
if (event instanceof RxBusObject) {
RxBusObject busObject = (RxBusObject) event;
busHandler();
}
}
})
);*/
}
#Override
public void onStop() {
super.onStop();
this.subscriptions.clear();
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(getLayout(), container, false);
ButterKnife.bind(this, view);
return view;
}
public RxBus getBus() {
return this.bus;
}
#Override
public void onValidationSucceeded() {
}
#Override
public void onValidationFailed(List<ValidationError> errors) {
for (ValidationError error : errors) {
View view = error.getView();
String message = error.getCollatedErrorMessage(getActivity());
if (view instanceof EditText) {
EditText et = ((EditText) view);
et.setError(message);
et.requestFocus();
} else {
Toast.makeText(getActivity(), message, Toast.LENGTH_LONG).show();
}
}
}
public void showSuccessDialog(String message, final Boolean isFinishActivity) {
new MaterialDialog.Builder(getActivity())
.iconRes(R.mipmap.ic_launcher)
.title(getString(R.string.success).toUpperCase())
.titleColor(Color.WHITE)
.content(message)
.contentColor(Color.WHITE)
.positiveText(R.string.ok)
.positiveColor(Color.WHITE)
.onPositive(new MaterialDialog.SingleButtonCallback() {
#Override
public void onClick(MaterialDialog dialog, DialogAction which) {
if (isFinishActivity) {
getActivity().finish();
}
}
})
.cancelable(false)
.show();
}
public void showProgressDialog(String message) {
((BaseActivity) getActivity()).showProgressDialog(message);
}
public Validator getValidator() {
return validator;
}
public BTNService.Api getApi() {
return ((BaseActivity) getActivity()).getBTNService().getApi();
}
public void dismissProgressDialog() {
((BaseActivity) getActivity()).dismissProgressDialog();
}
}
This my Retrofit Class
public BTNService(Context context) {
if (retrofit==null) {
Retrofit retrofit = new Retrofit.Builder()
.client(provideOkHttpClient(context))
.baseUrl(BASE_URL)
.build();
this.api = retrofit.create(Api.class);
}
}
private OkHttpClient provideOkHttpClient(final Context context) {
HttpLoggingInterceptor httpLoggingInterceptorinterceptor = new HttpLoggingInterceptor();
httpLoggingInterceptorinterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.addInterceptor(httpLoggingInterceptorinterceptor);
httpClient.addInterceptor(new Interceptor() {
#Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Response response = chain.proceed(request);
return response;
}
});
return httpClient.build();
}
public Api getApi() {
return api;
}
public interface Api {
#POST(PORTAL_URL + "customer/register")
Observable<SignUpResponse> regsiterCustomer(#Path("email") String Email,
#Path("name") String Name,
#Path("mobile") String PhoneNumber);
}
and this my Presenter
public class SignUpPresenter {
private SignUpFragment fragment;
public SignUpPresenter(SignUpFragment fragment) {
this.fragment = fragment;
}
public SignUpRequest constructSignUpRequest() {
SignUpRequest request = new SignUpRequest();
request.setName(getAndTrimValueFromEditText(fragment.etName));
request.setEmail(getAndTrimValueFromEditText(fragment.etEmail));
request.setMobile(getAndTrimValueFromEditText(fragment.etPhone));
return request;
}
private String getAndTrimValueFromEditText(EditText e) {
return e.getText().toString().trim();
}
void signup (){
this.register(constructSignUpRequest());
}
void register(final SignUpRequest signUpRequest) {
fragment.showProgressDialog(fragment.loading);
fragment.getApi().regsiterCustomer(
signUpRequest.getName(),
signUpRequest.getEmail(),
signUpRequest.getMobile())
.subscribeOn(Schedulers.io())
.subscribe(new Observer<GenericResponse>() {
#Override
public void onCompleted() {
}
#Override
public void onError(Throwable e) {
fragment.dismissProgressDialog();
Timber.e(e.getLocalizedMessage());
Toast.makeText(fragment.getContext(), fragment.connectionError, Toast.LENGTH_SHORT).show();
}
#Override
public void onNext(GenericResponse genericResponse) {
fragment.dismissProgressDialog();
Toast.makeText(fragment.getContext(), genericResponse.getInfo(), Toast.LENGTH_SHORT).show();
if (genericResponse.getCode() == fragment.successCode) {
/*fragment.gotoActivationCodeActivity(SignUpRequest.getEmail(), SignUpRequest.get());*/
fragment.gotoQuestionActivity(signUpRequest.getEmail(), signUpRequest.getEmail(), signUpRequest.getMobile());
}
}
});
}
public static <T> Function<BaseResponse<T>, Observable<T>> convertDataFlatMap() {
return new Function<BaseResponse<T>, Observable<T>>() {
#Override
public Observable<T> apply(BaseResponse<T> response) {
if (!Constants.SUCCESS_CODE.equals(response.getStatus_code())) {
BaseErrorResponse baseErrorResponse = new BaseErrorResponse();
baseErrorResponse.setError(response.getStatus_code(),
response.getStatus());
return Observable.error(BaseException.toServerError(baseErrorResponse));
}
T data = response.getData();
if (null == data) {
return Observable.empty();
}
return Observable.just(response.getData());
}
};
}
I'm using Rxjava 2, Maybe useful for you.
I am working on post method with parameters. My app is not responding (find my code below). I am getting a NullPointerException when I am trying to add data into queue in void addToRequestQueue(Request<T> req, String tag). Could you, please, help me to identify the problem.
RegisterActivity
public class RegistrationActivity extends AppCompatActivity implements View.OnClickListener, VolleyTasksListener {
private Button btnRegister;
private EditText edtEmail;
private EditText edtConfirmEmail;
private EditText edtPassword;
private EditText edtconfirmPassword;
private EditText edtFullName;
private EditText edtContactNumber;
private TextView txtDOB;
private LinearLayout parentLayout;
private Toolbar toolbar;
private String udid;
private TextView txtErrEmail;
private TextView txtErrCEMAIL;
private TextView txtErrPassword;
private TextView txtErrCpassword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
findViews();
initToolbar();
}
private void findViews() {
parentLayout = (LinearLayout) findViewById(R.id.lyt_parent);
btnRegister = (Button) findViewById(R.id.btn_register);
txtDOB = (TextView) findViewById(R.id.txt_dob);
txtErrPassword = (TextView) findViewById(R.id.txt_err_password);
txtErrCpassword = (TextView) findViewById(R.id.txt_err_c_password);
txtErrEmail = (TextView) findViewById(R.id.txt_err_email);
txtErrCEMAIL = (TextView) findViewById(R.id.txt_err_c_email);
edtEmail = (EditText) findViewById(R.id.edt_email);
edtConfirmEmail = (EditText) findViewById(R.id.edt_confirm_email);
edtPassword = (EditText) findViewById(R.id.edt_password);
edtconfirmPassword = (EditText) findViewById(R.id.edt_confirm_password);
edtFullName = (EditText) findViewById(R.id.edt_full_name);
edtContactNumber = (EditText) findViewById(R.id.edt_contact_number);
udid = Settings.Secure.getString(RegistrationActivity.this.getContentResolver(), Settings.Secure.ANDROID_ID);
TypefaceHelper.getInstance().setTypeface(parentLayout, Constant.FONT_OPENSANS_REGULAR);
TypefaceHelper.getInstance().setTypeface(btnRegister, Constant.FONT_OPENSANS_BOLD);
txtDOB.setOnClickListener(this);
btnRegister.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btn_register:
getRegistrationService();
break;
case R.id.txt_dob:
ShowDatePicker();
break;
}
}
private void getRegistrationServiceValidation() {
{
String username = edtFullName.getText().toString().trim();
String confirmEmail = edtConfirmEmail.getText().toString();
String email = edtEmail.getText().toString();
String confirmPassword = edtconfirmPassword.getText().toString();
String mobile = edtContactNumber.getText().toString();
String password = edtPassword.getText().toString();
if (ValidationUtils.isValidEmail(email)) {
if (ValidationUtils.isValidEmail(email, confirmEmail)) {
if (ValidationUtils.isValidPassword(password)) {
if (ValidationUtils.isValidPassword(password, confirmPassword)) {
getRegistrationService();
} else {
txtErrCpassword.setVisibility(View.VISIBLE);
txtErrCpassword.setText("Password does not match");
}
}else{
txtErrPassword.setVisibility(View.VISIBLE);
txtErrPassword.setText("Password require more than 8 character");
}
}else {
txtErrCEMAIL.setVisibility(View.VISIBLE);
txtErrCEMAIL.setText("*Email does not match");
}
}else {
txtErrEmail.setVisibility(View.VISIBLE);
txtErrEmail.setText("*This Email has already been used");
}
}
}
private void getRegistrationService() {
if (ConnectionUtils.isConnectedNetwork(RegistrationActivity.this)) {
JSONObject jsonMainObject = new JSONObject();
try {
jsonMainObject.put("email_id", edtEmail.getText().toString());
jsonMainObject.put("password", edtPassword.getText().toString());
jsonMainObject.put("full_name", edtFullName.getText().toString());
jsonMainObject.put("contact_number", edtContactNumber.getText().toString());
jsonMainObject.put("dob", txtDOB.getText().toString());
jsonMainObject.put("gender", "Male");
VolleyTasks.makeVolleyPost(RegistrationActivity.this, Constant.REGISTRATION_URL, jsonMainObject, "Login");
} catch (JSONException e) {
e.printStackTrace();
}
} else {
DialogUtils.switchOnInternetDialog(RegistrationActivity.this, false);
}
}
private void getRegisterSucessAlert() {
Builder builder = new Builder(this);
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View layout = inflater.inflate(R.layout.alet_register_success, (ViewGroup) findViewById(R.id.lnt_root));
LinearLayout lytAlertParent = (LinearLayout) layout.findViewById(R.id.lnt_root);
TextView txttitle = (TextView) layout.findViewById(R.id.txt_register_title);
TypefaceHelper.getInstance().setTypeface(lytAlertParent, Constant.FONT_OPENSANS_REGULAR);
TypefaceHelper.getInstance().setTypeface(txttitle, Constant.FONT_OPENSANS_BOLD);
Button btnOk = (Button) layout.findViewById(R.id.btn_ok);
builder.setView(layout);
final android.app.AlertDialog alertDialog = builder.create();
alertDialog.setCanceledOnTouchOutside(true);
alertDialog.show();
btnOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ActivityUtils.launchActivity(RegistrationActivity.this, HomeActivity.class, true);
}
});
}
private void ShowDatePicker() {
{
final AlertDialog.Builder builder = new AlertDialog.Builder(RegistrationActivity.this, R.style.AppCompatAlertDialogStyle);
final View view = View.inflate(RegistrationActivity.this, R.layout.picker_date, null);
builder.setView(view);
final DatePicker datePicker = (DatePicker) view.findViewById(R.id.date_picker);
builder.setPositiveButton("Set", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Calendar calendar = new GregorianCalendar(datePicker.getYear(), datePicker.getMonth(), datePicker.getDayOfMonth());
String date = DateUtils.getSimpleDateFormat(Constant.DATE_TEMPLATE_CAB_BOOK, calendar.getTime());
txtDOB.setText(date);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
builder.show();
}
}
private void initToolbar() {
toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("");
toolbar.setTitleTextColor(Color.WHITE);
setSupportActionBar(toolbar);
ImageView imgClose = (ImageView) findViewById(R.id.img_close);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
imgClose.setColorFilter(getResources().getColor(R.color.ft_blue, null));
} else {
imgClose.setColorFilter(getResources().getColor(R.color.ft_blue));
}
imgClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ActivityUtils.launchActivity(RegistrationActivity.this, AuthenticationActivity.class, true);
}
});
}
#Override
public void onBackPressed() {
super.onBackPressed();
ActivityUtils.launchActivity(this, AuthenticationActivity.class, true);
}
#Override
public void handleError(Exception error) {
L.d("Error"+error);
}
#Override
public void handleResult(String method_name, JSONObject response) {
L.d ("response" + response);
if (response != null) {
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.serializeNulls();
Gson gson = gsonBuilder.create();
if (method_name.equals("Login")) {
AbstractRegister abstractRegister = gson.fromJson(response.toString(), AbstractRegister.class);
if (abstractRegister != null) {
if (abstractRegister.getResponse().equals("1")) {
getRegisterSucessAlert();
} else {
}
} else {
}
}
}
}}
Application
public class eTravelApplication extends Application {
private static eTravelApplication sInstance;
private RequestQueue mRequestQueue;
public static final String TAG = "VolleyPatterns";
#Override
public void onCreate() {
super.onCreate();
TypefaceHelper.initialize(this);
}
/**
* #return ApplicationController singleton instance
*/
public static synchronized eTravelApplication getInstance() {
return sInstance;
}
public RequestQueue getRequestQueue() {
// created when it is accessed for the first time
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue (getApplicationContext ());
}
return mRequestQueue;
}
/**
* Adds the specified request to the global queue, if tag is specified
* then it is used else Default TAG is used.
*
* #param req
* #param tag
*/
public <T> void addToRequestQueue(Request<T> req, String tag) {
// set the default tag if tag is empty
req.setTag(TextUtils.isEmpty (tag) ? TAG : tag);
VolleyLog.d ("Adding request to queue: %s", req.getUrl ());
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
// set the default tag if tag is empty
req.setTag(TAG);
getRequestQueue().add(req);
}
/**
* Cancels all pending requests by the specified TAG, it is important
* to specify a TAG so that the pending/ongoing requests can be cancelled.
*
* #param tag
*/
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
#Override
public void onTerminate() {
TypefaceHelper.destroy();
super.onTerminate();
}}