android:onClick doesnot work - android

I am using navigation drawer in activity like this.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_registration);
FrameLayout contentFrameLayout=(FrameLayout)findViewById(R.id.contentView);
getLayoutInflater().inflate(R.layout.activity_registration,contentFrameLayout);
register=(Button)findViewById(R.id.register);
rname=(EditText)findViewById(R.id.name);
rmobile=(EditText)findViewById(R.id.mobile);
remail=(EditText)findViewById(R.id.email);
rpassword=(EditText)findViewById(R.id.password);
}
public void register(View v)
{
new DoRegistration().execute();
}
public class DoRegistration extends AsyncTask<Void,Void,Void>
{
JSONObject registrationResult;
#Override
protected Void doInBackground(Void... voids)
{
List<Pair> param=new ArrayList<>();
param.add(new Pair("R_name",rname.getText().toString()));
param.add(new Pair("R_mobile",rmobile.getText().toString()));
param.add(new Pair("R_email",remail.getText().toString()));
param.add(new Pair("R_password",rpassword.getText().toString()));
registrationResult=serviceHelper.Registration(param);
return null;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
register.setEnabled(false);
}
#Override
protected void onPostExecute(Void aVoid)
{
super.onPostExecute(aVoid);
register.setEnabled(true);
if(registrationResult!=null) {
try {
if (registrationResult.getString("status").equals("done")) {
Intent LoginIntent = new Intent(Registration.this, Login.class);
LoginIntent.putExtra("Msg", "Registered Successfully.. Login Now");
startActivity(LoginIntent);
} else {
}
} catch (Exception e) {
}
}
}
}
So onclick doesnot work.now how to access setContentView.
when register detail error occure could not find onclick method.
activity_registration
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="top|center">
<Button
android:id="#+id/register"
android:layout_width="190dp"
android:layout_height="50dp"
android:text="#string/reg"
android:textSize="20sp"
style="#style/button"
android:background="#drawable/button"
android:onClick="register"
/>
</LinearLayout>
why this error occure.

Try to add a listener to the registration button , and remove the onclick trigger from the layout.
View rootView = inflater.inflate(R.layout.activity_registration,contentFrameLayout);
register = (Button) rootView.findViewById(R.id.register);
register.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
new DoRegistration().execute();
}
});

Related

ProgressBar is not stopping

My app contained a login button and whenever that button is pressed, I want some Progress Bar to show up so that the user knows there is something happening. I've Progress Bar in XML but now i don't know how to set it in code. Please guide me where to put lines as when I press login button a Progress Bar shown up, here is my code
<ProgressBar
android:id="#+id/loading"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/layout_password"
android:layout_marginTop="30dp"
android:visibility="gone"/>
<Button
android:id="#+id/login"
android:layout_width="match_parent"
android:layout_height="55dp"
android:text="login"
android:layout_below="#id/layout_password"
android:layout_marginTop="30dp"/>
MainActivity.java
public class MainActivity extends AppCompatActivity {
TextView textView;
EditText email,password;
Button login;
String url="http://192.168.1.5/Register/login.php" ;
AlertDialog.Builder builder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView=findViewById(R.id.register);
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(MainActivity.this,Register.class);
startActivity(intent);
}
});
email=findViewById(R.id.email);
password=findViewById(R.id.password);
login=findViewById(R.id.login);
builder=new AlertDialog.Builder(MainActivity.this);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String user_email=email.getText().toString();
final String user_password=password.getText().toString();
if (user_email.equals("")||user_password.equals("")){
builder.setTitle("Something Went Wrong...");
dispalyAlert("Enter a valid Email and Password");
}
else {
StringRequest stringRequest=new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jsonArray=new JSONArray(response);
JSONObject jsonObject=jsonArray.getJSONObject(0);
String code=jsonObject.getString("code");
if (code.equals("login_failed")){
builder.setTitle("Login Error...");
dispalyAlert(jsonObject.getString("message"));
}
else {
Intent intent=new Intent(MainActivity.this,LoginSuccess.class);
Bundle bundle=new Bundle();
bundle.putString("name",jsonObject.getString("name"));
// bundle.putString("email",jsonObject.getString("email"));
intent.putExtras(bundle);
startActivity(intent);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this,"Error",Toast.LENGTH_LONG).show();
error.printStackTrace();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params=new HashMap<>();
params.put("email",user_email);
params.put("password",user_password);
return params;
}
};
MySingleton.getInstance(MainActivity.this).addToRequestQueue(stringRequest);
}
}
});
}
private void dispalyAlert(String message){
builder.setMessage(message);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
email.setText("");
password.setText("");
}
});
AlertDialog alertDialog=builder.create();
alertDialog.show();
}
You can achieve this as following. you don't have to add the progressBar in xml.
public class MainActivity extends AppCompatActivity {
TextView textView;
EditText email,password;
Button login;
String url="http://192.168.1.5/Register/login.php" ;
//To show the progressBar
private ProgressDialog progress;
AlertDialog.Builder builder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Prepare progressBar
progress = new ProgressDialog(this);
progress.setTitle("Please Wait!!");
progress.setMessage("Wait!!");
progress.setCancelable(false);
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
textView=findViewById(R.id.register);
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(MainActivity.this,Register.class);
startActivity(intent);
}
});
email=findViewById(R.id.email);
password=findViewById(R.id.password);
login=findViewById(R.id.login);
builder=new AlertDialog.Builder(MainActivity.this);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String user_email=email.getText().toString();
final String user_password=password.getText().toString();
if (user_email.equals("")||user_password.equals("")){
builder.setTitle("Something Went Wrong...");
dispalyAlert("Enter a valid Email and Password");
}
else {
//Show the progressBar
progress.show();
StringRequest stringRequest=new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//Hide the progressBar
progress.dismiss();
try {
JSONArray jsonArray=new JSONArray(response);
JSONObject jsonObject=jsonArray.getJSONObject(0);
String code=jsonObject.getString("code");
if (code.equals("login_failed")){
builder.setTitle("Login Error...");
dispalyAlert(jsonObject.getString("message"));
}
else {
Intent intent=new Intent(MainActivity.this,LoginSuccess.class);
Bundle bundle=new Bundle();
bundle.putString("name",jsonObject.getString("name"));
// bundle.putString("email",jsonObject.getString("email"));
intent.putExtras(bundle);
startActivity(intent);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Hide the progressBar
progress.dismiss();
Toast.makeText(MainActivity.this,"Error",Toast.LENGTH_LONG).show();
error.printStackTrace();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params=new HashMap<>();
params.put("email",user_email);
params.put("password",user_password);
return params;
}
};
MySingleton.getInstance(MainActivity.this).addToRequestQueue(stringRequest);
}
}
});
}
private void dispalyAlert(String message){
builder.setMessage(message);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
email.setText("");
password.setText("");
}
});
AlertDialog alertDialog=builder.create();
alertDialog.show();
}
}
You should be set progress bar visible when user click on button:
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String user_email=email.getText().toString();
final String user_password=password.getText().toString();
if (user_email.equals("")||user_password.equals("")){
builder.setTitle("Something Went Wrong...");
dispalyAlert("Enter a valid Email and Password");
}else{ //Right here
findViewById(R.id.loading).setVisible(View.VISIBLE);
You have to set visibility to gone when stop to load :
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jsonArray=new JSONArray(response);
JSONObject jsonObject=jsonArray.getJSONObject(0);
String code=jsonObject.getString("code");
if (code.equals("login_failed")){
builder.setTitle("Login Error...");
dispalyAlert(jsonObject.getString("message"));
}
else {
Intent intent=new Intent(MainActivity.this,LoginSuccess.class);
Bundle bundle=new Bundle();
bundle.putString("name",jsonObject.getString("name"));
// bundle.putString("email",jsonObject.getString("email"));
intent.putExtras(bundle);
startActivity(intent);
}
} catch (JSONException e) {
e.printStackTrace();
}
findViewById(R.id.loading).setVisible(View.GONE); ////Here
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
findViewById(R.id.loading).setVisible(View.GONE); //Here
Toast.makeText(MainActivity.this,"Error",Toast.LENGTH_LONG).show();
error.printStackTrace();
}

Getting error while clicking on the button on which I am calling Async task? [duplicate]

This question already has answers here:
Null pointer Exception - findViewById()
(12 answers)
Closed 4 years ago.
Here is my code in which on clicking I am calling AttemptLogin method.
class NewActivity extends AppCompatActivity implements View.OnClickListener {
EditText editEmail, editPassword, editName;
Button btnSignIn, btnRegister;
private ProgressDialog pDialog;
String URL= "https://xyz/restapi/registration";
JSONParser jsonParser=new JSONParser();
int i=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnRegister=(Button)findViewById(R.id.btnRegister);
btnRegister.setOnClickListener(this);
/*btnSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AttemptLogin attemptLogin= new AttemptLogin();
attemptLogin.execute(editName.getText().toString(),editPassword.getText().toString(),"");
}
});*/
/*btnRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new AttemptLogin().execute();
}
});*/
}
#Override
public void onClick(View v) {
new AttemptLogin().execute();
}
private class AttemptLogin extends AsyncTask<String, String, JSONObject> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NewActivity.this);
pDialog.setMessage("Attempting for registering...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
ArrayList params = new ArrayList();
params.add(new BasicNameValuePair("cust_firstname", "Sai"));
params.add(new BasicNameValuePair("cust_lastname", "Kumar"));
params.add(new BasicNameValuePair("cust_phoneno", "9989219692"));
params.add(new BasicNameValuePair("cust_confirmpass", "Sai#123"));
params.add(new BasicNameValuePair("cust_pass", "Sai#123"));
params.add(new BasicNameValuePair("cust_username", "sai#gmail.com"));
JSONObject json = jsonParser.makeHttpRequest(URL, "POST", params);
return json;
}
protected void onPostExecute(JSONObject result) {
// dismiss the dialog once product deleted
//Toast.makeText(getApplicationContext(),result,Toast.LENGTH_LONG).show();
try {
if (result != null) {
Toast.makeText(getApplicationContext(),result.getString("message"),Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Unable to retrieve any data from server", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
on button click i want to post data directly but getting error as
Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
If there are any nice tutorials for registering details for Async task means please let me know.
#Override
public void onClick(View v) {
switch(v.getId){
case R.id.button:
new AttemptLogin().execute();
}
}
try this one
The id of the button is correct? It corresponds with the id in XML layout?
Use in onCreate:
btnRegister.setOnClickListener(btnLoginClick);
Then, out of the onCreate declare method:
private View.OnClickListener btnLoginClick = new View.OnClickListener() {
#Override
public void onClick(View v) {
...
//write your code
}
};
Try this out.
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnRegister:
new AttemptLogin().execute();
break;
default:
break;
}
}
The official Android Developer site should be your closed friend. Make sure you read this:
https://developer.android.com/reference/android/os/AsyncTask

ProgressBar is not functioning in android activity

I am using progressbar in simple login application.But the progress bar is not showing .Sometimes when i change the position of the progressbar is shows before the calling progressbar.show();
here is My XML code
<ProgressBar
android:id="#+id/progressBar"
android:indeterminateDrawable="#drawable/progress"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="invisible"
>
</ProgressBar>
In onCreate() method:
progressBar= (ProgressBar) findViewById(R.id.progressBar);
progressBar.setVisibility(View.GONE);
In button oncliklistener
btn_login.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
uid=usrusr.getText().toString().trim();
upass=pswd.getText().toString().trim();
try {
progressBar.setVisibility(View.VISIBLE);
checkLogin(uid,upass);
progressBar.setVisibility(View.GONE);
} catch (SQLException e) {
e.printStackTrace();
}
}
});
}
I have tried many other solutions from stackoverflow but none of them worked
Thanks:/
Try the below code.
private ProgressDialog progDailog;
private Button btn_login;
private EditText uid, upass;
private String uid1, upass1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progDailog = new ProgressDialog(this);
progDailog.setTitle("Login");
progDailog.setMessage("Please wait...");
progDailog.setCancelable(false);
btn_login = findViewById(R.id.btn_login);
uid = findViewById(R.id.uid);
upass = findViewById(R.id.upass);
btn_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
uid1 = uid.getText().toString().trim();
upass1 = upass.getText().toString().trim();
progDailog.show();
checkLogin(uid1, upass1);
Runnable progressRunnable = new Runnable() {
#Override
public void run() {
progDailog.dismiss();
}
};
Handler pdCanceller = new Handler();
pdCanceller.postDelayed(progressRunnable, 3000);
}
});
}
Here 3000 is milliseconds which means 3 seconds, you can change it according to your requirement.
Your XML will be like.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText
android:id="#+id/uid"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="uid" />
<EditText
android:id="#+id/upass"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="upass" />
<Button
android:id="#+id/btn_login"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="btn_login" />
</LinearLayout>
Please try this and let me know if you require any other changes.
Have you considered that your "data processing" code is running on the UI thread, blocking any visible changes. I would suggest trying putting
runOnUiThread(new Runnable() {
#Override
public void run() {
progressBar.setVisibility(View.VISIBLE);
}
});
If your progressBar still not showing and nothing helps
Try added code to show the progressBar before calling the api and dismiss the progressBar on response of the request.
Ex.
void checkLogin(String name, String psd){
progressBar.setVisibility(View.VISIBLE);
//start the api call
}
void onApiCallresponse(){
runOnUiThread(new Runnable() {
#Override
public void run() {
progressBar.setVisibility(View.VISIBLE);
//code for what you want to do after login
}
});
}
You can show your progress for 3 second like this :
progressBar.setVisibility(View.VISIBLE);
progressBar.postDelayed(new Runnable() {
#Override
public void run() {
progressBar.setVisibility(View.GONE);
}
}, 3000) ;
checkLogin(uid,upass);
But it is better to show your progress when you start to check login and invoke api and hide it when you receive a result.

Google plus login from one activity and logout from second activity by clicking the logout button in second activity

Google plus login from one activity (this activity stored the login details in shared preference) and logout from another activity (this activity retreives the login details).Logout activity has the logout button.
My issue:I need to login from first activity (AndroidGooglePlusExample) and the login details (username,userimage,emailid) are stored in shared preference. I retreive these values in second activity(HomePage), and display it there, and from this second activity I need to logout on clicking the logout button. Please help me to solve this issue .This is my login activity
public class AndroidGooglePlusExample extends Activity implements OnClickListener, ConnectionCallbacks, OnConnectionFailedListener {
private static final int RC_SIGN_IN = 0;
// Google client to communicate with Google
private GoogleApiClient mGoogleApiClient;
private boolean mIntentInProgress;
private boolean signedInUser;
private ConnectionResult mConnectionResult;
private SignInButton signinButton;
private ImageView image;
private TextView username, emailLabel;
private LinearLayout profileFrame, signinFrame;
private SharedPreferences mPrefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
signinButton = (SignInButton) findViewById(R.id.button1);
signinButton.setOnClickListener(this);
// image = (ImageView) findViewById(R.id.image);
// username = (TextView) findViewById(R.id.username);
// emailLabel = (TextView) findViewById(R.id.email);
profileFrame = (LinearLayout) findViewById(R.id.profileFrame);
// signinFrame = (LinearLayout) findViewById(R.id.signinFrame);
mGoogleApiClient = new GoogleApiClient.Builder(this).addConnectionCallbacks(this).addOnConnectionFailedListener(this).addApi(Plus.API, Plus.PlusOptions.builder().build()).addScope(Plus.SCOPE_PLUS_LOGIN).build();
}
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
private void resolveSignInError() {
if (mConnectionResult.hasResolution()) {
try {
mIntentInProgress = true;
mConnectionResult.startResolutionForResult(this, RC_SIGN_IN);
} catch (SendIntentException e) {
mIntentInProgress = false;
mGoogleApiClient.connect();
}
}
}
#Override
public void onConnectionFailed(ConnectionResult result) {
if (!result.hasResolution()) {
GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this, 0).show();
return;
}
if (!mIntentInProgress) {
// store mConnectionResult
mConnectionResult = result;
if (signedInUser) {
resolveSignInError();
}
}
}
#Override
protected void onActivityResult(int requestCode, int responseCode, Intent intent) {
switch (requestCode) {
case RC_SIGN_IN:
if (responseCode == RESULT_OK) {
signedInUser = false;
}
mIntentInProgress = false;
if (!mGoogleApiClient.isConnecting()) {
mGoogleApiClient.connect();
}
break;
}
}
#Override
public void onConnected(Bundle arg0) {
signedInUser = false;
Toast.makeText(this, "Connected", Toast.LENGTH_LONG).show();
getProfileInformation();
}
private void updateProfile(boolean isSignedIn) {
// if (isSignedIn) {
// signinFrame.setVisibility(View.GONE);
// profileFrame.setVisibility(View.VISIBLE);
//
// } else {
// signinFrame.setVisibility(View.VISIBLE);
// profileFrame.setVisibility(View.GONE);
// }
if (isSignedIn) {
Intent intent = new Intent(AndroidGooglePlusExample.this, HomePage.class);
startActivity(intent);
}
}
private void getProfileInformation() {
try {
if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) {
Person currentPerson = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient);
String personName = currentPerson.getDisplayName();
String personPhotoUrl = currentPerson.getImage().getUrl();
String email = Plus.AccountApi.getAccountName(mGoogleApiClient);
username.setText(personName);
emailLabel.setText(email);
new LoadProfileImage(image).execute(personPhotoUrl);
// update profile frame with new info about Google Account
// profile
updateProfile(true);
//storing details in shared preference
if(mPrefs == null){
mPrefs = this.getSharedPreferences("MyGamePreferences", android.content.Context.MODE_PRIVATE);
}
SharedPreferences.Editor editor = mPrefs.edit();
//editor.putInt("login",401);
editor.putString("Guser_name", personName);
editor.putString("Guserpic_url", personPhotoUrl);
editor.putString("Guser_email", email);
editor.commit();
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onConnectionSuspended(int cause) {
mGoogleApiClient.connect();
updateProfile(false);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
googlePlusLogin();
break;
}
}
public void signIn(View v) {
googlePlusLogin();
}
// public void logout(View v) {
// googlePlusLogout();
// }
private void googlePlusLogin() {
if (!mGoogleApiClient.isConnecting()) {
signedInUser = true;
resolveSignInError();
}
}
// private void googlePlusLogout() {
// if (mGoogleApiClient.isConnected()) {
// Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
// mGoogleApiClient.disconnect();
// mGoogleApiClient.connect();
// updateProfile(false);
// }
// }
// download Google Account profile image, to complete profile
private class LoadProfileImage extends AsyncTask<String, Void, Bitmap> {
ImageView downloadedImage;
public LoadProfileImage(ImageView image) {
this.downloadedImage = image;
}
protected Bitmap doInBackground(String... urls) {
String url = urls[0];
Bitmap icon = null;
try {
InputStream in = new java.net.URL(url).openStream();
icon = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return icon;
}
protected void onPostExecute(Bitmap result) {
downloadedImage.setImageBitmap(result);
}
}
}
This is my second activity
public class HomePage extends Fragment {
SharedPreferences mPrefs;
Button logout_btn;
// Google client to communicate with Google
private GoogleApiClient mGoogleApiClient;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.activity_home_page, container, false);
// TextView name =(TextView)rootView.findViewById(R.id.username);
// TextView emailid =(TextView)rootView.findViewById(R.id.email);
// ImageView myimage=(ImageView)rootView.findViewById(R.id.image);
logout_btn=(Button)rootView.findViewById(R.id.logout);
logout_btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Editor editor = mPrefs.edit();
String name = mPrefs.getString("Guser_name", "");
Log.d("", name);
String pic = mPrefs.getString("Guserpic_url", "");
String email = mPrefs.getString("Guser_email", "");
}
public void logout(View v) {
googlePlusLogout();
}
private void googlePlusLogout() {
if (mGoogleApiClient.isConnected()) {
Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
mGoogleApiClient.disconnect();
mGoogleApiClient.connect();
// updateProfile(false);
}
}
});
return rootView;
}
}
this is my login xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
android:padding="15dp"
tools:context=".AndroidGooglePlusExample" >
<LinearLayout
android:id="#+id/signinFrame"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="20dp"
android:gravity="center"
android:orientation="vertical"
android:visibility="visible" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="10dp"
android:text="#string/loginText"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#ffffff" />
<com.google.android.gms.common.SignInButton
android:id="#+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="20dp"
android:textSize="18dp" />
logout xml
<LinearLayout
android:id="#+id/profileFrame"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="20dp"
android:gravity="center"
android:orientation="vertical"
>
<ImageView
android:id="#+id/image"
android:layout_width="80dp"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:textSize="20dp" />
<TextView
android:id="#+id/email"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:textSize="16dp" />
<Button
android:id="#+id/logout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="logout"
android:padding="10dp"
android:text="#string/logout"
android:textSize="18dp" />
</LinearLayout>
As per the initial chat discussion, you have a working code example for implementation of Android Login with Google Plus Account but you need to modify it with as per your requirement. I can give an idea only but unable to give an example for it !!
So here is my suggestions to meet your task completion.
As you mentioned in the post your able to login with Google+ account successfully. After successful login you need to store the credentials of the user (user name & password) in Shared Preferences along with a Boolean value (true/false) as a login status (logged-in /logged-out)
Then when your navigating to the second screen you can place a button in that and set an action to it for logout. after clicking the button you need to check the Boolean value in the shared preferences and if it is login you can logout the Google+ and update your preferences with new values ( username - null, password -null , Boolean status -false)
This links may help you to Role on
Start integrating Google+ into your Android
Google Plus Account in Android Example

Horizontal progress bar does not update its status

I am trying to show horizontal progress bar "Not ProgressDialog" on my activity like this
here is what my xml file contains
<ProgressBar
android:id="#+id/pdialog"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:indeterminate="true"
/>
I am trying to update its status using AsyncTask Class by setting pdialog.setProgress() but its not showing any progress, it works with progressdialog but not with horizontal progress bar.
public class MainActivity extends Activity {
private SQLiteDatabase db;
private Cursor cursor;
private ProgressBar pdialog;
private ImageButton btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.start);
btn = (ImageButton) findViewById(R.id.startbtn);
pbar = (ProgressBar) findViewById(R.id.progressBar1);
pdialog = (ProgressBar) findViewById(R.id.pdialog);
pdialog.setMax(100);
pdialog.setProgress(20);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pdialog.setVisibility(View.VISIBLE);
new DownloadFilesTask().execute();
}
});
}
private class DownloadFilesTask extends AsyncTask<Void, Integer, Integer> {
int load = 1;
protected Integer doInBackground(Void... params) {
try {
load = 10 * i;
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
pdialog.setProgress(load);
}
});
}
} catch (Exception e) {
}
}
protected void onProgressUpdate(Integer... progress) {
if (progress[0] == 100) {
pdialog.setVisibility(View.INVISIBLE);
}
}
protected void onPostExecute(Integer params) {
}
}
}
If load variable gets changed correctly:
Instead of this:
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
pdialog.setProgress(load);
}
});
You could use:
publishProgress(load);
which would automatically call on UI Thread:
protected void onProgressUpdate(Integer... progress) {
int p = progress[0];
if (p >= 100) {
pdialog.setVisibility(View.INVISIBLE);
}else{
pdialog.setProgress(p);
}
}
UPDATE:
remove android:indeterminate="true" as pointed out in other answer.
In your layout file please remove the following attribute android:indeterminate="true" from ProgressBar element.
I had the same question, but
I found the problem is the interface View.OnClickListener().
When the pbar was put out of the btn.setOnClickListener(new View.OnClickListener() {}), it worked well. Otherwise, it did not update.
Then, I made a constructor which passed the pbar into the OnXXXClickListener.
private class OnXXXClickListener implements View.OnClickListener() {
private ProgressBar bar;
public OnXXXClickListener(ProgressBar bar) {
this.bar = bar;
}
#Override
public void onClick(View v) {
bar.setProgess(50);
new DownloadFilesTask().execute();
}
}
Then the pbar could work well.

Categories

Resources