Payment to this merchant is not allowed (invalid clientid) - java

I integrated Paypal in my android app in sandbox mode and everything worked perfectly fine. Now I switched to live mode and changed the client ID in my app as well.
Now this error is displayed when I tried to make a test purchase:
"Payment to this merchant is not allowed (invalid clientid)"
I don't know what to do. I changed the client id in every place from the sandbox id to the live id.
My class where Paypal is initialized when click on a button:
public class EssenActivity extends AppCompatActivity {
private static final String TAG = "Log Essen Activity";
private String kochuiD, preis, preis_ohne_euro, AnfragePortionenS, ungefahreAnkunftS, preisRe;
private EditText anzahlPortionen;
private TextView ungefähreAnkunft;
private Button essenBesätigenBtn;
private FirebaseFirestore firebaseFirestore;
private TextView preisRechner;
private FirebaseAuth mAuth;
public static final int PAYPAL_REQUEST_CODE = 7171;
private static PayPalConfiguration config = new PayPalConfiguration()
.environment(PayPalConfiguration.ENVIRONMENT_SANDBOX)
.clientId(Config.PAYPAL_CLIENT_ID);
private String amount, amountOhneEuro;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_essen);
essenBesätigenBtn = findViewById(R.id.essenBestätigen);
essenBesätigenBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
processPayment();
}
}
}
private void processPayment() {
amount = preisRechner.getText().toString();
amountOhneEuro = amount.replace("€", "");
PayPalPayment payPalPayment = new PayPalPayment(new BigDecimal(String.valueOf(amountOhneEuro)), "EUR",
"Bezahle das Essen", PayPalPayment.PAYMENT_INTENT_SALE);
Intent intent = new Intent(EssenActivity.this, PaymentActivity.class);
intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);
intent.putExtra(PaymentActivity.EXTRA_PAYMENT, payPalPayment);
startActivityForResult(intent, PAYPAL_REQUEST_CODE);
}
#Override
//
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (requestCode == PAYPAL_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
PaymentConfirmation confirmation = data.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION);
if (confirmation != null) {
try {
String paymentDetails = confirmation.toJSONObject().toString(4);
startActivity(new Intent(EssenActivity.this, PaymentDetails.class)
.putExtra("PaymentDetails", paymentDetails)
.putExtra("PaymentAmount", amountOhneEuro)
.putExtra("Koch Uid", kochuiD)
);
} catch (JSONException e) {
e.printStackTrace();
}
}
} else if (resultCode == Activity.RESULT_CANCELED) {
Log.d(TAG, "onActivityResult: wurde gecancelt");
}
} else if (resultCode == PaymentActivity.RESULT_EXTRAS_INVALID)
Toast.makeText(EssenActivity.this, "Ungültig", Toast.LENGTH_SHORT).show();
}
#Override
public void onDestroy() {
EssenActivity.this.stopService(new Intent(EssenActivity.this, PayPalService.class));
super.onDestroy();
}
}
My Config class:
public class Config {
public static final String PAYPAL_CLIENT_ID ="MY CLIENT ID";
}
My Paymentdetails class:
public class PaymentDetails extends AppCompatActivity {
private static final String TAG = "PAYMENT";
private TextView txtid, txtAmount, txtStatus;
private FirebaseFirestore firebaseFirestore;
private FirebaseAuth mAuth;
private DocumentReference docIdRef;
private String kochUid;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_payment_details);
txtid = findViewById(R.id.txtId);
txtAmount = findViewById(R.id.txtAmount);
txtStatus = findViewById(R.id.txtStatus);
Intent intent = getIntent();
try {
JSONObject jsonObject = new JSONObject(intent.getStringExtra("PaymentDetails"));
showDetails(jsonObject.getJSONObject("response"), intent.getStringExtra("PaymentAmount"));
} catch (JSONException e) {
e.printStackTrace();
}
}
private void showDetails(JSONObject response, String paymentAmount) {
try {
firebaseFirestore = FirebaseFirestore.getInstance();
mAuth = FirebaseAuth.getInstance();
String uid = mAuth.getCurrentUser().getUid();
if (response.getString("state").equals("approved")) {
DocumentReference documentReference = firebaseFirestore.collection("essen_aktiv_anfrage").document(uid);
Map<String, String> anfrageMap = new HashMap<>();
anfrageMap.put("Id", response.getString("id"));
anfrageMap.put("Status", response.getString("state"));
anfrageMap.put("Betrag", paymentAmount + "€");
//NEU
anfrageMap.put("Anfrage User", uid);
anfrageMap.put("Koch Uid", kochUid);
documentReference.set(anfrageMap, SetOptions.merge())
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Intent intent = new Intent(PaymentDetails.this, MainActivity.class);
intent.putExtra("Bezahlung war erfolgreich", "approved");
Toast.makeText(PaymentDetails.this, "Bezahlung war erfolgreich", Toast.LENGTH_SHORT).show();
startActivity(intent);
}
});
} else{
Toast.makeText(PaymentDetails.this, "Bezahlung war nicht erfolgreich", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Any help is appreciated. Thank you very much.

Authorization defaults to sandbox unless explicitly set to "live". It needs to be set within the PayPalConfiguration which is used in creation of the oAuth token, and the creation of the APIContext which is used to call the PayPal service.
I had been getting the same error within a live environment, despite it working in sandbox. It is therefore likely that you have missed something.

Change ENVIRONMENT_SANDBOX to ENVIRONMENT_PRODUCTION

Related

Firebase is not sending OTP code on my Phone number | Java | Android Studio

I'm trying to authenticate user with phone number using the firebase Authentication method. But it is showing me error after some time by running the code. And I think the sendVerificationCodeToUser() function is not working properly.
package com.example.foodapp;
import ...
public class PhoneVerification<phoneAuthProvider> extends AppCompatActivity {
String verificationCodeBySystem;
Button btn_verify;
EditText phoneenteredbyuser;
ProgressBar progressbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_phone_verification);
btn_verify = findViewById(R.id.btn_verify);
phoneenteredbyuser = findViewById(R.id.txt_otp);
progressbar = findViewById(R.id.progressbar);
progressbar.setVisibility(View.GONE);
String phoneNo = getIntent().getStringExtra("phone");
sendVerificationCodeToUser(phoneNo);
btn_verify.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String code= phoneenteredbyuser.toString();
if(code.isEmpty() || code.length()< 6){
phoneenteredbyuser.setError("Wrong OTP...");
phoneenteredbyuser.requestFocus();
return;
}
progressbar.setVisibility(View.VISIBLE);
verifyCode(code);
}
});
}
private void sendVerificationCodeToUser(String phoneNo) {
FirebaseAuth mAuth= FirebaseAuth.getInstance();
PhoneAuthOptions options =
PhoneAuthOptions.newBuilder(mAuth)
.setPhoneNumber("+92" + phoneNo) // Phone number to verify
.setTimeout(60L, TimeUnit.SECONDS) // Timeout and unit
.setActivity(this) // Activity (for callback binding)
.setCallbacks(mCallbacks) // OnVerificationStateChangedCallbacks
.build();
PhoneAuthProvider.verifyPhoneNumber(options);
}
private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override //Entering OTP by manual way
public void onCodeSent(#NonNull String s, #NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
verificationCodeBySystem = s;
}
#Override // Automatically Verifying the OTP by system.
public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
String code = phoneAuthCredential.getSmsCode();
if (code != null) {
progressbar.setVisibility(View.VISIBLE);
verifyCode(code);
}
}
#Override //In case of error this code will run.
public void onVerificationFailed(FirebaseException e) {
Toast.makeText(PhoneVerification.this, "Error Occured", Toast.LENGTH_SHORT).show();
}
};
private void verifyCode(String codeByUser) {
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationCodeBySystem, codeByUser);
signInUserByCredentials(credential);
}
private void signInUserByCredentials(PhoneAuthCredential credential) {
FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
firebaseAuth.signInWithCredential(credential)
.addOnCompleteListener(PhoneVerification.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Toast.makeText(PhoneVerification.this, "Your Account has been created successfully!", Toast.LENGTH_SHORT).show();
//Perform Your required action here to either let the user sign In or do something required
Intent intent = new Intent(getApplicationContext(), User_Home.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
} else {
Toast.makeText(PhoneVerification.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
}

Firebase Google Auth Error

Hello I have been working on an project of an android app so i used firebase android google authentication but when i launch app and login it works fine and after closing app and relaunching it app stucks on white screen please help im posting my file below
googleutil.java
public class GoogleUtil {
public static boolean getBooleanPreference(Context context, String key, boolean defaultValue) {
boolean value = defaultValue;
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
if (preferences != null) {
value = preferences.getBoolean(key, defaultValue);
}
return value;
}
public static boolean setBooleanPreference(Context context, String key, boolean value) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
if (preferences != null) {
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean(key, value);
return editor.commit();
}
return false;
}
}
google.java
public class Google {
private static final int RC_SIGN_IN = 10;
private GoogleApiClient mGoogleApiClient;
private FragmentActivity context;
private OnInfoLoginGoogleCallback mGoogleCallback;
public Google(FragmentActivity context, OnInfoLoginGoogleCallback mGoogleCallback) {
this.context = context;
this.mGoogleCallback = mGoogleCallback;
getConfigDefaultLogin();
}
private void getConfigDefaultLogin() {
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(context.getString(R.string.default_web_client_id))
// TODO: 25-05-2017 Check With JSON default_web_client_id !!! Important
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(context)
.enableAutoManage(context /* FragmentActivity */, new GoogleApiClient.OnConnectionFailedListener() {
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
mGoogleCallback.connectionFailedApiClient(connectionResult);
}
}).addApi(Auth.GOOGLE_SIGN_IN_API, gso).build();
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
if (result.isSuccess()) {
GoogleSignInAccount account = result.getSignInAccount();
firebaseAuthWithGoogle(account);
} else {
mGoogleCallback.loginFailed();
}
}
}
public void signIn() {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
context.startActivityForResult(signInIntent, RC_SIGN_IN);
}
private void firebaseAuthWithGoogle(final GoogleSignInAccount acct) {
FirebaseAuth auth = FirebaseAuth.getInstance();
AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
auth.signInWithCredential(credential).addOnCompleteListener(context, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful()) {
mGoogleCallback.loginFailed();
} else {
mGoogleCallback.getInfoLoginGoogle(acct);
}
}
});
}
public interface OnInfoLoginGoogleCallback {
void getInfoLoginGoogle(GoogleSignInAccount account);
void connectionFailedApiClient(ConnectionResult connectionResult);
void loginFailed();
}
}
and finally implement all these in main activiity
public class MainActivity extends AppCompatActivity implements View.OnClickListener, Google.OnInfoLoginGoogleCallback {
private static final String USER_ROOT = "User";
private static final String KEY_LOGIN = "Key_Login";
private Google mGoogleSign;
private ProgressBar mProgressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Window window = getWindow();
window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(Color.TRANSPARENT);
setContentView(R.layout.activity_main);
TextView server_load = (TextView) findViewById(R.id.secure_key);
server_load.setText("Server Secure " + Math.random() + " Key");
firstShow();
if (GoogleUtil.getBooleanPreference(this, KEY_LOGIN, false)) {
startActivity(new Intent(this, MainActivity.class));
finish();
}
initViews();
}
private void firstShow() {
SharedPreferences sharedPreferences = getSharedPreferences("app", MODE_PRIVATE);
if (sharedPreferences.getBoolean("isFirst", true)) {
Intent intent = new Intent(MainActivity.this, OnboardingActivity.class);
startActivity(intent);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("isFirst", false);
editor.apply();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mGoogleSign.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.sign_in_trigger:
signInGoogle();
break;
}
}
#Override
public void getInfoLoginGoogle(GoogleSignInAccount account) {
sendUserFirebase();
}
#Override
public void connectionFailedApiClient(ConnectionResult connectionResult) {
addProgressBar(false);
toast("Error Play Services COD" + connectionResult);
}
#Override
public void loginFailed() {
addProgressBar(false);
toast("Login Failed");
}
private void initViews() {
mGoogleSign = new Google(this, this);
Button mBtnGoogleplus = (Button) findViewById(R.id.sign_in_trigger);
mProgressBar = (ProgressBar) findViewById(R.id.sign_in_progress_bar);
mBtnGoogleplus.setOnClickListener(this);
}
private void signInGoogle() {
mGoogleSign.signIn();
addProgressBar(true);
}
private void toast(String mensage) {
Toast.makeText(this, mensage, Toast.LENGTH_LONG).show();
}
private void addProgressBar(boolean flag) {
mProgressBar.setVisibility(flag ? View.VISIBLE : View.GONE);
}
private void sendUserFirebase() {
DatabaseReference referenceUser = FirebaseDatabase.getInstance().getReference().child(USER_ROOT);
FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
if (firebaseUser != null) {
User user = new User();
user.setName(firebaseUser.getDisplayName());
user.setEmail(firebaseUser.getEmail());
user.setPhotoUrl(firebaseUser.getPhotoUrl() == null ? "default_uri" : firebaseUser.getPhotoUrl().toString());
user.setuId(firebaseUser.getUid());
referenceUser.child(firebaseUser.getUid()).setValue(user).addOnCompleteListener(this, new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
GoogleUtil.setBooleanPreference(MainActivity.this, KEY_LOGIN, true);
startActivity(new Intent(MainActivity.this, FeedActivity.class));
finish();
} else {
toast("Login Failed Send User, try again.");
}
addProgressBar(false);
}
});
}
}
}
and also i used User.java to send user email to database
User.java
public class User {
private String Name;
private String Email;
private String UID;
private String PhotoURL;
public User() {
}
public User(String name, String email, String uId, String photoUrl) {
this.Name = name;
this.Email = email;
this.UID = uId;
this.PhotoURL = photoUrl;
}
public String getName() {
return Name;
}
public void setName(String name) {
this.Name = name;
}
public String getEmail() {
return Email;
}
public void setEmail(String email) {
this.Email = email;
}
public String getuId() {
return UID;
}
public void setuId(String uId) {
this.UID = uId;
}
public String getPhotoUrl() {
return PhotoURL;
}
public void setPhotoUrl(String photoUrl) {
this.PhotoURL = photoUrl;
}
}
So much code.
As I understood, you need some silent log in in background.
Here You go:
OptionalPendingResult example:
// LogIN pending result
mGoogleApiClientPendingResult = Auth.GoogleSignInApi.silentSignIn(mGoogleApiClient);
if (mGoogleApiClientPendingResult.isDone()) {
// There's immediate result available.
// Handle you result here
handleSignInResult(mGoogleApiClientPendingResult.get());
} else {
// There's no immediate result ready, displays some progress indicator and waits for the
// async callback.
mGoogleApiClientPendingResult.setResultCallback(new ResultCallback<GoogleSignInResult>() {
#Override
public void onResult(#NonNull GoogleSignInResult result) {
// Handle you result here
handleSignInResult(result);
}
});
}
Main Activity example:
private static final int RC_SIGN_IN = 28;
private static final String RC_SIGN_IN_TAG = "GoogleSignIn";
private GoogleApiClient mGoogleApiClient;
private OptionalPendingResult<GoogleSignInResult> mGoogleApiClientPendingResult;
#Override
protected void onCreate(Bundle savedInstanceState) {
// Google Log In
// Configure sign-in to request the user's ID, email address, and basic
// profile. ID and basic profile are included in DEFAULT_SIGN_IN.
GoogleSignInOptions googleSignInOptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
// Change this for Your needs
.requestScopes(new Scope(Scopes.DRIVE_APPFOLDER), new Scope(Scopes.DRIVE_FILE), new Scope(Scopes.PROFILE))
.requestEmail()
.build();
// Build a GoogleApiClient with access to the Google Sign-In API and the
// options specified by gso.
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, new GoogleApiClient.OnConnectionFailedListener() {
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
//
}
})
.addApi(Auth.GOOGLE_SIGN_IN_API, googleSignInOptions)
.addApi(Drive.API)
.addScope(Drive.SCOPE_APPFOLDER)
.addScope(Drive.SCOPE_FILE)
.build();
// LogIN pending result
mGoogleApiClientPendingResult = Auth.GoogleSignInApi.silentSignIn(mGoogleApiClient);
if (mGoogleApiClientPendingResult.isDone()) {
// There's immediate result available.
// Handle you result here
handleSignInResult(mGoogleApiClientPendingResult.get());
} else {
// There's no immediate result ready, displays some progress indicator and waits for the
// async callback.
mGoogleApiClientPendingResult.setResultCallback(new ResultCallback<GoogleSignInResult>() {
#Override
public void onResult(#NonNull GoogleSignInResult result) {
// Handle you result here
handleSignInResult(result);
}
});
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
handleSignInResult(result);
}
}
private void handleSignInResult(GoogleSignInResult result) {
Log.d(RC_SIGN_IN_TAG, "handleSignInResult:" + result.isSuccess());
if (result.isSuccess()) {
// Signed in successfully, show authenticated UI.
GoogleSignInAccount acct = result.getSignInAccount();
if (acct != null) {
// Do your things here
nameTextView.setText(acct.getDisplayName());
emailTextView.setText(acct.getEmail());
// You can gat methods here - https://developers.google.com/android/reference/com/google/android/gms/auth/api/signin/GoogleSignInAccount
}
}
}

Twitter API using Firebase: How do I get the twitter accessToken to post on user's behalf?? I already logged in successfully

I'm using firebase-UI to log in with twitter, and now as the docs say I have to get an access token using the method private void handleTwitterSession(TwitterSession session) . The login is working fine but I don't know what to send to that function the so called "Session". How do I get the access token from the FirebaseAuth mAuth object??...Thank you very much. The links to the docs are this https://firebase.google.com/docs/auth/android/twitter-login
public class MainActivity extends AppCompatActivity {
private static final String TAG = "NearGoal";
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private List<causes> causesList = new ArrayList<>();
private List<FundItem> fundItemList = new ArrayList<>();
private RecyclerView rv;
private RecyclerView rvgoal;
private causes_adaptor cAdapter;
private causes_adaptor_near_goal gAdapter;
private ProgressBar pb;
private ProgressBar progressBarGral;
private Context mContext;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
mAuth = FirebaseAuth.getInstance();
if (mAuth.getCurrentUser() != null) {
// already signed in
FirebaseUser firebaseUser=mAuth.getCurrentUser();
Log.d("TWITTER_USER_INFO",""+mAuth.getCurrentUser().getToken(true));
} else {
startActivityForResult(
AuthUI.getInstance()
.createSignInIntentBuilder()
.setProviders(Arrays.asList(
new AuthUI.IdpConfig.Builder(AuthUI.TWITTER_PROVIDER).build()))
.build(),
RC_SIGN_IN);
}
//TwitterAuthProvider
Fresco.initialize(getApplication());
setContentView(R.layout.activity_main);
rv = (RecyclerView) findViewById(R.id.rv);
rvgoal = (RecyclerView) findViewById(R.id.rvgoal);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
rv.setLayoutManager(mLayoutManager);
rv.setItemAnimator(new DefaultItemAnimator());
RecyclerView.LayoutManager gLayoutManager =new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
rvgoal.setLayoutManager(gLayoutManager);
rvgoal.setDrawingCacheEnabled(true);
rvgoal.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
rvgoal.setItemAnimator(new DefaultItemAnimator());
toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitle("Your Title");
//toolbar.setTitleTextColor(getResources().getColor(android.R.color.transparent));
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
//tabLayout = (TabLayout) findViewById(R.id.tabs);
//tabLayout.setupWithViewPager(viewPager);
//collapsingToolbarLayout.setTitle(" ");
pb=(ProgressBar) findViewById(R.id.ProgressBar);
progressBarGral = (ProgressBar) findViewById(R.id.progress_bar);
// String url = "http://10.0.2.2:3000/api/campaigns/get/all//api/campaigns/get/all/";
new DownloadTask().execute();;
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
} else {
// User is signed out
Log.d(TAG, "onAuthStateChanged:signed_out");
}
}
};
}
public class DownloadTask extends AsyncTask<String, Void, Integer> {
URL url = null;
#Override
protected void onPreExecute() {
progressBarGral.setVisibility(View.VISIBLE);
}
#Override
protected Integer doInBackground(String... params) {
Integer result = 0;
HttpURLConnection urlConnection;
try {
url = new URL(getResources().getString(R.string.backend_base_url)+"/api/campaigns/get/all/");
urlConnection = (HttpURLConnection) url.openConnection();
int statusCode = urlConnection.getResponseCode();
// 200 represents HTTP OK
if (statusCode == 200) {
BufferedReader r = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
response.append(line);
}
parseResult(response.toString());
result = 1; // Successful
} else {
result = 0; //"Failed to fetch data!";
}
} catch (Exception e) {
Log.d(TAG, e.getLocalizedMessage());
}
return result; //"Failed to fetch data!";
}
#Override
protected void onPostExecute(Integer result) {
progressBarGral.setVisibility(View.GONE);
if (result == 1) {
gAdapter = new causes_adaptor_near_goal(MainActivity.this, causesList);
//gAdapter = new causes_adaptor_near_goal(getApplicationContext(), causesList);
rvgoal.setAdapter(gAdapter);
cAdapter = new causes_adaptor(MainActivity.this, causesList);
//gAdapter = new causes_adaptor_near_goal(getApplicationContext(), causesList);
rv.setAdapter(cAdapter);
} else {
Toast.makeText(MainActivity.this, "Failed to fetch data!", Toast.LENGTH_SHORT).show();
}
}
private void parseResult(String result) {
try {
JSONObject response = new JSONObject(result);
JSONArray posts = response.getJSONArray("rows");
causesList = new ArrayList<>();
JSONArray funds;
for (int i = 0; i < posts.length(); i++) {
fundItemList = new ArrayList<>();
JSONObject post = posts.optJSONObject(i);
funds = post.getJSONArray("foundations");
causes item = new causes();
item.setName(post.optString("name"));
item.setcause_description(post.optString("cause_description"));
item.setGoal(post.optString("goal"));
item.setCurrent_contributions(post.optString("current_contributions"));
item.setTotalUniqueUsersReached(post.optString("totalUniqueUsersReached"));
item.setState(post.optString("state"));
item.setId(post.optString("_id"));
item.setRemaining_ammount_to_goal(post.optString("remaining_ammount_to_goal"));
item.setGoal_percentage_achieved(post.optString("goal_percentage_achieved"));
item.setCampaign_ending_date(post.optString("campaign_ending_date"));
for(int k=0, len=funds.length(); k <len;k++) {
FundItem fundItem = new FundItem();
JSONObject fund = funds.optJSONObject(k);
fundItem.setTwitter_account(fund.getString("twitter_account"));
fundItem.setName(fund.getString("name"));
fundItem.setPic_path(fund.getString("pic_path"));
fundItemList.add(fundItem);
}
item.setFundlist(fundItemList);
causesList.add(item);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_home, menu);
return true;
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
// user is signed in!
Log.d("user_status","user signed in!!");
return;
}
// Sign in canceled
if (resultCode == RESULT_CANCELED) {
/* startActivityForResult(
AuthUI.getInstance()
.createSignInIntentBuilder()
.setProviders(Arrays.asList(
new AuthUI.IdpConfig.Builder(AuthUI.TWITTER_PROVIDER).build()))
.build(),
RC_SIGN_IN);*/
return;
}
// User is not signed in. Maybe just wait for the user to press
// "sign in" again, or show a message.
}
private void handleTwitterSession(TwitterSession session) {
Log.d(TAG, "handleTwitterSession:" + session);
AuthCredential credential = TwitterAuthProvider.getCredential(
session.getAuthToken().token,
session.getAuthToken().secret);
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d(TAG, "signInWithCredential:onComplete:" + task.isSuccessful());
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful()) {
Log.w(TAG, "signInWithCredential", task.getException());
Toast.makeText(getApplicationContext(), "Authentication failed.",
Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
}
You can use setCallBack() to get TwitterSession
mLoginButton.setCallback(new Callback<TwitterSession>() {
#Override
public void success(Result<TwitterSession> result) {
Log.d(TAG, "twitterLogin:success" + result);
handleTwitterSession(result.data);
}
#Override
public void failure(TwitterException exception) {
Log.w(TAG, "twitterLogin:failure", exception);
}
});
Take a look at this question also.
I solved it by using the firebase ui onActivityResult parameter data instead of trying to use that handleTwitterSession function, cause firebase-ui already handles that loginWithCredentials so it would be redundant.....Changing the onActivityResult is what makes the difference in this case, I post the working code for future reference:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN && resultCode == RESULT_OK) {
IdpResponse response = IdpResponse.fromResultIntent(data);
//twitter token
response.getIdpToken();
//twitter secret
response.getIdpSecret();
}
}

Video and audio call 2 Android devices - webrtc

I'm trying do develop Android app which will send audio and video via webrtc protocol between devices. This code works well with Android and web interface, but not between two Androids. Every time connection is opened and popup says that devices are connected, but there is no sound and picture. I tried a lot of things, but nothing helped. Dependencies and permissions are ok. Used my own pub and sub keys from PubNub. It opens connection 1 of 20 times between two Androids, so I think that something isn't working well here.
Followed this tutorial to create app: tutorial
I found this error image
Camera is crashing somewhere, but I really don't know why.
public static final String VIDEO_TRACK_ID = "videoPN";
public static final String AUDIO_TRACK_ID = "audioPN";
public static final String LOCAL_MEDIA_STREAM_ID = "localStreamPN";
private PnRTCClient pnRTCClient;
private VideoSource localVideoSource;
private VideoRenderer.Callbacks localRender;
private VideoRenderer.Callbacks remoteRender;
private GLSurfaceView mVideoView;
private String username;
private class MyRTCListener extends PnRTCListener {
#Override
public void onLocalStream(final MediaStream localStream) {
VideoChatActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
if(localStream.videoTracks.size()==0) return;
localStream.videoTracks.get(0).addRenderer(new VideoRenderer(localRender));
}
});
}
#Override
public void onAddRemoteStream(final MediaStream remoteStream, final PnPeer peer) {
VideoChatActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(VideoChatActivity.this,"Connected to " + peer.getId(), Toast.LENGTH_SHORT).show();
try {
if(remoteStream.videoTracks.size()==0) return;
remoteStream.videoTracks.get(0).addRenderer(new VideoRenderer(remoteRender));
VideoRendererGui.update(remoteRender, 0, 0, 100, 100, VideoRendererGui.ScalingType.SCALE_ASPECT_FILL, false);
VideoRendererGui.update(localRender, 72, 72, 25, 25, VideoRendererGui.ScalingType.SCALE_ASPECT_FIT, true);
}
catch (Exception e){ e.printStackTrace(); }
}
});
}
#Override
public void onPeerConnectionClosed(PnPeer peer) {
Intent intent = new Intent(VideoChatActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.videochatactivity);
Bundle extras = getIntent().getExtras();
if (extras == null || !extras.containsKey(Constants.USER_NAME)) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
Toast.makeText(this, "Need to pass username to VideoChatActivity in intent extras (Constants.USER_NAME).",
Toast.LENGTH_SHORT).show();
finish();
return;
}
this.username = extras.getString(Constants.USER_NAME, "");
PeerConnectionFactory.initializeAndroidGlobals(
this, // Context
true, // Audio Enabled
true, // Video Enabled
true, // Hardware Acceleration Enabled
null); // Render EGL Context
PeerConnectionFactory pcFactory = new PeerConnectionFactory();
this.pnRTCClient = new PnRTCClient(Constants.PUB_KEY, Constants.SUB_KEY, this.username);
int camNumber = VideoCapturerAndroid.getDeviceCount();
String frontFacingCam = VideoCapturerAndroid.getNameOfFrontFacingDevice();
String backFacingCam = VideoCapturerAndroid.getNameOfBackFacingDevice();
VideoCapturerAndroid capturer = (VideoCapturerAndroid) VideoCapturerAndroid.create(frontFacingCam);
localVideoSource = pcFactory.createVideoSource(capturer, this.pnRTCClient.videoConstraints());
VideoTrack localVideoTrack = pcFactory.createVideoTrack(VIDEO_TRACK_ID, localVideoSource);
AudioSource audioSource = pcFactory.createAudioSource(this.pnRTCClient.audioConstraints());
AudioTrack localAudioTrack = pcFactory.createAudioTrack(AUDIO_TRACK_ID, audioSource);
MediaStream mediaStream = pcFactory.createLocalMediaStream(LOCAL_MEDIA_STREAM_ID);
mediaStream.addTrack(localVideoTrack);
mediaStream.addTrack(localAudioTrack);
this.mVideoView = (GLSurfaceView) findViewById(R.id.gl_surface);
VideoRendererGui.setView(mVideoView, null);
remoteRender = VideoRendererGui.create(0, 0, 100, 100, VideoRendererGui.ScalingType.SCALE_ASPECT_FILL, false);
localRender = VideoRendererGui.create(0, 0, 100, 100, VideoRendererGui.ScalingType.SCALE_ASPECT_FILL, true);
this.pnRTCClient.attachRTCListener(new MyRTCListener());
this.pnRTCClient.attachLocalMediaStream(mediaStream);
this.pnRTCClient.listenOn(this.username);
this.pnRTCClient.setMaxConnections(1);
if (extras.containsKey(Constants.JSON_CALL_USER)) {
String callUser = extras.getString(Constants.JSON_CALL_USER, "");
connectToUser(callUser);
}
}
public void connectToUser(String user) {
this.pnRTCClient.connect(user);
}
public void hangup(View view) {
this.pnRTCClient.closeAllConnections();
startActivity(new Intent(VideoChatActivity.this, MainActivity.class));
}
#Override
protected void onDestroy() {
super.onDestroy();
if (this.localVideoSource != null) {
localVideoSource.stop();
}
if (this.pnRTCClient != null) {
this.pnRTCClient.onDestroy();
this.pnRTCClient.closeAllConnections();
}
}
Here is MainActivity if it will help:
private SharedPreferences mSharedPreferences;
private TextView mUsernameTV;
private EditText mCallNumET;
// private Pubnub mPubNub;
private String username;
private Pubnub mPubNub;
public void initPubNub() {
String stdbyChannel = this.username + Constants.STDBY_SUFFIX;
this.mPubNub = new Pubnub(Constants.PUB_KEY, Constants.SUB_KEY);
this.mPubNub.setUUID(this.username);
try {
this.mPubNub.subscribe(stdbyChannel, new Callback() {
#Override
public void successCallback(String channel, Object message) {
Log.d("MA-success", "MESSAGE: " + message.toString());
if (!(message instanceof JSONObject)) return; // Ignore if not JSONObject
JSONObject jsonMsg = (JSONObject) message;
try {
if (!jsonMsg.has(Constants.JSON_CALL_USER)) return;
String user = jsonMsg.getString(Constants.JSON_CALL_USER);
// Consider Accept/Reject call here
Intent intent = new Intent(MainActivity.this, VideoChatActivity.class);
intent.putExtra(Constants.USER_NAME, username);
intent.putExtra(Constants.JSON_CALL_USER, user);
startActivity(intent);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
} catch (PubnubException e) {
e.printStackTrace();
}
}
public void makeCall(View view){
String callNum = mCallNumET.getText().toString();
if (callNum.isEmpty() || callNum.equals(this.username)) {
Toast.makeText(this, "Enter a valid number.", Toast.LENGTH_SHORT).show();
}
dispatchCall(callNum);
}
public void dispatchCall(final String callNum) {
final String callNumStdBy = callNum + Constants.STDBY_SUFFIX;
JSONObject jsonCall = new JSONObject();
try {
jsonCall.put(Constants.JSON_CALL_USER, this.username);
mPubNub.publish(callNumStdBy, jsonCall, new Callback() {
#Override
public void successCallback(String channel, Object message) {
Log.d("MA-dCall", "SUCCESS: " + message.toString());
Intent intent = new Intent(MainActivity.this, VideoChatActivity.class);
intent.putExtra(Constants.USER_NAME, username);
intent.putExtra(Constants.JSON_CALL_USER, callNum);
startActivity(intent);
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.mSharedPreferences = getSharedPreferences(Constants.SHARED_PREFS, MODE_PRIVATE);
// Return to Log In screen if no user is logged in.
if (!this.mSharedPreferences.contains(Constants.USER_NAME)){
Intent intent = new Intent(this, LoginActivity.class);
startActivity(intent);
finish();
return;
}
this.username = this.mSharedPreferences.getString(Constants.USER_NAME, "");
this.mCallNumET = (EditText) findViewById(R.id.call_num);
this.mUsernameTV = (TextView) findViewById(R.id.main_username);
this.mUsernameTV.setText(this.username); // Set the username to the username text view
//TODO: Create and instance of Pubnub and subscribe to standby channel
// In pubnub subscribe callback, send user to your VideoActivity
initPubNub();
}
I will appreciate any help. Thanks to everybody.
when You run your application that time they ask sign in usename
that time you wrote your name
put that name in VideoChatActivity class
this.pnRTCClient.listenOn("your name when your wrote at signin time");
this.pnRTCClient.setMaxConnections(3);

How to get data from getter setter class?

I am beginner in android development , I have some issue please help me.
I have 2 screen Login and After Login , I have set User id in login class and i want to use that user_id in after login how to get , when I use get method find Null how to resolve this problem.
here is my Login Code`public class LoginActivity extends FragmentActivity {
private EditText userName;
private EditText password;
private TextView forgotPassword;
private TextView backToHome;
private Button login;
private CallbackManager callbackManager;
private ReferanceWapper referanceWapper;
private LoginBean loginBean;
Context context;
String regid;
GoogleCloudMessaging gcm;
String SENDER_ID = "918285686540";
public static final String PROPERTY_REG_ID = "registration_id";
private static final String PROPERTY_APP_VERSION = "appVersion";
private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
static final String TAG = "GCM";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_login);
Utility.setStatusBarColor(this, R.color.tranparentColor);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/OpenSans_Regular.ttf");
setupUI(findViewById(R.id.parentEdit));
userName = (EditText) findViewById(R.id.userName);
userName.setTypeface(tf);
userName.setFocusable(false);
userName.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View view, MotionEvent paramMotionEvent) {
userName.setFocusableInTouchMode(true);
Utility.hideSoftKeyboard(LoginActivity.this);
return false;
}
});
password = (EditText) findViewById(R.id.passwordEText);
password.setTypeface(tf);
password.setFocusable(false);
password.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View paramView, MotionEvent paramMotionEvent) {
password.setFocusableInTouchMode(true);
Utility.hideSoftKeyboard(LoginActivity.this);
return false;
}
});
forgotPassword = (TextView) findViewById(R.id.forgotPassword);
forgotPassword.setTypeface(tf);
forgotPassword.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),ForgotPasswordActivity.class);
startActivity(intent);
}
});
backToHome = (TextView) findViewById(R.id.fromLogToHome);
backToHome.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
login = (Button) findViewById(R.id.loginBtn);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
doLoginTask();
// Intent intent = new Intent(getApplicationContext(), AfterLoginActivity.class);
// startActivity(intent);
}
});
}
private void doLoginTask() {
String strEmail = userName.getText().toString();
String strPassword = password.getText().toString();
if (strEmail.length() == 0) {
userName.setError("Email Not Valid");
} else if (!Utility.isEmailValid(strEmail.trim())) {
userName.setError("Email Not Valid");
} else if (strPassword.length() == 0) {
password.setError(getString(R.string.password_empty));
} else {
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject();
jsonObject.putOpt(Constants.USER_NAME, strEmail);
jsonObject.putOpt(Constants.USER_PASSWORD, strPassword);
jsonObject.putOpt(Constants.DEVICE_TOKEN, "11");
jsonObject.putOpt(Constants.MAC_ADDRESS, "111");
jsonObject.putOpt(Constants.GPS_LATITUDE, "1111");
jsonObject.putOpt(Constants.GPS_LONGITUDE, "11111");
} catch (JSONException e) {
e.printStackTrace();
}
final ProgressDialog pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
pDialog.show();
CustomJSONObjectRequest jsonObjectRequest = new CustomJSONObjectRequest(Request.Method.POST, Constants.USER_LOGIN_URL, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
pDialog.dismiss();
Log.e("LoginPage", "OnResponse =" + response.toString());
getLogin(response);
//LoginBean lb = new LoginBean();
//Toast.makeText(getApplicationContext(),lb.getFull_name()+"Login Successfuly",Toast.LENGTH_LONG).show();
Intent intent = new Intent(getApplicationContext(),AfterLoginActivity.class);
startActivity(intent);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),"Something, wrong please try again",Toast.LENGTH_LONG).show();
pDialog.dismiss();
}
});
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(
5000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
Log.e("LoginPage", "Url= " + Constants.USER_LOGIN_URL + " PostObject = " + jsonObject.toString());
AppController.getInstance().addToRequestQueue(jsonObjectRequest);
}
}
public void getLogin(JSONObject response) {
LoginBean loginBean = new LoginBean();
if (response != null){
try {
JSONObject jsonObject = response.getJSONObject("data");
loginBean.setUser_id(jsonObject.getString("user_id"));
loginBean.setFull_name(jsonObject.getString("full_name"));
loginBean.setDisplay_name(jsonObject.getString("display_name"));
loginBean.setUser_image(jsonObject.getString("user_image"));
loginBean.setGender(jsonObject.getString("gender"));
loginBean.setAuthorization_key(jsonObject.getString("authorization_key"));
} catch (JSONException e) {
e.printStackTrace();
}
}
Toast.makeText(getApplicationContext(),"User id is "+loginBean.getUser_id(),Toast.LENGTH_LONG).show();
}
public void onBackPressed() {
finish();
}
public void setupUI(View view) {
//Set up touch listener for non-text box views to hide keyboard.
if (!(view instanceof EditText)) {
view.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
Utility.hideSoftKeyboard(LoginActivity.this);
return false;
}
});
}
}
}
`
here is my AfterLogin class`public class AfterLoginActivity extends FragmentActivity {
private ImageView partyIcon;
private ImageView dealIcon;
private ImageView deliveryIcon;
private TextView txtParty;
private TextView txtDeals;
private TextView txtDelivery;
boolean doubleBackToExitPressedOnce = false;
int backButtonCount = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_after_login);
Utility.setStatusBarColor(this, R.color.splash_status_color);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
partyIcon = (ImageView)findViewById(R.id.party_Icon);
dealIcon = (ImageView)findViewById(R.id.deals_Icon);
deliveryIcon = (ImageView)findViewById(R.id.delivery_Icon);
partyIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplication(), BookPartyActivity.class);
startActivity(intent);
}
});
dealIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplication(), DealsActivity.class);
startActivity(intent);
}
});
deliveryIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LoginBean loginBean = new LoginBean();
Toast.makeText(getBaseContext(),"Auth"+loginBean.getUser_id(),Toast.LENGTH_LONG).show();
Intent intent = new Intent(getApplicationContext(),MyAuction.class);
startActivity(intent);
}
});
}
/*
public void onBackPressed()
{
if (doubleBackToExitPressedOnce)
{
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
doubleBackToExitPressedOnce = true;
Toast.makeText(this, "you have logged in ,plz enjoy the party", Toast.LENGTH_LONG).show();
new Handler().postDelayed(new Runnable()
{
public void run()
{
doubleBackToExitPressedOnce = false;
}
}
, 2000L);
}*/
#Override
public void onBackPressed()
{
if(backButtonCount >= 1)
{
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
else
{
Toast.makeText(this, "Press the back button once again to close the application.", Toast.LENGTH_SHORT).show();
backButtonCount++;
}
}
}`
here is LoginBean`public class LoginBean {
private String user_id;
private String full_name;
private String display_name;
private String user_image;
private String gender;
private String authorization_key;
public void setUser_id(String user_id) {
this.user_id = user_id;
}
public String getUser_id() {
return user_id;
}
public void setFull_name(String full_name) {
this.full_name = full_name;
}
public String getFull_name() {
return full_name;
}
public void setDisplay_name(String display_name) {
this.display_name = display_name;
}
public String getDisplay_name() {
return display_name;
}
public void setUser_image(String user_image) {
this.user_image = user_image;
}
public String getUser_image() {
return user_image;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getGender() {
return gender;
}
public void setAuthorization_key(String authorization_key) {
this.authorization_key = authorization_key;
}
public String getAuthorization_key() {
return authorization_key;
}
}`
//in your both activity or create class
private SharedPreferences mSharedPreferences;
//in your login on getLogin() method ;
mSharedPreferences = getSharedPreferences("user_preference",Context.MODE_PRIVATE);
//save actual drawable id in this way.
if(mSharedPreferences==null)
return;
SharedPreferences.Editor editor = mSharedPreferences.edit();
editor.putInt("userId", loginBean.getUser_id());
editor.commit();
// in your after login acvtivity on deliverable method
private SharedPreferences mSharedPreferences;
mSharedPreferences = getSharedPreferences("user_preference",Context.MODE_PRIVATE);
if(mSharedPreferences==null)
return;
string userId = mSharedPreferences.getString("userId", "");
You can write and apply below mentioned steps (Please ignore any syntactical error, I am giving you simple logical steps).
step 1 - Make a global application level loginObject setter and getter like below. Make sure to define Application class in your manifest just like you do it for your LoginActivity
public class ApplicationClass extends Application{
private LoginBean loginObject;
public void setLoginBean(LoginBean object) {
this.loginObject = object;
}
public LoginBean getName() {
return this.loginObject
}
}
Step - 2 Get an instance of ApplicationClass object reference in LoginActivity to set this global loginObject
e.g. setLogin object in your current Loginactivity like this
......
private ApplicationClass appObject;
......
#Override
protected void onCreate(Bundle savedInstanceState) {
......
appObject = (ApplicationClass) LoginActivity.this.getApplication();
.......
appObject.setLoginBean(loginObject)
}
Step - 3 Get an instance of ApplicationClass object reference in any other Activity get this global loginObject where you need to access this login data.
e.g. getLogin object in your otherActivity like this
......
private ApplicationClass appObject;
......
#Override
protected void onCreate(Bundle savedInstanceState) {
......
appObject = (ApplicationClass) LoginActivity.this.getApplication();
.......
LoginBean loginObject = appObject.getLoginBean();
}

Categories

Resources