How to get data from getter setter class? - java

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

Related

how to get twitter username with twitter4j

I am developing an app in java in the android studio IDE, the idea is that after logging in with my username and password, I can be redirected to a new view where a user profile is shown with the name, email and profile image. Currently I can log in and after that it redirects to the user profile but I don't know how to get the name, email and profile image.Then I leave you my code in case you have the time to help me, thank you very much for reading:
loggin.class
public class loggin extends AppCompatActivity {
//variable twitter
Button twitterButton;
//TwitterLoginButton login;
private static final String TAG = "Twitter4j";
private static Twitter twitter;
private static final String APIConsumerKey = "xxxx";
private static final String APIConsumerSecretKey = "xxxx";
private static final String CALLBACK_URL = "http://myurl";
private static RequestToken twitterRequestToken;
twitterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
initializeTwitter(loggin.this);
}
});
}
private static void initializeTwitter(final Activity activity) {
ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
configurationBuilder.setOAuthConsumerKey(APIConsumerKey);
configurationBuilder.setOAuthConsumerSecret(APIConsumerSecretKey);
twitter = new TwitterFactory(configurationBuilder.build()).getInstance();
new Thread(new Runnable() {
#Override
public void run() {
User user;
try {
twitterRequestToken = twitter.getOAuthRequestToken(CALLBACK_URL);
Log.i("LoginActivity", String.valueOf(twitterRequestToken));
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
//Open Dialog for authentication.
Intent intent = new Intent(activity, TwitterAuthActivity.class);
if (twitterRequestToken != null) {
intent.putExtra("TwitterReqTokenUrl", twitterRequestToken.getAuthenticationURL());
activity.startActivity(intent);
}
}
});
} catch (Exception e) {
Log.e(TAG, "Exception " + e.getMessage());
}
}
}).start();
}
}
twitterAuthActivity
public class TwitterAuthActivity extends AppCompatActivity {
private static final String TAG = "Twitter4j";
private static final String TWITTER_CALLBACK_URL = "http://www.stackoverflow.com"; //"x-oauthflow-twitter://twitterlogin";
private ProgressDialog progressDialog;
private String twitterRequesTokenUrl;
private WebView twitterWebView;
#SuppressLint("SetJavaScriptEnabled")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog_twitter);
twitterWebView = findViewById(R.id.TwitterWebView);
Bundle extras = getIntent().getExtras();
if (extras != null) {
twitterRequesTokenUrl = extras.getString("TwitterReqTokenUrl");
}
progressDialog = new ProgressDialog(this);
progressDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
progressDialog.setMessage("Loading...");
//Setup WebView
CookieSyncManager.createInstance(this);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.removeAllCookie();
twitterWebView.setVerticalScrollBarEnabled(false);
twitterWebView.setHorizontalScrollBarEnabled(false);
twitterWebView.setWebViewClient(new TwitterWebViewClient());
WebSettings webSettings = twitterWebView.getSettings();
webSettings.setSupportZoom(true);
webSettings.setSaveFormData(true);
webSettings.setJavaScriptEnabled(true);
twitterWebView.loadUrl(twitterRequesTokenUrl);
}
#Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
int[] l = new int[2];
twitterWebView.getLocationOnScreen(l);
Rect rect = new Rect(l[0], l[1], l[0] + twitterWebView.getWidth(), l[1] + twitterWebView.getHeight());
if (!rect.contains((int) ev.getRawX(), (int) ev.getRawY())) {
finish();
}
}
return super.dispatchTouchEvent(ev);
}
private class TwitterWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
boolean response = false;
if (url.contains(TWITTER_CALLBACK_URL)) {
Uri uri = Uri.parse(url);
//This uri could be saved as access token.
Log.i(TAG, "shouldOverrideUrlLoading() uri " + uri.getPath());
Intent intent=new Intent(TwitterAuthActivity.this,MainActivity.class);
startActivity(intent);
finish();
response = true;
}
return response;
}
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
Toast.makeText(TwitterAuthActivity.this, "Upps! something happened, retry later!.", Toast.LENGTH_LONG).show();
finish();
}
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if(progressDialog.isShowing() && !isFinishing() && !isDestroyed()) {
progressDialog.dismiss();
}
twitterWebView.setVisibility(View.VISIBLE);
}
}
}

Pass username to another activity with RewardedAd

The problem is that I am trying to pass the name of the user when the adReward is complete to another activity. But I'm stuck in this activity, even though the video ad is loaded. (and it works well while there are no video ad to show). Here is my code:
My java.class
public class TheDay1 extends AppCompatActivity implements RewardedVideoAdListener {
Vibrator vibrator;
private RewardedVideoAd HDay1;
int currentActivity = 0;
boolean flag;
private EditText vname;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_the_day1);
vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
MobileAds.initialize(this,
"ca-app-pub-3940256099942544/6300978111");
///ADD BAN
AdView mAdView = findViewById(R.id.banner1);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
///////////////////////////////////
//VIDEO
HDay1 = MobileAds.getRewardedVideoAdInstance(this);
HDay1.setRewardedVideoAdListener(this);
loadRewardedVideoDAY1();
vname = findViewById(R.id.name);
final ImageView nm = findViewById(R.id.ID);
nm.setVisibility(View.INVISIBLE);
ColorMatrix matrix = new ColorMatrix();
matrix.setSaturation(0);
ColorMatrixColorFilter filter = new ColorMatrixColorFilter(matrix);
nm.setColorFilter(filter);
final Button closeAd = findViewById(R.id.closeDay1);
closeAd.setVisibility(View.INVISIBLE);
///////////////////////////////////////////////////////////////////////////////////////////
closeAd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
vibrator.vibrate(50);
loadRewardedVideoDAY1();
if (HDay1.isLoaded()) {
HDay1.show();
setCurrent(1);
}
String name = vname.getText().toString();
getusername(name);
}
});
}
////////////////////////////////////////////////////////////////
private void Day1() {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
private void getusername(String name) {
Intent intent = new Intent(this, ActivityTwo.class);
Resources resources = getResources();
String key = resources.getString(R.string.key_name);
intent.putExtra(key, name);
startActivity(intent);
}
private void loadRewardedVideoDAY1() {
if (!HDay1.isLoaded()) {
HDay1 = null;
HDay1 = MobileAds.getRewardedVideoAdInstance(this);
HDay1.setRewardedVideoAdListener(this);
///////////////TEST ID//////////////////
HDay1.loadAd("ca-app-pub-3940256099942544/5224354917", new AdRequest.Builder().build());
}
}
#Override
public void onRewardedVideoAdLoaded() {
Log.d("LOADED!", "onRewardedVideoAdLoaded");
}
#Override
public void onRewardedVideoAdOpened() {
Log.d("OPENED!", "onRewardedVideoAdLoaded");
}
#Override
public void onRewardedVideoStarted() {
Log.d("STARTED!", "onRewardedVideoAdLoaded");
}
#Override
public void onRewardedVideoAdClosed() {
loadRewardedVideoDAY1();
if (currentActivity == 1) {
Day1();
}
}
#Override
public void onRewarded(RewardItem rewardItem) {
loadRewardedVideoDAY1();
flag = true;
if (currentActivity == 1) {
Day1();
}
}
#Override
public void onRewardedVideoAdLeftApplication() {
}
#Override
public void onRewardedVideoAdFailedToLoad(int i) {
}
#Override
public void onRewardedVideoCompleted() {
}
#Override
protected void onPause() {
HDay1.pause(this);
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
}
public void setCurrent(int val){
currentActivity = val;
}
Any idea what the problem could be? Thanks in advance
Try below code. Update ProcessData with your intent logic and update oncreate with other data required in your class
public class TheDay1 extends AppCompatActivity implements RewardedVideoAdListener {
private RewardedVideoAd mRewardedVideoAd;
private Boolean bRewardVideo = false;
#Override
public void onResume() {
super.onResume();
if (mRewardedVideoAd != null) {
mRewardedVideoAd.resume(this);
}
}
#Override
public void onPause() {
super.onPause();
if (mRewardedVideoAd != null) {
mRewardedVideoAd.pause(this);
}
}
#Override
public void onDestroy() {
super.onDestroy();
if (mRewardedVideoAd != null) {
mRewardedVideoAd.destroy(this);
}
}
#Override
public void onRewardedVideoCompleted() {
//Toast.makeText(this, "onRewardedVideoCompleted", Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoAdLoaded() {
//Toast.makeText(this, "onRewardedVideoAdLoaded", Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoAdOpened() {
//Toast.makeText(this, "onRewardedVideoAdOpened", Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoStarted() {
//Toast.makeText(this, "onRewardedVideoStarted", Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoAdClosed() {
//Toast.makeText(this, "Reward Video Closed", Toast.LENGTH_SHORT).show();
// Load the next rewarded video ad.
if (bRewardVideo) {
ProcessData();
} else {
Toast.makeText(this, "Please View Reward Video to get Reward Points", Toast.LENGTH_LONG).show();
}
loadRewardedVideoAd();
}
#Override
public void onRewarded(RewardItem rewardItem) {
Toast.makeText(this, "Now you can close Ad to Process", Toast.LENGTH_LONG).show();
bRewardVideo = true;
}
#Override
public void onRewardedVideoAdLeftApplication() {
//Toast.makeText(this, "onRewardedVideoAdLeftApplication",Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoAdFailedToLoad(int i) {
Toast.makeText(this, "Fail to Load Reward Video. Please try again!", Toast.LENGTH_SHORT).show();
}
private void loadRewardedVideoAd() {
bRewardVideo = false;
mRewardedVideoAd.loadAd(BuildConfig.REWARDVIDEOID,
new AdRequest.Builder().build());
}
private void ProcessData() {
Snackbar.make(findViewById(R.id.drawer_layout_law), "Please wait while we process the request... ", Snackbar.LENGTH_INDEFINITE).show();
//WRITE YOUR INTENT CODE HERE
Intent intent = new Intent(this, ActivityTwo.class);
Resources resources = getResources();
String key = resources.getString(R.string.key_name);
intent.putExtra(key, name);
startActivity(intent);
}
private void ShowRewardVideoDialog() {
if (mRewardedVideoAd.isLoaded()) {
mRewardedVideoAd.show();
} else {
loadRewardedVideoAd();
Toast.makeText(mctx, "Fail to Load Reward Video : Please try again", Toast.LENGTH_LONG).show();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mRewardedVideoAd = MobileAds.getRewardedVideoAdInstance(this);
mRewardedVideoAd.setRewardedVideoAdListener(this);
loadRewardedVideoAd();
}
}

Passing database value to variable

I'm rarely ask on here, so first of all I'm sorry if my question is readable or not allowed here. So what I'm trying to do here is passing the username from LoginActivity into the player1 variable at HomeActivity . here's the code for the HomeActivity.java class
public class HomeActivity extends Activity {
TextView NameTxt;
TextView CoinTxt;
TextView GemTxt;
String p1name = player1.getName();
int p1coin = player1.getCoins();
int p1gem = player1.getGems();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_screen);
//////TV declare///////
NameTxt = (TextView)findViewById(R.id.playerName);
CoinTxt = (TextView)findViewById(R.id.cointxt);
GemTxt = (TextView)findViewById(R.id.gemtxt);
NameTxt.setText(p1name);
CoinTxt.setText("Coin: " +p1coin);
GemTxt.setText("Gem: " +p1gem);
}
}
And this is LoginActivity.class
public class LoginActivity extends Activity {
EditText edit1;
EditText edit2;
EditText edit3;
Button registerBtn;
Button loginBtn;
DatabaseHelper myDb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Set fullscreen and no title//////////
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
///////////////////////////////////////
setContentView(R.layout.login_screen);
edit1 = (EditText)findViewById(R.id.editpname);
edit2 = (EditText)findViewById(R.id.editpemail);
edit3 = (EditText)findViewById(R.id.editppw);
registerBtn = (Button)findViewById(R.id.registerbtn);
loginBtn = (Button)findViewById(R.id.loginbtn);
myDb = new DatabaseHelper(this);
loginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (validate()) {
String Email = edit2.getText().toString();
String Password = edit3.getText().toString();
User currentUser = myDb.Authenticate(new User(null, null, Email, Password));
if (currentUser != null) {
System.out.println("Successfull");
Intent intent = new Intent(getApplicationContext(),HomeActivity.class);
startActivity(intent);
finish();
} else {
System.out.println("Unsuccessfull");
}
}
}
});
registerBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (validate()) {
String UserName = edit1.getText().toString();
String Email = edit2.getText().toString();
String Password = edit3.getText().toString();
if (!myDb.isEmailExists(Email)) {
myDb.addUser(player1);
public User player1 = new User(null, UserName, Email, Password);
}
}
}
});
}
public boolean validate() {
boolean valid = false;
String Email = edit2.getText().toString();
String Password = edit3.getText().toString();
if (!android.util.Patterns.EMAIL_ADDRESS.matcher(Email).matches()) {
valid = false;
edit2.setError("Please enter valid email!");
} else {
valid = true;
edit2.setError(null);
}
if (Password.isEmpty()) {
valid = false;
edit3.setError("Please enter valid password!");
} else {
if (Password.length() > 5) {
valid = true;
edit3.setError(null);
} else {
valid = false;
edit3.setError("Password is to short!");
}
}
return valid;
}
}
And I also have simple User.java class
String id;
String userName;
String email;
String password;
int coins;
int gems;
public User(String id, String userName, String email, String password) {
this.id = id;
this.email = email;
//And so on. Don't mind this
}
public String getName() {
return this.userName;
}
public int getCoins() {
return this.coins;
}
public int getGems() {
return this.gems;
}
And I write the short code , for the sake of readability.
I get an error on
myDb.addUser(player1);
And the one below it.
I'm just trying to make so that the player name equals to the value of Username on the database . and also the coins and gems too. Can you guys help me to get the idea how to pass the value? It tooks me whole 3days to figure a way to fix this. And it just blew my brain. So maybe you guys can help me
Ignoring the database stuff and assuming that LoginActivity is started from another activity (MainActivity) then you could adapt the following which passes the Username and UserId (ample to then get any additional data in the HomeActivity from the database).
So this when it starts immediately invokes the LoginActivity.
Clicking Login (mimics getting user and id from db) starts the HomeActivity passing the Username and userid via Intent Extras.
The HomeActivity displays the username and userid, and additionally a DONE button.
Clicking the DONE button returns back through the stack (skippng LoginActivity as that was finished) to the MainActivity which changes the TextView from Hello World to Welcome Back (not that you'd ever see Hello World).
MainActivity.java :-
public class MainActivity extends AppCompatActivity {
TextView mMessage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mMessage = this.findViewById(R.id.message);
// Immediately start Login Activity
Intent i = new Intent(MainActivity.this,LoginActivity.class);
startActivity(i);
}
#Override
protected void onResume() {
super.onResume();
mMessage.setText("Welcome back");
}
}
LoginActivity.java :-
public class LoginActivity extends AppCompatActivity {
public static final String INTENTKEY_USERNAME = "IK_USERNAME";
public static final String INTENTKEY_USERID = "IK_USERID";
Button mloginbtn;
Context mContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mContext = this;
mloginbtn = this.findViewById(R.id.loginbtn);
mloginbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(mContext,HomeActivity.class);
i.putExtra(INTENTKEY_USERNAME,"Fred");
i.putExtra(INTENTKEY_USERID,99L);
startActivity(i);
finish();
}
});
}
}
HomeActivity.java
public class HomeActivity extends AppCompatActivity {
TextView mUsername, muserid;
Button mDone;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
mUsername = this.findViewById(R.id.username);
muserid = this.findViewById(R.id.userid);
mDone = this.findViewById(R.id.done);
mDone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
Intent i = this.getIntent();
mUsername.setText(i.getStringExtra(LoginActivity.INTENTKEY_USERNAME));
muserid.setText(String.valueOf(i.getLongExtra(LoginActivity.INTENTKEY_USERID,0)));
}
}
I'd do the following:
...
Intent intent = new Intent(getApplicationContext(),HomeActivity.class);
intent.putExtra("username", Bob)
startActivity(intent);
finish();
...
and then in home have:
Intent intent = getIntent();
String easyPuzzle = intent.getExtras().getString("username");

Unable to start activity ComponentInfo : Attempt to invoke virtual method on a null object reference [duplicate]

This question already has answers here:
NullPointerException addToRequestQueue(com.android.volley.Request, java.lang.String)' on a null object reference
(8 answers)
Closed 4 years ago.
This is a barcode scanning app. It crashes when I scanned the code. If anyone knows how to fix help me out.
It crashes after I scanned the code from the ScanActivity.java and pass the object to the TicketResultActivity.javato display the result.
error
java.lang.RuntimeException: Unable to start activity ComponentInfo{info.androidhive.movietickets/info.androidhive.movietickets.TicketResultActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void info.androidhive.movietickets.MyApplication.addToRequestQueue(com.android.volley.Request)' on a null object reference
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
// making toolbar transparent
transparentToolbar();
setContentView(R.layout.activity_main);
findViewById(R.id.btn_scan).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this, ScanActivity.class));
}
});
}
private void transparentToolbar() {
if (Build.VERSION.SDK_INT >= 19 && Build.VERSION.SDK_INT < 21) {
setWindowFlag(this, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, true);
}
if (Build.VERSION.SDK_INT >= 19) {
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
}
if (Build.VERSION.SDK_INT >= 21) {
setWindowFlag(this, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, false);
getWindow().setStatusBarColor(Color.TRANSPARENT);
}
}
private void setWindowFlag(Activity activity, final int bits, boolean on) {
Window win = activity.getWindow();
WindowManager.LayoutParams winParams = win.getAttributes();
if (on) {
winParams.flags |= bits;
} else {
winParams.flags &= ~bits;
}
win.setAttributes(winParams);
}
}
ScanActivity.java
public class ScanActivity extends AppCompatActivity implements BarcodeReader.BarcodeReaderListener{
BarcodeReader barcodeReader;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan);
// get the barcode reader instance
barcodeReader = (BarcodeReader) getSupportFragmentManager().findFragmentById(R.id.barcode_scanner);
}
#Override
public void onScanned(Barcode barcode) {
// playing barcode reader beep sound
barcodeReader.playBeep();
// ticket details activity by passing barcode
Intent intent = new Intent(ScanActivity.this, TicketResultActivity.class);
intent.putExtra("code", barcode.displayValue);
startActivity(intent);
}
#Override
public void onScannedMultiple(List<Barcode> list) {
}
#Override
public void onBitmapScanned(SparseArray<Barcode> sparseArray) {
}
/*#Override
public void onCameraPermissionDenied() {
finish();
}*/
#Override
public void onScanError(String s) {
Toast.makeText(getApplicationContext(), "Error occurred while scanning " + s, Toast.LENGTH_SHORT).show();
}
}
TicketResultActivity.java
public class TicketResultActivity extends AppCompatActivity {
private static final String TAG = TicketResultActivity.class.getSimpleName();
// url to search barcode
private static final String URL = "https://api.androidhive.info/barcodes/search.php?code=";
private TextView txtName, txtDuration, txtDirector, txtGenre, txtRating, txtPrice, txtError;
private ImageView imgPoster;
private Button btnBuy;
private ProgressBar progressBar;
private TicketView ticketView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ticket_result);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
txtName = findViewById(R.id.name);
txtDirector = findViewById(R.id.director);
txtDuration = findViewById(R.id.duration);
txtPrice = findViewById(R.id.price);
txtRating = findViewById(R.id.rating);
imgPoster = findViewById(R.id.poster);
txtGenre = findViewById(R.id.genre);
btnBuy = findViewById(R.id.btn_buy);
imgPoster = findViewById(R.id.poster);
txtError = findViewById(R.id.txt_error);
ticketView = findViewById(R.id.layout_ticket);
progressBar = findViewById(R.id.progressBar);
String barcode = getIntent().getStringExtra("code");
// close the activity in case of empty barcode
if (TextUtils.isEmpty(barcode)) {
Toast.makeText(getApplicationContext(), "Barcode is empty!", Toast.LENGTH_LONG).show();
finish();
}
// search the barcode
searchBarcode(barcode);
}
/**
* Searches the barcode by making HTTP call
* Request was made using Volley network library but the library is
* not suggested in production, consider using Retrofit
*/
private void searchBarcode(String barcode) {
// making volley's json request
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
URL + barcode, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e(TAG, "Ticket response: " + response.toString());
// check for success status
if (!response.has("error")) {
// received movie response
renderMovie(response);
} else {
// no movie found
showNoTicket();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Error: " + error.getMessage());
showNoTicket();
}
});
MyApplication.getInstance().addToRequestQueue(jsonObjReq);
}
private void showNoTicket() {
txtError.setVisibility(View.VISIBLE);
ticketView.setVisibility(View.GONE);
progressBar.setVisibility(View.GONE);
}
/**
* Rendering movie details on the ticket
*/
private void renderMovie(JSONObject response) {
try {
// converting json to movie object
Movie movie = new Gson().fromJson(response.toString(), Movie.class);
if (movie != null) {
txtName.setText(movie.getName());
txtDirector.setText(movie.getDirector());
txtDuration.setText(movie.getDuration());
txtGenre.setText(movie.getGenre());
txtRating.setText("" + movie.getRating());
txtPrice.setText(movie.getPrice());
Glide.with(this).load(movie.getPoster()).into(imgPoster);
if (movie.isReleased()) {
btnBuy.setText(getString(R.string.btn_buy_now));
btnBuy.setTextColor(ContextCompat.getColor(this, R.color.colorPrimary));
} else {
btnBuy.setText(getString(R.string.btn_coming_soon));
btnBuy.setTextColor(ContextCompat.getColor(this, R.color.btn_disabled));
}
ticketView.setVisibility(View.VISIBLE);
progressBar.setVisibility(View.GONE);
} else {
// movie not found
showNoTicket();
}
} catch (JsonSyntaxException e) {
Log.e(TAG, "JSON Exception: " + e.getMessage());
showNoTicket();
Toast.makeText(getApplicationContext(), "Error occurred. Check your LogCat for full report", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
// exception
showNoTicket();
Toast.makeText(getApplicationContext(), "Error occurred. Check your LogCat for full report", Toast.LENGTH_SHORT).show();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish();
}
return super.onOptionsItemSelected(item);
}
private class Movie {
String name;
String director;
String poster;
String duration;
String genre;
String price;
float rating;
#SerializedName("released")
boolean isReleased;
public String getName() {
return name;
}
public String getDirector() {
return director;
}
public String getPoster() {
return poster;
}
public String getDuration() {
return duration;
}
public String getGenre() {
return genre;
}
public String getPrice() {
return price;
}
public float getRating() {
return rating;
}
public boolean isReleased() {
return isReleased;
}
}
}
MyApplication.java
public class MyApplication extends Application {
public static final String TAG = MyApplication.class
.getSimpleName();
private RequestQueue mRequestQueue;
private static MyApplication mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized MyApplication getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
// set the default tag if tag is empty
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
To initialize MyApplication properly you have to add the following in the AndroidManifest.xml
<application android:name="com.package.subpackage.MyApplication">
...
</application>

How to set data from JSON?

I am new to android JSON programming. I want to use set and get function in this program ,but when i used get() for full_name,getting null.
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;
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);
setContentView(R.layout.activity_login);
Utility.setStatusBarColor(this, R.color.tranparentColor);
Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/OpenSans_Regular.ttf");
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);
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);
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);
}
}
private void getLogin(JSONObject response) {
if (response != null){
try {
JSONObject jsonObject = response.getJSONObject("data");
LoginBean loginBean = new LoginBean();
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"));
// signUpArrayList.add(signUpBean);
} catch (JSONException e) {
e.printStackTrace();
}
// dataBean.setSignUp(signUpArrayList);
}
LoginBean loginBean = new LoginBean();
Toast.makeText(getApplicationContext(),"Hello"+loginBean.getFull_name(),Toast.LENGTH_LONG).show();
}
public void onBackPressed() {
finish();
}
}
JSON Input:
"{
""user_name"":""ashish#soms.in"",
""user_password"":""123456"",
""device_token"":""1111"",
""mac_address"":""1111"",
""gps_latitude"":""1111"",
""gps_longitude"":""1111""
}"
Here is JSON Response:
{
""data"": {
""user_id"": ""90"",
""full_name"": ""ashish"",
""display_name"": ""ashish"",
""user_image"": ""images/noimage.png"",
""gender"": ""0"",
""authorization_key"": ""4eef1d65f7b470dbca881fe6452ec11457f54489""
}
}
pls comment line LoginBean loginBean = new LoginBean(); then try .
try this code
private void getLogin(JSONObject response) {
LoginBean loginBean=null;
if (response != null){
try {
loginBean = new LoginBean();
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"));
// signUpArrayList.add(signUpBean);
} catch (JSONException e) {
e.printStackTrace();
}
// dataBean.setSignUp(signUpArrayList);
}
Toast.makeText(getApplicationContext(),"Hello"+loginBean.getFull_name(),Toast.LENGTH_LONG).show();
}

Categories

Resources