This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
Hi I have searched through Stackoverflow and Google and I believe my error is I am not initiating the variable email. But I can't figure where my error is in my code. Any help would be appreciated. Thanks.
The error I am getting is.
FATAL EXCEPTION: main Process: com.xxx.loginandregistration, PID: 5821
java.lang.NullPointerException: Attempt to invoke virtual method
'java.lang.String com.xxx.loginandregistration.User.getEmail()' on a
null object reference at
com.xxx.loginandregistration.LoginFragment$1.onResponse(LoginFragment.java:105)
at
retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.jav...:
I think my error is in my loginProcess method but I am not sure what I am doing wrong.
private void loginProcess(String email,String password){
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constants.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
RequestInterface requestInterface = retrofit.create(RequestInterface.class);
User user = new User();
user.setEmail(email);
user.setPassword(password);
ServerRequest request = new ServerRequest();
request.setOperation(Constants.LOGIN_OPERATION);
request.setUser(user);
Call<ServerResponse> response = requestInterface.operation(request);
response.enqueue(new Callback<ServerResponse>() {
#Override
public void onResponse(Call<ServerResponse> call, retrofit2.Response<ServerResponse> response) {
ServerResponse resp = response.body();
Snackbar.make(getView(), resp.getMessage(), Snackbar.LENGTH_LONG).show();
if(resp.getResult().equals(Constants.SUCCESS)){
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean(Constants.IS_LOGGED_IN,true);
editor.putString(Constants.EMAIL,resp.getUser().getEmail());
editor.putString(Constants.FIRSTNAME,resp.getUser().getFirstname());
editor.putString(Constants.LASTNAME,resp.getUser().getLastname());
editor.putString(Constants.UNIQUE_ID,resp.getUser().getUnique_id());
editor.apply();
goToProfile();
}
progress.setVisibility(View.INVISIBLE);
}
My full Code
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.AppCompatButton;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
/**
* Created by hozda_000 on 4/19/2016.
*/
public class LoginFragment extends Fragment implements View.OnClickListener {
private AppCompatButton loginButton;
private EditText emailEditText;
private EditText passwordEditText;
private TextView registerTextView;
private ProgressBar progress;
private SharedPreferences pref;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_login, container,false);
initViews(view);
return view;
}
private void initViews(View view) {
pref = getActivity().getPreferences(0);
loginButton = (AppCompatButton)view.findViewById(R.id.loginButton);
registerTextView = (TextView)view.findViewById(R.id.registerTextView);
emailEditText = (EditText)view.findViewById(R.id.emailEditText);
passwordEditText = (EditText)view.findViewById(R.id.passwordEditText);
progress = (ProgressBar)view.findViewById(R.id.progress);
loginButton.setOnClickListener(this);
registerTextView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.registerTextView:
goToRegister();
break;
case R.id.loginButton:
String email = emailEditText.getText().toString();
String password = passwordEditText.getText().toString();
if(!email.isEmpty() && !password.isEmpty()) {
progress.setVisibility(View.VISIBLE);
loginProcess(email, password);
} else {
Snackbar.make(getView(), "You have empty fields!", Snackbar.LENGTH_LONG).show();
}
break;
}
}
private void loginProcess(String email,String password){
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constants.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
RequestInterface requestInterface = retrofit.create(RequestInterface.class);
User user = new User();
user.setEmail(email);
user.setPassword(password);
ServerRequest request = new ServerRequest();
request.setOperation(Constants.LOGIN_OPERATION);
request.setUser(user);
Call<ServerResponse> response = requestInterface.operation(request);
response.enqueue(new Callback<ServerResponse>() {
#Override
public void onResponse(Call<ServerResponse> call, retrofit2.Response<ServerResponse> response) {
ServerResponse resp = response.body();
Snackbar.make(getView(), resp.getMessage(), Snackbar.LENGTH_LONG).show();
if(resp.getResult().equals(Constants.SUCCESS)){
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean(Constants.IS_LOGGED_IN,true);
editor.putString(Constants.EMAIL,resp.getUser().getEmail());
editor.putString(Constants.FIRSTNAME,resp.getUser().getFirstname());
editor.putString(Constants.LASTNAME,resp.getUser().getLastname());
editor.putString(Constants.UNIQUE_ID,resp.getUser().getUnique_id());
editor.apply();
goToProfile();
}
progress.setVisibility(View.INVISIBLE);
}
#Override
public void onFailure(Call<ServerResponse> call, Throwable t) {
progress.setVisibility(View.INVISIBLE);
Log.d(Constants.TAG, "failed");
Snackbar.make(getView(), t.getLocalizedMessage(), Snackbar.LENGTH_LONG).show();
}
});
}
private void goToRegister(){
Fragment register = new RegisterFragment();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.fragment_frame, register);
ft.commit();
}
private void goToProfile(){
Fragment profile = new ProfileFragment();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.fragment_frame, profile);
ft.commit();
}
}
editor.putString(Constants.EMAIL,resp.getUser().getEmail()); this line is causing error.
Object returned from resp.getUser()is null so calling getEmail() method on null object gives you NullPointerException
What is a NullPointerException, and how do I fix it?
Related
On running this app on an emulator it is performing as expected but when run on an actual android device it is not producing desired result and is showing the warning "getExtractedText on inactive InputConnection" in the logs. It's a chatbot application where i'm performing get request on an api with retrofit2 library.
package com.example.chatbot;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Context;
import android.inputmethodservice.Keyboard;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.ArrayList;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class MainActivity extends AppCompatActivity {
private RecyclerView chatBotRV;
private MessageAdapter messageAdapter;
private FloatingActionButton sendButton;
private EditText queryText;
private String USER_KEY = "USER";
private String BOT_KEY = "CHAT_BOT";
private Retrofit retrofit;
private APIservice apIservice;
private ArrayList<ChatModel> chatModelArrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
chatBotRV = findViewById(R.id.chat_bot_rv);
sendButton = findViewById(R.id.send_button);
queryText = findViewById(R.id.chat_ev);
chatModelArrayList = new ArrayList<>();
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(!queryText.getText().toString().isEmpty()){
String message = queryText.getText().toString();
queryText.setText(null);
getMessage(message);
}else{
Toast.makeText(MainActivity.this, "Please enter your message :)", Toast.LENGTH_SHORT).show();
return;
}
}
});
messageAdapter = new MessageAdapter(chatModelArrayList, MainActivity.this);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
chatBotRV.setLayoutManager(layoutManager);
chatBotRV.setAdapter(messageAdapter);
}
private void getMessage(String msg){
ChatModel chatModel_user = new ChatModel(msg, USER_KEY);
chatModelArrayList.add(chatModel_user);
messageAdapter.notifyDataSetChanged();
String url = "MY_API_URL"+msg;
String BASE_URL = "http://api.brainshop.ai/";
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
apIservice = retrofit.create(APIservice.class);
Call<MessageModel> call = apIservice.getMessage(url);
call.enqueue(new Callback<MessageModel>() {
#Override
public void onResponse(Call<MessageModel> call, Response<MessageModel> response) {
if(response.isSuccessful()){
MessageModel model = response.body();
chatModelArrayList.add(new ChatModel(model.getCnt(), BOT_KEY));
messageAdapter.notifyDataSetChanged();
}else{
Toast.makeText(MainActivity.this, "Some error on our side", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<MessageModel> call, Throwable t) {
chatModelArrayList.add(new ChatModel("Please revert your query", BOT_KEY));
messageAdapter.notifyDataSetChanged();
}
});
}
}
The InputConnection is overwhelmed by requests to clear the text. I tried modifying the code to check for text length before trying to clear it:
if (editText.length() > 0) {
editText.setText(null);
}
This helps mitigate the problem in that pressing the send button rapidly no longer causes the stream of InputConnectionWrapper warnings. However, this is still prone to problems when the user rapidly pressing the send button when the app is under sufficient load, etc.
There's another way to clear text: Editable.clear(). with this I don't get warnings at all:
(like getExtractedText on inactive InputConnection)
try this:
if (editText.length() > 0) {
editText.getText().clear();
}
Note that should you wish to clear all input state and not just the text (autotext, autocap, multitap, undo), you can use TextKeyListener.clear(Editable e).
if (editText.length() > 0) {
TextKeyListener.clear(editText.getText());
}
This is such a basic issue that I am not sure what I could possibly be doing wrong. Sinch is not starting for me and I don't know why. I don't have enough experience with Sinch to diagnose why a basic command is not doing what it is supposed to do. Here's what I have:
I am trying to start and making the call from the Calling.java class. The code is as follows:
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.sinch.android.rtc.calling.Call;
import com.squareup.picasso.Picasso;
import static android.content.Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP;
public class Calling extends CallActivity {
private String calleeID;
private TextView serviceName;
Bundle callDetails;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calling);
callDetails = getIntent().getBundleExtra("callDetails");
//Setup end button
Button endCallButton = findViewById(R.id.endcall);
endCallButton.setOnClickListener(v -> endCall());
}
private void endCall() {
if (getSinchServiceInterface() != null) {
getSinchServiceInterface().stopClient();
}
finishActivity(FLAG_ACTIVITY_PREVIOUS_IS_TOP);
finish();
}
// invoked when the connection with SinchServer is established
#Override
protected void onServiceConnected() {
//Setup Calling Screen
ImageView avatar = findViewById(R.id.dialingAvatar);
Picasso.get().load(callDetails.getString("Logo")).into(avatar);
TextView midScreenName = findViewById(R.id.memberName);
midScreenName.setText(callDetails.getString("Name"));
serviceName = findViewById(R.id.serviceName);
serviceName.setText(callDetails.getString("Service"));
TextView ratings = findViewById(R.id.rating);
ratings.setText(callDetails.getString("Rating") + " ★");
//Get CallerID and CalleeID
calleeID = callDetails.getString("CalleeID");
//Start sinch Service
if(!getSinchServiceInterface().isStarted()){
getSinchServiceInterface().startClient(callDetails.getString("CallerID"));
Call call = getSinchServiceInterface().callUserVideo(calleeID);
Intent callServiceScreen = new Intent(this, ServiceCallActivity.class);
callDetails.putString(SinchService.CALL_ID, call.getCallId());
callServiceScreen.putExtra("Call Details", callDetails);
startActivity(callServiceScreen);
}
}
#Override
public void onDestroy() {
if (getSinchServiceInterface() != null) {
getSinchServiceInterface().stopClient();
}
super.onDestroy();
}
}
I am coming to Calling.java from Precall.java the code for that is:
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.sinch.android.rtc.SinchError;
import com.squareup.picasso.Picasso;
import org.json.JSONObject;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class precall extends CallActivity implements SinchService.StartFailedListener {
private Bundle memberDetails;
private String url;
private Button cancel;
private Button call;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_precall);
//url
url = apiCallPoints.userInfo;
//Set Member Text
memberDetails = getIntent().getBundleExtra("Member");
//Populate screen
ImageView avatar = findViewById(R.id.avatar);
Picasso.get().load(memberDetails.getString("Logo")).into(avatar);
TextView memberName = findViewById(R.id.membername);
memberName.setText(memberDetails.getString("Name"));
TextView rating = findViewById(R.id.rating);
rating.setText(memberDetails.getString("Rating") + " ★");
TextView serviceName = findViewById(R.id.servicename);
serviceName.setText(memberDetails.getString("Service"));
TextView overview = findViewById(R.id.overview);
overview.setText(memberDetails.getString("Overview"));
//Add button clicks
cancel = findViewById(R.id.cancel_button);
cancel.setOnClickListener(view -> finish());
cancel.setEnabled(false);
call = findViewById(R.id.yes_button);
call.setOnClickListener(view -> {
goToCalling();
});
call.setEnabled(false);
setHomeBar();
}
//this method is invoked when the connection is established with the SinchService
#Override
protected void onServiceConnected() {
call.setEnabled(true);
cancel.setEnabled(true);
getSinchServiceInterface().setStartListener(this);
}
#Override
protected void onPause() {
super.onPause();
}
#Override
public void onStartFailed(SinchError error) {
}
//Invoked when just after the service is connected with Sinch
#Override
public void onStarted() {
}
private void goToCalling() {
//Async search
CallBackendSync callBackendSync = new CallBackendSync();
Object [] params = {url, memberDetails};
callBackendSync.execute(params);
}
private void setHomeBar() {
final Button home = findViewById(R.id.home_button);
home.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Code here executes on main thread after user presses button
startActivity(new Intent(precall.this, SecondActivity.class));
}
});
final Button favourites = findViewById(R.id.star_button);
favourites.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Code here executes on main thread after user presses button
startActivity(new Intent(precall.this, Favourite_Page.class));
}
});
final Button profile_page = findViewById(R.id.person_button);
profile_page.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Code here executes on main thread after user presses button
startActivity(new Intent(getApplicationContext(), Profile.class));
}
});
final Button notifications = findViewById(R.id.notification_button);
notifications.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Code here executes on main thread after user presses button
startActivity(new Intent(precall.this, Notification_Page.class));
}
});
final Button service = findViewById(R.id.service_button);
service.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Code here executes on main thread after user presses button
startActivity(new Intent(precall.this, services.class));
}
});
}
class CallBackendSync extends AsyncTask {
OkHttpClient client = new OkHttpClient();
#Override
protected Object doInBackground(Object [] objects) {
String url = (String) objects[0];
Bundle memberDetails = (Bundle) objects[1];
//Get access token from shared preference
isLoggedIn loggedIn = new isLoggedIn(getApplicationContext());
String token = loggedIn.getToken();
if(token != null){
//Create request
Request request = new Request.Builder()
.url(url)
.addHeader("Authorization", "Bearer " + token)
.addHeader("Accept", "application/json")
.build();
try {
Response response = client.newCall(request).execute();
JSONObject results = new JSONObject(response.body().string());
String UserID = results.getString("UserId");
memberDetails.putString("CallerID", UserID);
Intent callIntent = new Intent(precall.this, Calling.class);
callIntent.putExtra("callDetails", memberDetails);
startActivity(callIntent);
return results;
}catch (Exception e){
e.printStackTrace();
}
} else {
startActivity(new Intent(precall.this, Login_page.class));
}
return null;
}
protected void onPostExecute(String s){
super.onPostExecute(s);
}
}
}
The failure is happening in SinchService.java
import com.sinch.android.rtc.AudioController;
import com.sinch.android.rtc.ClientRegistration;
import com.sinch.android.rtc.Sinch;
import com.sinch.android.rtc.SinchClient;
import com.sinch.android.rtc.SinchClientListener;
import com.sinch.android.rtc.SinchError;
import com.sinch.android.rtc.video.VideoController;
import com.sinch.android.rtc.calling.Call;
import com.sinch.android.rtc.calling.CallClient;
import com.sinch.android.rtc.calling.CallClientListener;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
public class SinchService extends Service {
private static final String APP_KEY = "is correct";
private static final String APP_SECRET = "is correct";
//private static final String ENVIRONMENT = "clientapi.sinch.com";
private static final String ENVIRONMENT = "sandbox.sinch.com";
public static final String CALL_ID = "CALL_ID";
static final String TAG = SinchService.class.getSimpleName();
private SinchServiceInterface mSinchServiceInterface = new SinchServiceInterface();
private SinchClient mSinchClient = null;
private String mUserId = "";
private StartFailedListener mListener;
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onDestroy() {
if(mSinchClient != null){
mSinchClient.terminate();
}
super.onDestroy();
}
private void start(String userName) {
mUserId = userName;
mSinchClient = Sinch.getSinchClientBuilder().context(getApplicationContext())
.applicationKey(APP_KEY)
.applicationSecret(APP_SECRET)
.environmentHost(ENVIRONMENT)
.userId(userName)
.enableVideoCalls(true)
.build();
mSinchClient.setSupportCalling(true);
mSinchClient.startListeningOnActiveConnection();
mSinchClient.addSinchClientListener(new MySinchClientListener());
mSinchClient.getCallClient().addCallClientListener(new SinchCallClientListener());
mSinchClient.checkManifest();
mSinchClient.start();
System.out.println("Is started: " + mSinchClient.isStarted());
}
private void stop() {
if(mSinchClient != null){
mSinchClient.terminate();
}
}
private boolean isStarted() {
if(mSinchClient != null){
return mSinchClient.isStarted();
} else {
return false;
}
}
#Override
public IBinder onBind(Intent intent) {
return mSinchServiceInterface;
}
public class SinchServiceInterface extends Binder {
public Call callUserVideo(String userId) {
return mSinchClient.getCallClient().callUserVideo(userId);
}
public String getUserName() {
return mUserId;
}
public boolean isStarted() {
return SinchService.this.isStarted();
}
public void startClient(String userName) {
start(userName);
}
public void stopClient() {
stop();
}
public void setStartListener(StartFailedListener listener) {
mListener = listener;
}
public Call getCall(String callId) {
return mSinchClient.getCallClient().getCall(callId);
}
public VideoController getVideoController() {
return mSinchClient.getVideoController();
}
public AudioController getAudioController() {
return mSinchClient.getAudioController();
}
}
public interface StartFailedListener {
void onStartFailed(SinchError error);
void onStarted();
}
private class MySinchClientListener implements SinchClientListener {
#Override
public void onClientFailed(SinchClient client, SinchError error) {
if (mListener != null) {
mListener.onStartFailed(error);
}
mSinchClient.terminate();
mSinchClient = null;
}
#Override
public void onClientStarted(SinchClient client) {
Log.d(TAG, "SinchClient started");
if (mListener != null) {
mListener.onStarted();
}
}
#Override
public void onClientStopped(SinchClient client) {
Log.d(TAG, "SinchClient stopped");
}
#Override
public void onLogMessage(int level, String area, String message) {
switch (level) {
case Log.DEBUG:
Log.d(area, message);
break;
case Log.ERROR:
Log.e(area, message);
break;
case Log.INFO:
Log.i(area, message);
break;
case Log.VERBOSE:
Log.v(area, message);
break;
case Log.WARN:
Log.w(area, message);
break;
}
}
#Override
public void onRegistrationCredentialsRequired(SinchClient client,
ClientRegistration clientRegistration) {
}
}
private class SinchCallClientListener implements CallClientListener {
#Override
public void onIncomingCall(CallClient callClient, Call call) {
Log.d(TAG, "Incoming call");
Intent intent = new Intent(SinchService.this, Calling.class);
intent.putExtra(CALL_ID, call.getCallId());
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
SinchService.this.startActivity(intent);
}
}
}
And the base activity is CallActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.sinch.android.rtc.calling.Call;
import com.squareup.picasso.Picasso;
import static android.content.Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP;
public class Calling extends CallActivity {
private String calleeID;
private TextView serviceName;
Bundle callDetails;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calling);
callDetails = getIntent().getBundleExtra("callDetails");
//Setup end button
Button endCallButton = findViewById(R.id.endcall);
endCallButton.setOnClickListener(v -> endCall());
}
private void endCall() {
if (getSinchServiceInterface() != null) {
getSinchServiceInterface().stopClient();
}
finishActivity(FLAG_ACTIVITY_PREVIOUS_IS_TOP);
finish();
}
// invoked when the connection with SinchServer is established
#Override
protected void onServiceConnected() {
//Setup Calling Screen
ImageView avatar = findViewById(R.id.dialingAvatar);
Picasso.get().load(callDetails.getString("Logo")).into(avatar);
TextView midScreenName = findViewById(R.id.memberName);
midScreenName.setText(callDetails.getString("Name"));
serviceName = findViewById(R.id.serviceName);
serviceName.setText(callDetails.getString("Service"));
TextView ratings = findViewById(R.id.rating);
ratings.setText(callDetails.getString("Rating") + " ★");
//Get CallerID and CalleeID
calleeID = callDetails.getString("CalleeID");
//Start sinch Service
if(!getSinchServiceInterface().isStarted()){
getSinchServiceInterface().startClient(callDetails.getString("CallerID"));
Call call = getSinchServiceInterface().callUserVideo(calleeID);
Intent callServiceScreen = new Intent(this, ServiceCallActivity.class);
callDetails.putString(SinchService.CALL_ID, call.getCallId());
callServiceScreen.putExtra("Call Details", callDetails);
startActivity(callServiceScreen);
}
}
#Override
public void onDestroy() {
if (getSinchServiceInterface() != null) {
getSinchServiceInterface().stopClient();
}
super.onDestroy();
}
}
I have been banging my head against this but I cannot figure out what's wrong. I sure it's something stupid and obvious that I can't see because I am too close to the code. But any ideas you guys have would be very helpful!
It looks like you are not waiting for it to start before you try to make a call. We recommend to start the service when the app starts. If you dont do that you need to wait or the onStarted event in the service for fire
I am trying to make the EditTextLayout makes an error message when they are empty and the app crashes
import android.app.ProgressDialog;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.design.widget.TextInputEditText;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
public class LoginActivity extends AppCompatActivity {
private TextInputLayout textInputEmail , textInputPassword;
private Button login;
String emailInput , passwordInput;
private FirebaseAuth auth;
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
auth = FirebaseAuth.getInstance();
textInputEmail = (TextInputLayout) findViewById(R.id.login_email);
textInputPassword = (TextInputLayout) findViewById(R.id.login_password);
login = (Button)findViewById(R.id.login_button);
progressDialog = new ProgressDialog(this);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ConfirmInput();
progressDialog.setTitle("Singing in");
progressDialog.setMessage("Please wait while we sign you in");
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.show();
auth.signInWithEmailAndPassword(emailInput , passwordInput).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
progressDialog.dismiss();
Toast.makeText(LoginActivity.this, "Account Created successfuly", Toast.LENGTH_SHORT).show();
SendUserToMainActivity();
}else{
progressDialog.dismiss();
Toast.makeText(LoginActivity.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
});
}
private void SendUserToMainActivity() {
Intent intent = new Intent(LoginActivity.this , MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
public boolean ValidateEmail(){
emailInput = textInputEmail.getEditText().getText().toString().trim();
if(emailInput.isEmpty()){
textInputEmail.setError("You Can't leave this Empty!");
return false;
}else{
textInputEmail.setError(null);
return true;
}
}
public boolean ValidatePassword(){
passwordInput = textInputPassword.getEditText().getText().toString();
if(passwordInput.isEmpty()){
textInputPassword.setError("You Can't leave this Empty!");
return false;
}else{
textInputPassword.setError(null);
return true;
}
}
public void ConfirmInput(){
if(!ValidateEmail() | !ValidatePassword()){
return;
}
}
}
java.lang.IllegalArgumentException: Given String is empty or null
at com.google.android.gms.common.internal.zzbq.zzgm(Unknown Source)
at com.google.firebase.auth.FirebaseAuth.signInWithEmailAndPassword(Unknown Source)
at com.example.bestever.snapchatclone.LoginActivity$1.onClick(LoginActivity.java:50)
at android.view.View.performClick(View.java:5184)
at android.view.View$PerformClick.run(View.java:20893)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5938)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)
I tried also to change The TextInputLayout to TextInputEditText and nothing changed. I also tried to change my approach for checking if the TextInputLayout is empty, but it doesn't work
You should validate if textInputEmail.getEditText().getText() is null before retrieving the text from it, that might be the problem. Hope it works.
You can't call getText() function on null String.
Please use this method to implement it in the right way:
String emailInput;
emailInput = textInputEmail.getEditText().getText();
if (emailInput != null) {
emailInput = emailInput.toString().trim();
}
Or (My favorite way)
String emailInput = "";
try {
emailInput = textInputEmail.getEditText().getText().toString().trim();
} catch (IllegalArgumentException ex) { }
I have a login screen that take the username and password from user and validate it in the backend. Code i have written so far is below
package com.example.opinion;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import java.util.Map;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.Body;
import retrofit2.http.POST;
public class Login extends Activity {
private Button login;
private Button reg;
private EditText uname;
private EditText pword;
public static final String BASE_URL = "http://192.168.0.105/";
public interface LoginApi{
#POST("login")
Call<HttpBinResponse> userLogin(#Body LoginData data);
}
static class HttpBinResponse {
String result;
}
public class LoginData {
String username;
String password;
public LoginData(String uname, String pword) {
this.username = uname;
this.password = pword;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
login =(Button) findViewById(R.id.btnlogin);
reg =(Button) findViewById(R.id.btnregister);
uname = (EditText)findViewById(R.id.uname);
pword = (EditText)findViewById(R.id.pass);
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String name = uname.getText().toString();
String pass = pword.getText().toString();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
LoginData user = new LoginData(name, pass);
System.out.println(user.username+user.password);
LoginApi apiService = retrofit.create(LoginApi.class);
Call<HttpBinResponse> call = apiService.userLogin(user);
call.enqueue(new Callback<HttpBinResponse>() {
#Override
public void onResponse(Call<HttpBinResponse> call, Response<HttpBinResponse> response) {
int statusCode = response.code();
HttpBinResponse decodedResponse = response.body();
if (decodedResponse == null)
return;
// at this point the JSON body has been successfully parsed
System.out.println(decodedResponse.result);
}
#Override
public void onFailure(Call<HttpBinResponse> call, Throwable t) {
}
});
Intent it= new Intent(Login.this, Home.class);
startActivity(it);
}
});
reg.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent it = new Intent(Login.this, Registration.class);
startActivity(it);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.login, menu);
return true;
}
}
In the above code LoginData class is used to attach the body for my post request.
HttpBinResponse class is for getting the response and store it in the result attribute. But i checked that my code is not returning any thing as the decodedResponse.result is null.
see this:
05-30 11:35:59.186 31176-31194/? I/OpenGLRenderer﹕ Initialized EGL,
version 1.4 05-30 11:36:08.783 31176-31176/com.example.opinion
I/System.out﹕ hkbffghjk 05-30 11:36:08.877
31176-31176/com.example.opinion I/System.out﹕ null
instead of null it should be a json object with key as result and its value.
Can anyone tell me how to get the proper response.
it seems like the url i'm creating is not created properly, either the body of the post request is not getting attached or some other problem.
i checked my sever logs and found that the request is reaching the server but nothing happens after that.
Ok,
I'm doing this for 4 straight hours. And the facebook Login still doesn't work. The session state is always OPENING. ALWAYS. onActivityResult NEVER gets called. The key in the developer console is correct, the starting class is correct, and this is my code
package XXXXX
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import ua.org.zasadnyy.zvalidations.Field;
import ua.org.zasadnyy.zvalidations.Form;
import ua.org.zasadnyy.zvalidations.validations.HasMinimumLength;
import ua.org.zasadnyy.zvalidations.validations.IsEmail;
import ua.org.zasadnyy.zvalidations.validations.NotEmpty;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.Signature;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Base64;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphUser;
import com.facebook.widget.LoginButton;
public class SplashScreen extends FragmentActivity {
public static String TAG = "SplashScreen";
/**
* LoginActivity
*/
private static final int LOGIN = 0;
private static final int SIGNUP = 1;
private static final int SELECTUSERNAME = 2;
private static final int FRAGMENT_COUNT = SELECTUSERNAME +1;
private boolean isResumed = false;
private Fragment[] fragments = new Fragment[FRAGMENT_COUNT];
private MenuItem settings;
private UiLifecycleHelper uiHelper;
private Session.StatusCallback callback =
new Session.StatusCallback() {
#Override
public void call(Session session,
SessionState state, Exception exception) {
onSessionStateChange(session, state, exception);
}
};
/**
* UI Elements
*/
Button btn_signUp;
Button btn_signUpSubmit;
LoginButton btn_facebookAuth;
//Edit Text
EditText edittextEmail;
EditText edittextPassword;
//Form
Form signUpForm;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i(TAG, "onCreate");
uiHelper = new UiLifecycleHelper(this, callback);
uiHelper.onCreate(savedInstanceState);
setContentView(R.layout.splash);
FragmentManager fm = getSupportFragmentManager();
fragments[LOGIN] = fm.findFragmentById(R.id.loginFragment);
fragments[SIGNUP] = fm.findFragmentById(R.id.signUpFragment);
fragments[SELECTUSERNAME] = fm.findFragmentById(R.id.selectUserNameFragment);
FragmentTransaction transaction = fm.beginTransaction();
for(int i = 0; i < fragments.length; i++) {
transaction.hide(fragments[i]);
}
transaction.commit();
btn_signUp = ( Button ) findViewById(R.id.btn_signUpMail);
btn_signUp.setOnClickListener( listener_btn_signUp );
btn_signUpSubmit = (Button) findViewById(R.id.btn_signUpSubmit);
btn_signUpSubmit.setOnClickListener(listener_btn_signUpSubmit);
edittextEmail = (EditText)findViewById(R.id.et_signUpMail);
edittextPassword = (EditText)findViewById(R.id.et_signUpPw);
signUpForm = new Form ( this );
signUpForm.addField(Field.using(edittextEmail).validate(NotEmpty.build(this.getApplicationContext())).validate(IsEmail.build(this.getApplicationContext())));
signUpForm.addField(Field.using(edittextPassword).validate(NotEmpty.build(this.getApplicationContext())).validate(HasMinimumLength.build(this.getApplicationContext(), 8)));
btn_facebookAuth = (LoginButton)findViewById(R.id.login_button);
btn_facebookAuth.setReadPermissions(Arrays.asList("email"));
}
private OnClickListener listener_btn_signUp = new OnClickListener() {
#Override
public void onClick(View v) {
showFragment(SIGNUP, true);
}
};
private OnClickListener listener_btn_signUpSubmit = new OnClickListener() {
#Override
public void onClick(View v) {
if (signUpForm.isValid()) {
Log.i("SignupFragment", "Form is valid");
// User userModel = new User();
// userModel.isFacebookConnected = "0";
// userModel.userEmail = edittextEmail.getText().toString();
// userModel.userPassword = edittextPassword.getText().toString();
// SelectUserNameFragment selectUserNameFragment = new SelectUserNameFragment();
// SelectUserNameFragment.user = userModel;
// getFragmentManager()
// .beginTransaction()
// .replace(android.R.id.content, selectUserNameFragment)
// .addToBackStack("")
// .commit();
} else {
Log.i("SignupFragment", "Form not valid");
}
}
};
private void showFragment(int fragmentIndex, boolean addToBackStack) {
Log.i(TAG, "showFragment");
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction transaction = fm.beginTransaction();
for (int i = 0; i < fragments.length; i++) {
if (i == fragmentIndex) {
transaction.show(fragments[i]);
} else {
transaction.hide(fragments[i]);
}
}
if (addToBackStack) {
transaction.addToBackStack(null);
}
transaction.commit();
}
private void onSessionStateChange(Session session, SessionState state, Exception exception) {
Log.i(TAG, "onSessionStateChange");
FragmentManager manager = getSupportFragmentManager();
int backStackSize = manager.getBackStackEntryCount();
for (int i = 0; i < backStackSize; i++) {
manager.popBackStack();
}
System.out.println ( state.name() );
if (state.isOpened()) {
Request.newMeRequest(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
try {
User userModel = new User();
userModel.facebookId = user.getId();
Map<String, String> where = new HashMap<String, String>();
where.put("where", "WHERE facebookId='" + user.getId() + "'" );
userModel.loadModelFrom(where);
if ( userModel.userData.isEmpty() ) {
userModel.isFacebookConnected = "1";
userModel.userEmail = user.asMap().get("email").toString();
SelectUserNameFragment.user = userModel;
showFragment(SELECTUSERNAME, true);
} else {
Intent intent = new Intent ( getApplicationContext(), DashboardActivity.class );
intent.putExtra("User", userModel);
startActivity(intent);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}).executeAsync();
// showFragment(DASHBOARD, false);
} else if (state.isClosed()) {
showFragment(LOGIN, false);
}
}
#Override
protected void onResumeFragments() {
super.onResumeFragments();
Log.i(TAG, "onResumeFragments");
Session session = Session.getActiveSession();
if (session != null && session.isOpened()) {
Intent intent = new Intent ( this, DashboardActivity.class );
intent.putExtra("Session", session);
startActivity(intent);
} else {
showFragment(LOGIN, false);
}
}
#Override
public void onResume() {
super.onResume();
Log.i(TAG, "onResume");
uiHelper.onResume();
isResumed = true;
}
#Override
public void onPause() {
super.onPause();
Log.i(TAG, "onPause");
uiHelper.onPause();
isResumed = false;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.i(TAG, "onActivityResult");
super.onActivityResult(requestCode, resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onDestroy() {
super.onDestroy();
Log.i(TAG, "onDestroy");
uiHelper.onDestroy();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Log.i(TAG, "onSaveInstanceState");
uiHelper.onSaveInstanceState(outState);
}
}
What did I forget?
Apparently it is not allowed to have
android:noHistory="true" in your manifest. I removed it and now it works.