getting error when passing data from one activity to another activity - android

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

Related

Login Details using Content Provider, brings many loop

I want to create a Toast Text (about I haven't registered in the database) on the Login Activity. However, there is a problem when I put this Toast text. If I put it inside a while loop Cursor.MoveToNext(), it will loop as many times as many entries it has.
Inside the loop
if(cursor!=null)
{
{
int i = 0;
while(cursor.moveToNext())
{
if(cursor.getString(i).equals(input_email) && cursor.getString(i).equals(input_password))
{
Log.d(TAG, "Udah masuk belum " );
Toast.makeText(getApplicationContext(),"Login Successful!", Toast.LENGTH_SHORT).show();
Intent intent =new Intent(LoginActivity.this, RegisterActivity.class);
startActivity(intent);
finish();
i = i + 1;
}
else
{
Toast.makeText(getApplicationContext(),"You haven't Registered yet!", Toast.LENGTH_SHORT).show();
Intent intent =new Intent(LoginActivity.this, RegisterActivity.class);
startActivity(intent);
finish();
}
}
cursor.close();
}
}
But when I putted outside of the loop, it brings error. Do you know what is the solution of this one?
Outside the loop
String [] projection ={ServiceProvidersContract.Columns.SEmail, ServiceProvidersContract.Columns.spPassword};
Cursor cursor = contentResolver.query(ServiceProvidersContract.CONTENT_URI, projection, null, null, null);
Log.d(TAG, "Checking Cursor" + cursor );
if(cursor!=null)
{
{
int i = 0;
while(cursor.moveToNext())
{
if(cursor.getString(i).equals(input_email) && cursor.getString(i).equals(input_password))
{
Log.d(TAG, "Udah masuk belum " );
Toast.makeText(getApplicationContext(),"Login Successful!", Toast.LENGTH_SHORT).show();
Intent intent =new Intent(LoginActivity.this, RegisterActivity.class);
startActivity(intent);
finish();
i = i + 1;
}
}
cursor.close();
if(!cursor.getString(i).equals(input_email) && cursor.getString(i).equals(input_password))
{
Toast.makeText(getApplicationContext(),"You haven't Registered yet!", Toast.LENGTH_SHORT).show();
Intent intent =new Intent(LoginActivity.this, RegisterActivity.class);
startActivity(intent);
finish();
}
}
}
Just want to clarify, I did finally login successfully in my login parts using For and While.
The other problem is coming from the Toast Text ( where I couldn't put the failed Toast Text in the loop). This is my codes :
private static final String TAG = "LoginActivity";
private Button btnLogin, btnLinkToRegister;
private SessionManager session;
private EditText password, email;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
// Defining everything
email = (EditText) findViewById(R.id.email);
password = (EditText) findViewById(R.id.password);
btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegister);
btnLogin = (Button) findViewById(R.id.btnLogin);
// Login button Click Event
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
ContentResolver contentResolver = getContentResolver() ;
String input_email = email.getText().toString().trim();
String input_password = password.getText().toString().trim();
Log.d(TAG, "onClick: " + input_email + input_password);
// Check for empty data in the form
if (!input_email.isEmpty() && !input_password.isEmpty()) {
Log.d(TAG, "onClick: if statement succeseful");
// checking from the database
String [] projection ={ServiceProvidersContract.Columns.SEmail, ServiceProvidersContract.Columns.spPassword};
Cursor cursor = contentResolver.query(ServiceProvidersContract.CONTENT_URI, projection, null, null, null);
Log.d(TAG, "Checking Cursor" + cursor );
if(cursor!=null)
{
cursor.moveToFirst();
while(cursor.moveToNext())
{
Log.d(TAG, "while process");
for(int i=0; i<cursor.getColumnCount(); i++)
{
Log.d(TAG, "for process " + cursor.getString(i));
if (cursor.getString(0).equals(input_email) && cursor.getString(1).equals(input_password)) {
Log.d(TAG, "if process");
Toast.makeText(getApplicationContext(), "Login Successful!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
startActivity(intent);
finish();
break;
}
}
}
if (!cursor.getString(0).equals(input_email) && cursor.getString(1).equals(input_password)) {
Log.d(TAG, "if process");
Toast.makeText(getApplicationContext(), "You haven't registered yet!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
startActivity(intent);
finish();
}
cursor.close();
}
} else {
// Prompt user to enter credentials
Toast.makeText(getApplicationContext(),
"Please enter the credentials!", Toast.LENGTH_LONG)
.show();
}
}
});
btnLinkToRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view){
Intent i = new Intent(LoginActivity.this, RegisterActivity.class);
startActivity(i);
finish();
}
});
}
}

Android payapal integration

this is my first question on stackoverflow.hope i can find my solutuon .i am integrating paypal in android.my device is showing "payment of this marchent are not allowed(invalid client id).here is my code
private static final String CONFIG_ENVIRONMENT = PayPalConfiguration.ENVIRONMENT_PRODUCTION;
// note that these credentials will differ between live & sandbox
// environments.
private static final String CONFIG_CLIENT_ID ="my client id";
private static final int REQUEST_CODE_PAYMENT = 1;
private static final int REQUEST_CODE_FUTURE_PAYMENT = 2;
private static PayPalConfiguration config = new PayPalConfiguration()
.environment(CONFIG_ENVIRONMENT)
.clientId(CONFIG_CLIENT_ID)
// The following are only used in PayPalFuturePaymentActivity.
.merchantName("Rajeev Lochan Sharma")
.merchantPrivacyPolicyUri(
Uri.parse("https://www.example.com/privacy"))
.merchantUserAgreementUri(
Uri.parse("https://www.example.com/legal"));
PayPalPayment thingToBuy;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_afcl);
final GlobalClass globalVariable = (GlobalClass) getApplicationContext();
Intent intent = new Intent(this, PayPalService.class);
intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startService(intent);
ButterKnife.inject(this);
_request3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// signup();
new Test().execute(_names.getText().toString(), _placeofbirth.getText().toString(), _timeofbirth.getText().toString()
);
thingToBuy = new PayPalPayment(new BigDecimal("10"), "USD",
"quote", PayPalPayment.PAYMENT_INTENT_SALE);
Intent intent = new Intent(AfcRequest1Activity.this,
PaymentActivity.class);
intent.putExtra(PaymentActivity.EXTRA_PAYMENT, thingToBuy);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivityForResult(intent, REQUEST_CODE_PAYMENT);
}
});
}
public void onBackPressed() {
new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_alert).setTitle("Exit")
.setMessage("Are you sure you want to exit?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
}).setNegativeButton("No", null).show();
}
private class Test extends AsyncTask {
protected void onPreExecute() {
super.onPreExecute();
//here you can some progress dialog or some view
}
#Override
protected String doInBackground(String... Params) {
String res = "";
try {
byte[] result = null;
String str = "";
HttpClient client;
HttpPost post;
ArrayList<NameValuePair> nameValuePair;
HashMap<String, String> mData;
Iterator<String> it;
HttpResponse response;
StatusLine statusLine;
//here is url api call url
post = new HttpPost("http://astro360horoscope.com/backend/api/form_amc_afc.php");
nameValuePair = new ArrayList<NameValuePair>();
mData = new HashMap<String, String>();
mData.put("username", Params[0]);
mData.put("placeofbirth", Params[1]);
mData.put("timeofbirth", Params[2]);
//for now nothing is there
it = mData.keySet().iterator();
while (it.hasNext()) {
String key = it.next();
nameValuePair.add(new BasicNameValuePair(key, mData.get(key)));
}
post.setEntity(new UrlEncodedFormEntity(nameValuePair, "utf-8"));
client = new DefaultHttpClient();
response = client.execute(post);
statusLine = response.getStatusLine();
result = EntityUtils.toByteArray(response.getEntity());
str = new String(result, "utf-8");
if (statusLine.getStatusCode() == HttpURLConnection.HTTP_OK) {
//here we get the response if all is correct
res = str;
} else {
res = str;
return res;
}
} catch (Exception e1) {
res = "error:" + e1.getMessage().toString();
e1.printStackTrace();
}
return res;
}
protected void onPostExecute(String response) {
super.onPostExecute(response);
}
}
public void onFuturePaymentPressed(View pressed) {
Intent intent = new Intent(AfcRequest1Activity.this,
PayPalFuturePaymentActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivityForResult(intent, REQUEST_CODE_FUTURE_PAYMENT);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_PAYMENT) {
if (resultCode == Activity.RESULT_OK) {
PaymentConfirmation confirm = data
.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION);
if (confirm != null) {
try {
System.out.println(confirm.toJSONObject().toString(4));
System.out.println(confirm.getPayment().toJSONObject()
.toString(4));
Toast.makeText(getApplicationContext(), "Order placed",
Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
} else if (resultCode == Activity.RESULT_CANCELED) {
System.out.println("The user canceled.");
} else if (resultCode == PaymentActivity.RESULT_EXTRAS_INVALID) {
System.out
.println("An invalid Payment or PayPalConfiguration was submitted. Please see the docs.");
}
} else if (requestCode == REQUEST_CODE_FUTURE_PAYMENT) {
if (resultCode == Activity.RESULT_OK) {
PayPalAuthorization auth = data
.getParcelableExtra(PayPalFuturePaymentActivity.EXTRA_RESULT_AUTHORIZATION);
if (auth != null) {
try {
Log.i("FuturePaymentExample", auth.toJSONObject()
.toString(4));
String authorization_code = auth.getAuthorizationCode();
Log.i("FuturePaymentExample", authorization_code);
sendAuthorizationToServer(auth);
Toast.makeText(getApplicationContext(),
"Future Payment code received from PayPal",
Toast.LENGTH_LONG).show();
} catch (JSONException e) {
Log.e("FuturePaymentExample",
"an extremely unlikely failure occurred: ", e);
}
}
} else if (resultCode == Activity.RESULT_CANCELED) {
Log.i("FuturePaymentExample", "The user canceled.");
} else if (resultCode == PayPalFuturePaymentActivity.RESULT_EXTRAS_INVALID) {
Log.i("FuturePaymentExample",
"Probably the attempt to previously start the PayPalService had an invalid PayPalConfiguration. Please see the docs.");
}
}
}
private void sendAuthorizationToServer(PayPalAuthorization authorization) {
}
public void onFuturePaymentPurchasePressed(View pressed) {
// Get the Application Correlation ID from the SDK
String correlationId = PayPalConfiguration
.getApplicationCorrelationId(this);
Log.i("FuturePaymentExample", "Application Correlation ID: "
+ correlationId);
// TODO: Send correlationId and transaction details to your server for
// processing with
// PayPal...
Toast.makeText(getApplicationContext(),
"App Correlation ID received from SDK", Toast.LENGTH_LONG)
.show();
}
#Override
public void onDestroy() {
// Stop service when done
stopService(new Intent(this, PayPalService.class));
super.onDestroy();
}

jav.nullPointer .Exception when using Intent's putExtra() method

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.

Google+ login, fetching user data using new google services

I am implementing login with google using the new google services version 4.2, I am creating my google client as follows:
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addApi(Plus.API)
.addScope(Plus.SCOPE_PLUS_PROFILE)
.addScope(Plus.SCOPE_PLUS_LOGIN)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
With only SCOPE_PLUS_LOGIN it does not work- internal error. However I can login using this ApiClient and following the instructions found at google. But whenever I am trying to access any information via
Plus.PeopleApi.getCurrentPerson(mGoogleApiClient)
The object is empty, I have added my SHA-1 key to my console, and have no idea what could go wrong.
Thanks for any answers
Try with this method:
private static final int REQUEST_CODE_GPLUS = 9000;
private static final String TAG_GPLUS = "google";
private ProgressDialog mProgressDialogGplus;
private PlusClient mPlusClient;
private ConnectionResult mConnectionResult;
mPlusClient = new PlusClient.Builder(SignUpActiivty.this, callbacks,
connectionFailedListener).setActions(
"http://schemas.google.com/AddActivity",
"http://schemas.google.com/BuyActivity")
// .setScopes(Scopes.PLUS_PROFILE) // recommended login scope
// for social features
.build();
mProgressDialogGplus = new ProgressDialog(SignUpActiivty.this);
mProgressDialogGplus.setCancelable(false);
mProgressDialogGplus.setMessage("Signing in...");
mProgressDialogGplus.show();
mPlusClient.connect();
Methods:
1. ConnectionCallbacks callbacks = new ConnectionCallbacks() {
public void onDisconnected() {
Log.v(TAG_GPLUS, "disconnected");
}
#Override
public void onConnected(Bundle arg0) {
Log.v(TAG_GPLUS, "onConnected");
mProgressDialogGplus.dismiss();
String accountName = mPlusClient.getAccountName();
Toast.makeText(SignUpActiivty.this, accountName + " is connected.",
Toast.LENGTH_LONG).show();
if (mPlusClient.getCurrentPerson() != null) {
Person currentPerson = mPlusClient.getCurrentPerson();
saveGooglePlusUserData(currentPerson);
}
}
};
2. OnConnectionFailedListener connectionFailedListener = new OnConnectionFailedListener() {
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.v(TAG_GPLUS, "onConnectionFailed result = " + result);
if (mProgressDialogGplus.isShowing()) {
// The user clicked the sign-in button already. Start to resolve
// connection errors. Wait until onConnected() to dismiss the
// connection dialog.
if (result.hasResolution()) {
Log.v(TAG_GPLUS,
"onConnectionFailed result.hasResolution() = "
+ result);
try {
result.startResolutionForResult(SignUpActiivty.this,
REQUEST_CODE_GPLUS);
} catch (SendIntentException e) {
mPlusClient.connect();
}
}
}
// Save the intent so that we can start an activity when the user
// clicks the sign-in button.
mConnectionResult = result;
}
};
In onActivityResult :
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.v(TAG, "requestCode = " + requestCode + " resultCode = "
+ resultCode);
if (requestCode == REQUEST_CODE_GPLUS && resultCode == RESULT_OK) {
Log.v(TAG, "requestCode = " + requestCode + " resultCode = "
+ resultCode);
mConnectionResult = null;
mPlusClient = new PlusClient.Builder(SignUpActiivty.this,
callbacks, connectionFailedListener).setActions(
"http://schemas.google.com/AddActivity",
"http://schemas.google.com/BuyActivity").build();
mPlusClient.connect();
}
}
And method saveGooglePlusUserData is:
private void saveGooglePlusUserData(Person currentPerson) {
int gender_id = currentPerson.getGender();
Person.Name name = currentPerson.getName();
String account_id = currentPerson.getId();
String email = mPlusClient.getAccountName();
String bDate = currentPerson.getBirthday();
int ageGroup = countGPlusUserAge(bDate);
// Person.Name name = {"familyName":"surname","givenName":"Name"}
// BirthDate = 1988-04-24
String firstName = "";
String lastName = "";
try {
JSONObject jObj = new JSONObject(name.toString());
firstName = jObj.getString("givenName");
lastName = jObj.getString("familyName");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.v(TAG_GPLUS, "FirstName = " + firstName + " Name = " + name);
Log.v(TAG_GPLUS, "LastName = " + lastName);
Log.v(TAG_GPLUS, "Account_id = " + account_id);
Log.v(TAG_GPLUS, "Email = " + email);
Log.v(TAG_GPLUS, "Gender ID = " + gender_id);
Log.v(TAG_GPLUS, "BirthDate = " + bDate);
}
Hope this will help you.
When I used SCOPE_PLUS_PROFILE it would connect but I would get nothing when I used both scopes it would do the same and when I used just the login it wouldn't connect. For me the reason was because I changed my package name and I didn't change it in the client id on google developers console. You might not have exactly the same situation but try to check if your client id info is correct.

I don't get RSS feed values.. I think error in getting Feed values

I am new to JSON. Please any one give a sample code for getting JSON Values...
when i click login button, i want to get User Token valules from Json object..please help me..
here is my code..
Thank you in advanced..
public void onClick(View v) {
switch(v.getId()){
case R.id.btnLogin:
txtUserName=(EditText)this.findViewById(R.id.txtUname);
txtPassword=(EditText)this.findViewById(R.id.txtPwd);
String uname = txtUserName.getText().toString();
String pass = txtPassword.getText().toString();
if(uname.equals("") || uname == null){
Toast.makeText(getApplicationContext(), "Username Empty", Toast.LENGTH_SHORT).show();
}else if(pass.equals("") || pass == null){
Toast.makeText(getApplicationContext(), "Password Empty", Toast.LENGTH_SHORT).show();
}else{
boolean validLogin = validateLogin(uname, pass, Loginpage.this);
if(validLogin){
}
}
break;
case R.id.btnCancel:
Intent i = new Intent(Loginpage.this,Loginpage.class);
startActivity(i);
//finish();
break;
}
}
private boolean validateLogin(String uname, String pass, Loginpage loginpage) {
System.out.println("UserToken...");
loginuser();
Intent intent = new Intent(Loginpage.this, Main.class);
intent.putExtra("tokenNumber", token);
startActivity(intent);
return true;
}
private void loginuser() {
// TODO Auto-generated method stub
JSONObject json = JSONfunctions.getJSONfromURL("http://xxx.xxx.x.xxx/my url link...");
token = null;
try {
token = json.getString("UserToken");
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println("UserToken:"+token);
}
You must search the web to get Example.Bye the way Here is a link.3 minute to json
You must also go to this site to make everything clearJson

Categories

Resources