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.
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
package com.quickblox.q_municate.ui.activities.authorization;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.SwitchCompat;
import android.view.MenuItem;
import android.view.View;
import com.quickblox.auth.session.QBSessionManager;
import com.quickblox.q_municate.R;
import com.quickblox.q_municate.ui.activities.forgotpassword.ForgotPasswordActivity;
import com.quickblox.q_municate.utils.KeyboardUtils;
import com.quickblox.q_municate.utils.ValidationUtils;
import com.quickblox.q_municate_core.models.AppSession;
import com.quickblox.q_municate_core.models.LoginType;
import com.quickblox.q_municate_db.managers.DataManager;
import com.quickblox.q_municate_user_service.model.QMUser;
import butterknife.Bind;
import butterknife.OnCheckedChanged;
import butterknife.OnClick;
public class LoginActivity extends BaseAuthActivity {
#Bind(R.id.remember_me_switch)
SwitchCompat rememberMeSwitch;
public static void start(Context context) {
Intent intent = new Intent(context, LoginActivity.class);
context.startActivity(intent);
}
#Override
protected int getContentResId() {
return R.layout.activity_login;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initFields(savedInstanceState);
setUpActionBarWithUpButton();
}
#OnClick(R.id.login_email_button)
void loginQB(View view) {
if (checkNetworkAvailableWithError()) {
login();
}
}
#OnClick(R.id.facebook_connect_button)
void loginFB(View view) {
if (checkNetworkAvailableWithError()) {
loginType = LoginType.FACEBOOK;
startSocialLogin();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
startLandingScreen();
break;
default:
super.onOptionsItemSelected(item);
}
return true;
}
#Override
public void onBackPressed() {
startLandingScreen();
}
#OnCheckedChanged(R.id.remember_me_switch)
void rememberMeCheckedChanged(boolean checked) {
appSharedHelper.saveSavedRememberMe(checked);
}
#OnClick(R.id.forgot_password_textview)
void forgotPassword(View view) {
ForgotPasswordActivity.start(this);
}
private void initFields(Bundle bundle) {
title = getString(R.string.auth_login_title);
rememberMeSwitch.setChecked(true);
}
private void login() {
KeyboardUtils.hideKeyboard(this);
loginType = LoginType.EMAIL;
String userEmail = emailEditText.getText().toString();
String userPassword = passwordEditText.getText().toString();
if (new ValidationUtils(this).isLoginDataValid(emailTextInputLayout, passwordTextInputLayout,
userEmail, userPassword)) {
showProgress();
boolean ownerUser = QBSessionManager.getInstance().getSessionParameters() != null && userEmail.equals(QBSessionManager.getInstance().getSessionParameters().getUserEmail());
if (!ownerUser) {
DataManager.getInstance().clearAllTables();
}
login(userEmail, userPassword);
}
}
}
I modified Q-municate powered by QuickBlox (which is open source) GitHub code. But, in this app code (when i try to login from two step Authentication by firebase he login successfully. But whenever i open app again after sometime like half an hour, the Q-Municate app again comes on first splash page of app and start again procedure. It means when i login first time successfully by mobile number then why each time take from first step whenever i open the application of Q-Municate. How i can solve this issue.
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?
I'm using shared preference to store user data, and in my start screen, I want to check whether username has already logged in or not, when user is still not logged out yet it will redirect to UserView.java when the application starts, otherwise it will go to LoginActivity.java
I've used these tutorial as my references :
Android Hive Tutorial Shared Pref, and
Android example tutorial Shared Pref..
but when I exit my activity without logging out, next time I open my application it's status is logged out (its like the session has ended although I have not logged out yet from my application),,
What should I do to fix this thing, so whenever I exit my application (without logging out) my data is still there in shared pref and will be redirected to UserView.java, Am i making any mistakes with my codes?
These are my code:
userSessionManager.java
package com.thesis.teamizer;
import java.util.HashMap;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
public class userSessionManager {
// Shared Preferences Reference
SharedPreferences CurrentSession;
// Editor Reference for Editing Shared Preferences
Editor editor;
// Context Reference
Context _context;
// Shared pref mode
int PRIVATE_MODE = 0;
// Sharef Preferences Name
public static String PrefName = "MyUsername";
// All Shared Preferences Keys
private static final String IS_USER_LOGIN = "IsUserLoggedIn";
// User name (make variable public to access from outside)
public static final String KEY_USERNAME = "username";
// Constructor
public userSessionManager(Context context) {
this._context = context;
CurrentSession = _context.getSharedPreferences(PrefName, PRIVATE_MODE);
editor = CurrentSession.edit();
}
public void createUserLogin(String username) {
// User has already login
editor.putBoolean(IS_USER_LOGIN, true);
// Storing username in pref
editor.putString(KEY_USERNAME, username);
// Editor ready to execute the previous codes
editor.commit();
}
public boolean checkLogin() {
// Check login status. If the user is not logged in
if (!this.isUserLoggedIn()) {
return true;
}
return false;
}
// Read session using hashmap
public HashMap<String, String> getUserDetails() {
// Use hashmap to store user credentials
HashMap<String, String> user = new HashMap<String, String>();
// user name
user.put(KEY_USERNAME, CurrentSession.getString(KEY_USERNAME, null));
// return user
return user;
}
public void logOut() {
// clearing all data from Shared pref
editor.remove(KEY_USERNAME);
editor.clear();
editor.commit();
}
// Will check if the user is Login or not by getting the boolean of
// IS_USER_LOGIN from CurrentSession(pref)
private boolean isUserLoggedIn() {
// TODO Auto-generated method stub
return CurrentSession.getBoolean(IS_USER_LOGIN, false);
}
}
LoginActivity.java
package com.thesis.teamizer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class LoginActivity extends Activity implements View.OnClickListener {
private EditText etUsername;
private EditText etPassword;
private Button bLogin, bRegis, bAdmin;
userSessionManager session;
String loginUrl;
JSONParser jsonParser = new JSONParser();
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
private ProgressDialog pDialog;
String Username;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.login_screen);
Declaration();
bLogin.setOnClickListener(this);
bRegis.setOnClickListener(this);
bAdmin.setOnClickListener(this);
if (session.checkLogin()) {
Intent intent = new Intent("com.thesis.teamizer.USERVIEW");
finish();
startActivity(intent);
}
}
private void Declaration() {
// TODO Auto-generated method stub
etUsername = (EditText) findViewById(R.id.etLoginUsername);
etPassword = (EditText) findViewById(R.id.etLoginPassword);
bLogin = (Button) findViewById(R.id.bLogin);
bRegis = (Button) findViewById(R.id.bRegister);
bAdmin = (Button) findViewById(R.id.bAdminadmin);
session = new userSessionManager(getApplicationContext());
HashMap<String, String> user = session.getUserDetails();
Username = user.get(userSessionManager.KEY_USERNAME);
myIP ip = new myIP();
String myIp = ip.getIp();
String thisPhp = "doLogin.php";
loginUrl = myIp + thisPhp;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.bLogin:
new AttemptLogin().execute();
break;
case R.id.bRegister:
Intent i = new Intent("com.thesis.teamizer.REGISTRATIONACTIVITY");
startActivity(i);
break;
}
class AttemptLogin extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(LoginActivity.this);
pDialog.setMessage("Attempting login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String username = etUsername.getText().toString();
String password = etPassword.getText().toString();
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
Log.d("request!", "starting");
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(loginUrl, "POST",
params);
// check your log for json response
Log.d("Login attempt", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Login Successful!", json.toString());
String currentLoginUsername = username;
session.createUserLogin(currentLoginUsername);
Intent intent = new Intent("com.thesis.teamizer.USERVIEW");
finish();
startActivity(intent);
String sukses = "Sukses login";
return sukses;
} else if (success == 0) {
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
Toast.makeText(getApplicationContext(), file_url,
Toast.LENGTH_SHORT).show();
}
}
}
UserView.java
package com.thesis.teamizer;
import java.util.HashMap;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class UserView extends Activity implements View.OnClickListener {
public Button createGr, viewGr, createAn, viewAn, notification, logout,
calendar, createEvent, myEvent, createTask, myTask;
public String Username;
userSessionManager session;
Intent i;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.user_view);
sessionAndDeclaration();
createGr.setOnClickListener(this);
viewGr.setOnClickListener(this);
createAn.setOnClickListener(this);
viewAn.setOnClickListener(this);
notification.setOnClickListener(this);
logout.setOnClickListener(this);
createEvent.setOnClickListener(this);
calendar.setOnClickListener(this);
myEvent.setOnClickListener(this);
createTask.setOnClickListener(this);
myTask.setOnClickListener(this);
}
private void sessionAndDeclaration() {
// TODO Auto-generated method stub
session = new userSessionManager(getApplicationContext());
HashMap<String, String> user = session.getUserDetails();
// get name
Username = user.get(userSessionManager.KEY_USERNAME);
TextView a = (TextView) findViewById(R.id.tvUserVUsername);
a.setText(Username);
createGr = (Button) findViewById(R.id.bCreateGroup);
viewGr = (Button) findViewById(R.id.bViewMyGroup);
createAn = (Button) findViewById(R.id.bCreateAnnouncement);
viewAn = (Button) findViewById(R.id.bViewMyAnnouncement);
notification = (Button) findViewById(R.id.bNotification);
logout = (Button) findViewById(R.id.bDoLogout);
calendar = (Button) findViewById(R.id.bGoToMyCalendar);
createEvent = (Button) findViewById(R.id.bCreateEvent);
myEvent = (Button) findViewById(R.id.bGoToMyEvent);
createTask = (Button) findViewById(R.id.bGoToCreateTask);
myTask = (Button) findViewById(R.id.bGoToMyTask);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.bCreateGroup:
i = new Intent("com.thesis.teamizer.CREATEGROUPACTIVITY");
startActivity(i);
break;
case R.id.bViewMyGroup:
i = new Intent("com.thesis.teamizer.MYGROUPACTIVITY");
startActivity(i);
break;
case R.id.bCreateAnnouncement:
i = new Intent("com.thesis.teamizer.CREATEANNOUNCEMENTACTIVITY");
startActivity(i);
break;
case R.id.bViewMyAnnouncement:
i = new Intent("com.thesis.teamizer.VIEWALLANNOUNCEMENT");
startActivity(i);
break;
case R.id.bNotification:
i = new Intent("com.thesis.teamizer.NOTIFICATION");
startActivity(i);
break;
case R.id.bDoLogout:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to Logout?")
.setCancelable(false)
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
finish();
session.logOut();
Intent i = new Intent(
"com.thesis.teamizer.LOGINACTIVITY");
// Closing all the Activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
startActivity(i);
finish();
}
})
.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
break;
case R.id.bGoToMyCalendar:
i = new Intent("com.thesis.teamizer.VIEWCALENDAR");
startActivity(i);
break;
case R.id.bCreateEvent:
i = new Intent("com.thesis.teamizer.CREATEEVENT");
startActivity(i);
break;
case R.id.bGoToMyEvent:
i = new Intent("com.thesis.teamizer.MYEVENT");
startActivity(i);
break;
case R.id.bGoToCreateTask:
i= new Intent("com.thesis.teamizer.CREATETASK");
startActivity(i);
break;
case R.id.bGoToMyTask:
i = new Intent("com.thesis.teamizer.MYTASK");
startActivity(i);
break;
}
}
}