I keep getting a NulPpointerException, when I use the Intent's putExtras() method like shown below. It is in the onClick method where I create an intent and call the register activity class. I use android"s account authentication mechanism. Whenever the signUpTxt Textview is clicked, the app crushes and the error log trace below shows. What am I missing?
Here is my source code
public class LoginActivity extends AccountAuthenticatorActivity {
//.......................................
//..........................................
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
actionBar = getSupportActionBar();
actionBar.hide();
mAccountManager = AccountManager.get(getBaseContext());
String accountName = getIntent().getStringExtra(ARG_ACCOUNT_NAME);
mAuthTokenType = getIntent().getStringExtra(ARG_AUTH_TYPE);
if (mAuthTokenType == null)
mAuthTokenType = AccountInfo.AUTHTOKEN_TYPE_FULL_ACCESS;
if (accountName != null) {
accountname = ((EditText) findViewById(R.id.txtAccountPhone));
accountname.setText(accountName);
}
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
login();
}
});
signUpTxt = (TextView) findViewById(R.id.txtSignUp);
signUpTxt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Since there can only be one AuthenticatorActivity, we call the sign up activity, get his results,
// and return them in setAccountAuthenticatorResult(). See finishLogin().
Intent signup = new Intent(getBaseContext(), RegisterActivity.class);
signup.putExtras(getIntent().getExtras());
startActivityForResult(signup, REQ_SIGNUP);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// The sign up activity returned that the user has successfully created an account
if (requestCode == REQ_SIGNUP && resultCode == RESULT_OK) {
finishLogin(data);
} else
super.onActivityResult(requestCode, resultCode, data);
}
public void login() {
final String userName = ((TextView) findViewById(R.id.txtAccountPhone)).getText().toString();
final String userPass = ((TextView) findViewById(R.id.txtAccountPassword)).getText().toString();
final String accountType = getIntent().getStringExtra(ARG_ACCOUNT_TYPE);
new AsyncTask<String, Void, Intent>() {
#Override
protected Intent doInBackground(String... params) {
Log.d("Slime", TAG + "> Started authenticating");
String authtoken = null;
Bundle data = new Bundle();
try {
authtoken = AccountInfo.sServerAuthenticate.userSignIn(userName, userPass, mAuthTokenType);
data.putString(AccountManager.KEY_ACCOUNT_NAME, userName);
data.putString(AccountManager.KEY_ACCOUNT_TYPE, accountType);
data.putString(AccountManager.KEY_AUTHTOKEN, authtoken);
data.putString(PARAM_USER_PASS, userPass);
} catch (Exception e) {
data.putString(KEY_ERROR_MESSAGE, e.getMessage());
}
final Intent res = new Intent();
res.putExtras(data);
return res;
}
#Override
protected void onPostExecute(Intent intent) {
if (intent.hasExtra(KEY_ERROR_MESSAGE)) {
Toast.makeText(getBaseContext(), intent.getStringExtra(KEY_ERROR_MESSAGE), Toast.LENGTH_SHORT).show();
} else {
finishLogin(intent);
}
}
}.execute();
}
private void finishLogin(Intent intent) {
Log.d("Slime", TAG + "> finishLogin");
String accountName = intent.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
String accountPassword = intent.getStringExtra(PARAM_USER_PASS);
final Account account = new Account(accountName, intent.getStringExtra(AccountManager.KEY_ACCOUNT_TYPE));
if (getIntent().getBooleanExtra(ARG_IS_ADDING_NEW_ACCOUNT, false)) {
Log.d("Slime", TAG + "> finishLogin > addAccountExplicitly");
String authtoken = intent.getStringExtra(AccountManager.KEY_AUTHTOKEN);
String authtokenType = mAuthTokenType;
// Creating the account on the device and setting the auth token we got
// (Not setting the auth token will cause another call to the server to authenticate the user)
mAccountManager.addAccountExplicitly(account, accountPassword, null);
mAccountManager.setAuthToken(account, authtokenType, authtoken);
} else {
Log.d("Slime", TAG + "> finishLogin > setPassword");
mAccountManager.setPassword(account, accountPassword);
}
setAccountAuthenticatorResult(intent.getExtras());
setResult(RESULT_OK, intent);
finish();
}
}
This is the error Logs from the logcat
06-30 14:53:46.109: E/AndroidRuntime(6015): FATAL EXCEPTION: main
06-30 14:53:46.109: E/AndroidRuntime(6015): java.lang.NullPointerException
06-30 14:53:46.109: E/AndroidRuntime(6015): at android.os.Bundle.putAll(Bundle.java:281)
06-30 14:53:46.109: E/AndroidRuntime(6015): at android.content.Intent.putExtras(Intent.java:4828)
06-30 14:53:46.109: E/AndroidRuntime(6015): at com.rowland.slumber.LoginActivity$2.onClick(LoginActivity.java:86)
06-30 14:53:46.109: E/AndroidRuntime(6015): at android.view.View.performClick(View.java:2485)
06-30 14:53:46.109: E/AndroidRuntime(6015): at android.view.View$PerformClick.run(View.java:9080)
06-30 14:53:46.109: E/AndroidRuntime(6015): at android.os.Handler.handleCallback(Handler.java:587)
Edit, this is line 86
public void onClick(View v) {
// Since there can only be one AuthenticatorActivity, we call the sign up activity, get his results,
// and return them in setAccountAuthenticatorResult(). See finishLogin().
Intent signup = new Intent(getBaseContext(), RegisterActivity.class);
signup.putExtras(getIntent().getExtras()); //LINE 86
startActivityForResult(signup, REQ_SIGNUP);
}
});
}
Iam passing the extras from Authenticator.java which extends AbstractAccountAuthenticator, in the addAccount() method
#Override
public Bundle addAccount(AccountAuthenticatorResponse response,
String accountType, String authTokenType,
String[] requiredFeatures, Bundle options)
throws NetworkErrorException {
Bundle result;
if (hasAccount(mContext)) {
result = new Bundle();
Intent i = new Intent(mContext, LoginActivity.class);
i.putExtra(LoginActivity.ARG_ACCOUNT_TYPE, accountType);
i.putExtra(LoginActivity.ARG_AUTH_TYPE, authTokenType);
i.putExtra(LoginActivity.ARG_IS_ADDING_NEW_ACCOUNT, true);
i.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE,response);
result.putParcelable(AccountManager.KEY_INTENT, i);
return result;
}
Based on the API:
Intent.getExtras() returns:
the map of all extras previously added with putExtra(), or null if none have been added
My guess would be that you are not passing in any extras and therefore passing null to the Intent.putExtras() method... Or if you think you are you may be doing so incorrectly.
From
getIntent().getStringExtra(ARG_ACCOUNT_NAME);
I can say thay you have used putStringExtra method, instead of putExtras.
Therefore, when you try getIntent().getExtras it is null.
Related
im kinda new to programming and would like to make some sort of like a login and register page. so from my login page i click register and it would go to the register page and i want the username/password i get from the register page to be used in the previous login page to login into the app. But i cant seem to set the username/password using the result. Only able to set the textview. pls help heres the code
public class MainActivity extends AppCompatActivity {
private EditText Name;
private EditText Password;
private TextView Info;
private Button Login;
private int counter = 5;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Name = (EditText)findViewById(R.id.etName);
Password = (EditText)findViewById(R.id.etPass);
Info = (TextView) findViewById(R.id.tvInfo);
Login = (Button)findViewById(R.id.btnLogin);
Info.setText("No Of Attempts Remaining: 5");
Login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
validate(Name.getText().toString(),Password.getText().toString());
}
});
}
private void validate(String userName, String userPassword){
if(userName.equals("") && userPassword.equals("")){
Intent intent = new Intent(MainActivity.this, MenuActivity.class);
startActivity(intent);
}
else{
counter--;
Info.setText("No Of Attempts Remaining: " + String.valueOf(counter));
if(counter == 0){
Login.setEnabled(false);
}
}
}
public void facebooklogin(View myview){
Intent intent = new Intent(this, MenuActivity.class);
startActivity(intent);
}
public void register(View myview) {
Intent i = new Intent(this, RegisterActivity .class);
startActivityForResult(i, 1);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if(resultCode == RESULT_OK) {
String reginame = data.getStringExtra("NAME");
String regipass = data.getStringExtra("PASS");
Name.setText("" + reginame);
Password.setText("" + regipass);
}
}
}
How do i set the
private void validate(String userName, String userPassword){
if(userName.equals("") && userPassword.equals("")){
Intent intent = new Intent(MainActivity.this, MenuActivity.class);
startActivity(intent);
}
to be equal to the onActivityResult reginame and regipass
your condition is wrong it should be like this:-
private void validate(String userName, String userPassword){
if(!userName.equals("") && !userPassword.equals("")){
Intent intent = new Intent(MainActivity.this, MenuActivity.class);
startActivity(intent);
}
First Activity.
Send information
Intent send = new Intent(MainActivity.this, Main2Activity.class);
send.putExtra("login",editText.getText());
send.putExtra("password",editText1.getText());
startActivity(send);
Second Activity.
Get Information
if(getIntent()!=null){
Intent intent = getIntent();
editText.setText(intent.getStringExtra("login")) ;
editText1.setText(intent.getStringExtra("password")) ;
}
I am sending data from one activity to another activity .
but getting error null pointer exception and app is crashed.
Error-
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.a98fit.neeraj.a98fit, PID: 31167
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.BaseBundle.getString(java.lang.String)' on a null object reference
at com.a98fit.neeraj.a98fit.Signup$1.onClick(Signup.java:118)
at android.view.View.performClick(View.java:5612)
at android.view.View$PerformClick.run(View.java:22285)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6123)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
Application terminated.
one activity- i am storing data token & userId in database and sending to another activity via intent.
Intent intent1 = new Intent(Name.this, Signup.class);
intent1.putExtra("userId", userId);
intent1.putExtra("token",token);
startActivity(intent1);
Another activity - where i am getting
Bundle bundle = getIntent().getExtras();
String token = bundle.getString("token").toString();
String userId= bundle.getString("userId");
one activity---
public class Name extends AppCompatActivity {
private static final String TAG = Name.class.getSimpleName();
private Button btn_name_next;
EditText emailid,editTextUserName;
private ProgressDialog pDialog;
private SessionManager session;
private SQLiteHandler db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_name);
btn_name_next = (Button) findViewById(R.id.btn_name_next);
editTextUserName=(EditText) findViewById(R.id.editTextUserName);
final TelephonyManager tm = (TelephonyManager) getBaseContext().getSystemService(Context.TELEPHONY_SERVICE);
final String tmDevice, tmSerial, androidId;
tmDevice = "" + tm.getDeviceId();
tmSerial = "" + tm.getSimSerialNumber();
androidId = "" + Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
UUID deviceUuid = new UUID(androidId.hashCode(), ((long) tmDevice.hashCode() << 32) | tmSerial.hashCode());
final String deviceId = deviceUuid.toString();
Log.e(TAG, "Device Id: " + deviceId);
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
// Session manager
session = new SessionManager(getApplicationContext());
// SQLite database handler
db = new SQLiteHandler(getApplicationContext());
// Check if user is already logged in or not
if (session.isLoggedIn()) {
// User is already logged in. Take him to main activity
Intent intent = new Intent(Name.this,
MakemeHealthy.class);
startActivity(intent);
finish();
}
btn_name_next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String name=editTextUserName.getText().toString();
if (name.length()==0) {
editTextUserName.setError("Tell us your name atleast");
}
else
{
//launchAgeScreen();
registerUser(name, deviceId);
}
}
});
}
private void registerUser(final String name, final String deviceId) {
// Tag used to cancel the request
String tag_string_req = "req_register";
pDialog.setMessage("Registering ...");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.POST,
AppConfig.NAME_REGISTER, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Register Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean success = jObj.getBoolean("success");
//boolean error = jObj.getBoolean("error");
if (success) {
// User successfully stored in MySQL
// Now store the user in sqlite
//String uid = jObj.getString("uid");
String userId =jObj.getString("userId");
String token = jObj.getString("token");
db.addUser( token,userId);
//db.addUser(userId);
Intent intent1 = new Intent(Name.this, Signup.class);
intent1.putExtra("userId", userId);
intent1.putExtra("token",token);
startActivity(intent1);
Log.e(TAG, "token: " + token);
Log.e(TAG, "userId: " + userId);
Toast.makeText(getApplicationContext(), "User successfully registered. Try login now!", Toast.LENGTH_LONG).show();
// Launch login activity
Intent intent = new Intent(
Name.this,
Signup.class);
startActivity(intent);
finish();
} else {
// Error occurred in registration. Get the error
// message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Registration Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("name", name);
//params.put("email", email);
// params.put("password", password);
params.put("deviceId", deviceId);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
another activity- where i am sending data .
protected void onCreate(Bundle savedInstanceState) {
//ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.READ_PHONE_STATE}, 1);
/* if(b!=null)
{
String token =(String) b.get("token");
String userId = (String) b.get("userId");
// Textv.setText(j);
}*/
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
TextView textViewlaer = (TextView) findViewById(R.id.textViewlater);
btn_name_make = (Button) findViewById(R.id.btn_name_make);
editTextEmailid = (EditText) findViewById(R.id.editTextEmailid);
passwordentry = (EditText) findViewById(R.id.passwordentry);
final TelephonyManager tm = (TelephonyManager) getBaseContext().getSystemService(Context.TELEPHONY_SERVICE);
final String tmDevice, tmSerial, androidId;
tmDevice = "" + tm.getDeviceId();
tmSerial = "" + tm.getSimSerialNumber();
androidId = "" + Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
UUID deviceUuid = new UUID(androidId.hashCode(), ((long) tmDevice.hashCode() << 32) | tmSerial.hashCode());
final String deviceId = deviceUuid.toString();
Log.e(TAG, "Device Id: " + deviceId);
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
// Session manager
session = new SessionManager(getApplicationContext());
// SQLite database handler
db = new SQLiteHandler(getApplicationContext());
// Check if user is already logged in or not
if (session.isLoggedIn()) {
// User is already logged in. Take him to main activity
Intent intent = new Intent(Signup.this,
MakemeHealthy.class);
startActivity(intent);
finish();
}
// Make Me Awesome Button Click event
btn_name_make.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = editTextEmailid.getText().toString();
String password = passwordentry.getText().toString();
Bundle bundle = getIntent().getExtras();
String token = bundle.getString("token").toString();
String userId= bundle.getString("userId");
Log.e(TAG, "token: " + token);
Log.e(TAG, "userId: " + userId);
if (email.length() == 0) {
editTextEmailid.setError("Please Enter Email id");
} else if (!Patterns.EMAIL_ADDRESS.matcher(email).matches())
{
editTextEmailid.setError("Please enter Valid Email id");
} else if (password.length() == 0) {
passwordentry.setError("Please Enter password");
} else if (password.length() < 6) {
passwordentry.setError("Please Enter minimum 6 character");
} else {
registerUser(token,userId,email,password);
}
}
});
// I'll do it later Button Click event
textViewlaer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent doitlater = new Intent(Signup.this, Name.class);
startActivity(doitlater);
}
});
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
You made mistake here
startActivity(intent);
You put intent value in intent and start activity is intent1. So please pass intent1 instead of intent
startActivity(intent1);// pass this intent1
Use this code
Intent intent1 = new Intent(Name.this, Signup.class);
intent1.putExtra("userId", userId);
intent1.putExtra("token",token);
startActivity(intent1);
Log.e(TAG, "token: " + token);
Log.e(TAG, "userId: " + userId);
Toast.makeText(getApplicationContext(), "User successfully registered. Try login now!", Toast.LENGTH_LONG).show();
startActivity(intent1);
Your Bundle is null :
try this: in Second activity to get Data
Intent i = getIntent();
String id = i.getStringExtra("userId");
String token = i.getStringExtra("token");
You have called Signup Actvity twice in your code see below code in your code.
Intent intent1 = new Intent(Name.this, Signup.class);
intent1.putExtra("userId", userId);
intent1.putExtra("token",token);
startActivity(intent1);
Log.e(TAG, "token: " + token);
Log.e(TAG, "userId: " + userId);
Toast.makeText(getApplicationContext(), "User successfully registered. Try login now!", Toast.LENGTH_LONG).show();
// Launch login activity
Intent intent = new Intent(Name.this,Signup.class);
startActivity(intent);
finish();
Remove code below your Toast message in your code. like below code:
// Launch Signup activity
Intent intent1 = new Intent(Name.this, Signup.class);
intent1.putExtra("userId", userId);
intent1.putExtra("token",token);
startActivity(intent1);
Log.e(TAG, "token: " + token);
Log.e(TAG, "userId: " + userId);
Toast.makeText(getApplicationContext(), "User successfully registered. Try login now!", Toast.LENGTH_LONG).show();
finish();
For not showing NullPointerException Error try like this:
Bundle bundle = getIntent().getExtras();
if(bundle !=null){
String token = bundle.getString("token").toString();
String userId= bundle.getString("userId");
}
I am trying to integrate paypal as payment in my android app but But i failed with some error like this .
Error:(70, 5) error: no suitable method found for
startService(Intent,int) method ContextWrapper.startService(Intent) is
not applicable (actual and formal argument lists differ in length)
method Context.startService(Intent) is not applicable (actual and
formal argument lists differ in length)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pay);
actionBar = getActionBar();
ColorDrawable colorDrawable = new ColorDrawable(
Color.parseColor("#01bfff"));
actionBar.setBackgroundDrawable(colorDrawable);
btnPayPal = (Button) findViewById(R.id.btnPaypal);
//Intent get value
Intent intent = getIntent();
final String currency = intent.getStringExtra("CURRENCY");
int cost = intent.getIntExtra("COST", 0);
txtCurrency.setText(currency);
txtTotal.setText(String.valueOf(" " + cost));
btnPayPal.setOnClickListener(new OnClickListener() {
public void onClick (View v) {
Intent in = new Intent(this, PayPalService.class);
in.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);
startService(intent,0);
}public void onBuyPressed(View pressed) {
PayPalPayment payment = new PayPalPayment(new BigDecimal("2"), "USD", "Total Ticket Price : ",
PayPalPayment.PAYMENT_INTENT_SALE);
Intent intnt = new Intent(this, PaymentActivity.class);
intnt.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);
intnt.putExtra(PaymentActivity.EXTRA_PAYMENT, payment);
startActivityForResult(intnt, 0);
}
#Override
protected void onActivityResult (int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
PaymentConfirmation confirm = data.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION);
if (confirm != null) {
try {
Log.i("paymentExample", confirm.toJSONObject().toString(4));
} catch (JSONException e) {
Log.e("paymentExample", "an extremely unlikely failure occurred: ", e);
}
}
}
else if (resultCode == Activity.RESULT_CANCELED) {
Log.i("paymentExample", "The user canceled.");
}
else if (resultCode == PaymentActivity.RESULT_EXTRAS_INVALID) {
Log.i("paymentExample", "An invalid Payment or PayPalConfiguration was submitted. Please see the docs.");
}
}
});
It returned expected in
public void onClick (View v) {
Intent in = new Intent(this, PayPalService.class);
in.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);
startService(intent,0);
}
You're doing wrong over here
startService(intent,0);
Change it to
startService(intent);
startService(Intent) has only one argument.
and more information refer Official Service Docs
I use paypal integration using android paypal sdk, and i use this code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(this, PayPalService.class);
intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);
startService(intent);
}
public void onBuyPressed(View pressed) {
PayPalPayment thingToBuy = getThingToBuy(PayPalPayment.PAYMENT_INTENT_SALE);
Intent intent = new Intent(MainActivity.this, PaymentActivity.class);
intent.putExtra(PaymentActivity.EXTRA_PAYMENT, thingToBuy);
startActivityForResult(intent, REQUEST_CODE_PAYMENT);
}
I got error like this request failed with server response:
{"name":"TRANSACTION_REFUSED","message":"The request was refused.{0}","information_link":"https://developer.paypal.com/webapps/developer/docs/api/#TRANSACTION_REFUSED","debug_id":"f1123aecd0ece"}
05-15 13:36:53.530: E/PayPalService(9581): TRANSACTION_REFUSED
anyone help me
public class PaymentConfermationFragment extends Fragment {
private static final String CONFIG_ENVIRONMENT = PaymentActivity.ENVIRONMENT_SANDBOX;
private static final String CONFIG_CLIENT_ID = "ASdSlRC8iBoCu6ehg59npQXZfhfhfhfhfhl6xQVx0IcYKCCUrZNfcdTBI0zdYCroY1ONz";
private static final String CONFIG_RECEIVER_EMAIL = "xyz#gmail.com";
private FragmentManager mFragmentManager;
private TextView frind_name, amount;
private ImageView frind_img;
private GiftekFriend giftekFriend;
private ArrayList<GiftekProduct> productList;
private View mLoadingCover;
private View mPaymentOK;
long price = 0;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.frag_payment_confirmation, container, false);
frind_img = (ImageView) rootView.findViewById(R.id.friend_img);
frind_name = (TextView) rootView.findViewById(R.id.friend_name);
mLoadingCover = rootView.findViewById(R.id.loading_cover);
mPaymentOK = rootView.findViewById(R.id.payment_ok);
amount = (TextView) rootView.findViewById(R.id.amount);
((ActionBarActivity) getActivity()).getSupportActionBar().setTitle("Payment");
giftekFriend = AppData.getInstance().getGiftekFriend();
if (giftekFriend != null) {
String name = giftekFriend.first_name + " " + giftekFriend.last_name;
frind_name.setText(name);
}
productList = AppData.getInstance().getProductList();
Intent intent = new Intent(this.getActivity(), PayPalService.class);
intent.putExtra(PaymentActivity.EXTRA_PAYPAL_ENVIRONMENT, CONFIG_ENVIRONMENT);
intent.putExtra(PaymentActivity.EXTRA_CLIENT_ID, CONFIG_CLIENT_ID);
intent.putExtra(PaymentActivity.EXTRA_RECEIVER_EMAIL, CONFIG_RECEIVER_EMAIL);
getActivity().startService(intent);
rootView.findViewById(R.id.payment_button).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
paymentStart();
}
});
new Imageloder().execute();
mFragmentManager = getActivity().getSupportFragmentManager();
return rootView;
}
protected void paymentStart() {
PayPalPayment thingToBuy = new PayPalPayment(new BigDecimal(Integer.parseInt(amount.getText().toString())), "USD", "Giftek Gifts");
Intent intent = new Intent(this.getActivity(), PaymentActivity.class);
intent.putExtra(PaymentActivity.EXTRA_PAYPAL_ENVIRONMENT, CONFIG_ENVIRONMENT);
intent.putExtra(PaymentActivity.EXTRA_CLIENT_ID, CONFIG_CLIENT_ID);
intent.putExtra(PaymentActivity.EXTRA_RECEIVER_EMAIL, CONFIG_RECEIVER_EMAIL);
intent.putExtra(PaymentActivity.EXTRA_CLIENT_ID, "credential-from-developer.paypal.com");
intent.putExtra(PaymentActivity.EXTRA_PAYER_ID, "your-customer-id-in-your-system");
intent.putExtra(PaymentActivity.EXTRA_PAYMENT, thingToBuy);
startActivityForResult(intent, 0);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
PaymentConfirmation confirm = data.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION);
onPaymentSuccess();
if (confirm != null) {
try {
System.out.print(confirm.toJSONObject().toString(4));
Log.i("paymentExample", confirm.toJSONObject().toString(3));
Log.i("paymentExample", confirm.toJSONObject().toString(2));
Log.i("paymentExample", confirm.toJSONObject().toString(1));
Log.i("paymentExample", confirm.toJSONObject().toString(0));
} catch (JSONException e) {
Log.e("paymentExample", "an extremely unlikely failure occurred: ", e);
}
}
} else if (resultCode == Activity.RESULT_CANCELED) {
onPaymentCancel();
Log.i("paymentExample", "The user canceled.");
} else if (resultCode == PaymentActivity.RESULT_PAYMENT_INVALID) {
onPaymentInvalid();
Log.i("paymentExample", "An invalid payment was submitted. Please see the docs.");
}
}
private void onPaymentInvalid() {
Bundle args = new Bundle();
args.putString("result", "Payment Invalid");
mFragmentManager.popBackStack("giftek-process-select-friend", 0);
mFragmentManager.beginTransaction()
.replace(R.id.container, ResultFragment.instantiate(getActivity(), ResultFragment.class.getName(), args))
.addToBackStack("result").commit();
}
private void onPaymentCancel() {
Bundle args = new Bundle();
args.putString("result", "Payment Cancel");
mFragmentManager.popBackStack("giftek-process-select-friend", 0);
mFragmentManager.beginTransaction()
.replace(R.id.container, ResultFragment.instantiate(getActivity(), ResultFragment.class.getName(), args))
.addToBackStack("result").commit();
}
private void onPaymentSuccess() {
Bundle args = new Bundle();
args.putString("result", "Order has been completed successfully.");
mFragmentManager.popBackStack("giftek-process-select-friend", 0);
mFragmentManager.beginTransaction()
.replace(R.id.container, ResultFragment.instantiate(getActivity(), ResultFragment.class.getName(), args))
.addToBackStack("result").commit();
}
#Override
public void onDestroy() {
getActivity().stopService(new Intent(getActivity(), PayPalService.class));
super.onDestroy();
}
I try to pass a string from one activity to another activity.
This is the coding in Activity A:
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putString("UserName", UserName);
Log.i(Tag, "UserName1: "+ UserName);
super.onSaveInstanceState(savedInstanceState);
}
In Activity B I use this code to get the string:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_item);
setUpViews();
if (savedInstanceState != null){
UserName = savedInstanceState.getString("UserName");
}
Log.i(Tag, "UserName2: "+ UserName);
}
But the logcat shown the first log "UserName1" when I clikc the open to Activity B,
and show the second log "UserName2" as "null".
May I know what wrong with my code?
What I want to do is Activity A pass the String in Activity B when I click the "button" and intent to Activity B. So I can get the String value in Activity B.
Any Idea? Cause I getting error when using intent.putStringExtra() and getintent.getStringExtra(), so I change to use onSaveInstanceState (), but still having problem.
EDIT:
This is my original code, I can get the String in Activity B, but unexpected I can't save my data in Sqlite. If remove the putString Extra then everything go smoothly.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent addItem = new Intent(ItemActivity.this, AddEditItem.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
addItem.putStringExtra("UserName", UserName);
Log.e(Tag, "UseName: "+ UserName);
startActivity(addItem);
return super.onOptionsItemSelected(item);
}
Code in Activity B:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_item);
setUpViews();
UserName = (String) getIntent().getStringExtra("UserName");
Log.e(Tag, "UserName3: "+ UserName);
}
Full code for Activity B:
public class AddEditItem extends Activity implements OnItemSelectedListener {
private static final String Tag = null;
private EditText inputItemName;
private EditText inputItemCondition;
private EditText inputEmail;
private Button btnGal, btnConfirm;
private Bitmap bmp;
private ImageView ivGalImg;
private Spinner spinner;
String[] category = {"Books", "Clothes & Shoes", "Computer", "Electronics", "Entertainment", "Food & Drinks",
"Furnitures", "Mobile Phone", "Other", "UKM"};
String selection;
String filePath, itemName, itemCondition;
String UserName, user;
private int id;
private byte[] blob=null;
byte[] byteImage2 = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_item);
setUpViews();
if (savedInstanceState != null){
UserName = savedInstanceState.getString("UserName");
}
Log.e(Tag, "UserName2: "+ UserName);
//UserName = (String) getIntent().getStringExtra("UserName");
//Log.e(Tag, "UserName3: "+ UserName);
}
private void setUpViews() {
inputItemName = (EditText)findViewById(R.id.etItemName);
inputItemCondition = (EditText)findViewById(R.id.etItemCondition);
inputEmail = (EditText)findViewById(R.id.etEmail);
ivGalImg = (ImageView) findViewById(R.id.ivImage);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(AddEditItem.this, android.R.layout.simple_spinner_dropdown_item, category);
spinner = (Spinner)findViewById(R.id.spnCategory);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
Bundle extras = getIntent().getExtras();
if (extras != null) {
id=extras.getInt("id");
user=extras.getString("user");
inputItemName.setText(extras.getString("name"));
inputItemCondition.setText(extras.getString("condition"));
inputEmail.setText(extras.getString("email"));
selection = extras.getString("category");
byteImage2 = extras.getByteArray("blob");
if (byteImage2 != null) {
if (byteImage2.length > 3) {
ivGalImg.setImageBitmap(BitmapFactory.decodeByteArray(byteImage2,0,byteImage2.length));
}
}
}
btnGal = (Button) findViewById(R.id.bGallary);
btnGal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, 0);
}
});
btnConfirm = (Button) findViewById(R.id.bConfirm);
btnConfirm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (inputItemName.getText().length() != 0 && inputItemCondition.getText().length() != 0
&& inputEmail.getText().length() != 0) {
AsyncTask<Object, Object, Object> saveItemTask = new AsyncTask<Object, Object, Object>() {
#Override
protected Object doInBackground(Object... params) {
saveItem();
return null;
}
#Override
protected void onPostExecute(Object result) {
Toast.makeText(getApplicationContext(),
"Item saved", Toast.LENGTH_LONG)
.show();
finish();
}
};
saveItemTask.execute((Object[]) null);
Toast.makeText(getApplicationContext(),
"Item saved reconfirm", Toast.LENGTH_LONG)
.show();
} else {
AlertDialog.Builder alert = new AlertDialog.Builder(
AddEditItem.this);
alert.setTitle("Error In Save Item");
alert.setMessage("You need to fill in all the item details");
alert.setPositiveButton("OK", null);
alert.show();
}
}
});
}
private void saveItem() {
if(bmp!=null){
ByteArrayOutputStream outStr = new ByteArrayOutputStream();
bmp.compress(CompressFormat.JPEG, 100, outStr);
blob = outStr.toByteArray();
}
else{blob=byteImage2;}
ItemSQLiteConnector sqlCon = new ItemSQLiteConnector(this);
if (getIntent().getExtras() == null) {
sqlCon.insertItem(UserName, inputItemName.getText().toString(),
inputItemCondition.getText().toString(),
inputEmail.getText().toString(),
selection, blob);
}
else {
sqlCon.updateItem(id, UserName, inputItemName.getText().toString(),
inputItemCondition.getText().toString(),
inputEmail.getText().toString(),
selection, blob);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode,Intent resultdata) {
super.onActivityResult(requestCode, resultCode, resultdata);
switch (requestCode) {
case 0:
if (resultCode == RESULT_OK) {
Uri selectedImage = resultdata.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
// Convert file path into bitmap image using below line.
bmp = BitmapFactory.decodeFile(filePath);
ivGalImg.setImageBitmap(bmp);
}
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// TODO Auto-generated method stub
TextView tv = (TextView)view;
selection = tv.getText().toString();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
onSaveInstanceState is not used in that purpose, its used to save your activity state on for example orientation change, or when you leave an activity and get back to it.
What you need is to use intents.
Other than starting activity, intents can also carry some information throughout app, like this:
This would be activity 1:
Intent = new Intent (getApplicationContext(), Activity2.class);
intent.putExtra("UserName", UserName);
startActivity(intent);
and to recover it in second activity use:
String username = getIntent().getExtras().getString("UserName");
May I know what wrong with my code?
onSaveInstanceState() has nothing to do with passing data between activities. Instead, you need to put your string in an extra on the Intent used with startActivity().
Cause I getting error when using intent.putExtra() and getintent.getExtra()
Since that is the correct approach (albeit using getStringExtra()), please go back to it and fix whatever error you are encountering.