Save Session Android - java

I want to do make my app save session to not login again when i kill the process : when i login in the Main.java he weel redirect me to Menu.java then after i kill the precess an runit again he should take me directly to Menu.java without login with saving the username
exactly like this tutu http://www.tutorialspoint.com/android/android_session_management.htm
this is Main.java "Login Page"
public class Main extends Activity {
Button b;
EditText et,pass;
TextView tv;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
ProgressDialog dialog = null;
public static final String data = "ett";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button exit = (Button)findViewById(R.id.button18);
exit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
Intent exit = new Intent(Intent.ACTION_MAIN);
exit.addCategory(Intent.CATEGORY_HOME);
exit.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(exit);
}
});
b = (Button)findViewById(R.id.Button01);
et = (EditText)findViewById(R.id.username);
pass= (EditText)findViewById(R.id.password);
tv = (TextView)findViewById(R.id.tv);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog = ProgressDialog.show(Main.this, "",
"Verification ...", true);
new Thread(new Runnable() {
public void run() {
login();
}
}).start();
}
});
}
void login(){
try{
httpclient=new DefaultHttpClient();
httppost= new HttpPost("http://192.168.1.4/android/etc.php"); // make sure the url is correct.
//add your data
nameValuePairs = new ArrayList<NameValuePair>(2);
// Always use the same variable name for posting i.e the android side variable name and php side variable name should be similar,
nameValuePairs.add(new BasicNameValuePair("username",et.getText().toString().trim())); // $Edittext_value = $_POST['Edittext_value'];
nameValuePairs.add(new BasicNameValuePair("password",pass.getText().toString().trim()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//Execute HTTP Post Request
response=httpclient.execute(httppost);
// edited by James from coderzheaven.. from here....
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpclient.execute(httppost, responseHandler);
System.out.println("Response : " + response);
runOnUiThread(new Runnable() {
public void run() {
tv.setText("Response from PHP : " + response);
dialog.dismiss();
}
});
if(response.equalsIgnoreCase("User Found")){
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(Main.this,"Login Success", Toast.LENGTH_SHORT).show();
}
});
SharedPreferences setting = getSharedPreferences(data, 0);
SharedPreferences.Editor editor = setting.edit();
editor.putString("et", et.getText().toString());
editor.commit();
Intent intent=new Intent(Main.this, Menu.class);
startActivity(intent);
}else{
showAlert();
}
}catch(Exception e){
dialog.dismiss();
System.out.println("Exception : " + e.getMessage());
}
}
public void showAlert(){
Main.this.runOnUiThread(new Runnable() {
public void run() {
AlertDialog.Builder builder = new AlertDialog.Builder(Main.this);
builder.setTitle("Erreur d'identification");
builder.setMessage("Code ou mot de passe incorrecte")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
}
}
Menu.java this wher should the app start after saving session
public class Menu extends ActionBarActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menus);
Button button1 = (Button)findViewById(R.id.button1);
Button button3 = (Button)findViewById(R.id.button3);
Button button4 = (Button)findViewById(R.id.button4);
Button button14 = (Button)findViewById(R.id.button14);
Button button5 = (Button)findViewById(R.id.button5);
Button exit = (Button)findViewById(R.id.button18);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent1 = new Intent(Menu.this, emploi.class);
startActivity(intent1);
}
});
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent2 = new Intent(Menu.this, Maritimnews.class);
startActivity(intent2);
}
});
button4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent3 = new Intent(Menu.this, Resultats.class);
startActivity(intent3);
}
});
button14.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent4 = new Intent(Menu.this, Demande.class);
startActivity(intent4);
}
});
button5.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent5 = new Intent(Menu.this, Apropos.class);
startActivity(intent5);
}
});
exit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
Intent exit = new Intent(Intent.ACTION_MAIN);
exit.addCategory(Intent.CATEGORY_HOME);
exit.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(exit);
}
});
}
}
i don't know where i put the sharedpreferces exactly to make it save the session
the sharedpreferences there just for passing data between Main.java and Menu.java
i wan't to add another sheredPreferences to save session like facebook means when i login in Main.java ---redirecte--> Menu.java so if i close an run the app again he will start with Menu.java :) and Thank you

if you implement that way the user will login only once in your application and will be forever connected. the best is to do it this way:
first add a checkbox to login to let the user decide if he wants to save his login.
add sharepreferences if checked and delete sharepreferences if uncheck.
read sharedpreferences in the onresume() method of main activity and add some logic to intent directly to menu activity if preferences is not null

I used mySharedPreferences that indicate to me if user already logged in, and I pass a int value from previous activity to know if the user just enter the app or not.
public class ConnectWithFaceBookActivity extends Activity{
int mode = Activity.MODE_PRIVATE;
private SharedPreferences mySharedPreferences;
private String TAG = "ConnectWithFaceBookActivity";
private TextView lblEmail;
private String accessToken;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.connect_with_facebook);
mySharedPreferences = this.getSharedPreferences( "facebook", Context.MODE_PRIVATE);
final SharedPreferences.Editor editor= mySharedPreferences.edit();
lblEmail = (TextView) findViewById(R.id.lblEmail);
LoginButton authButton = (LoginButton) findViewById(R.id.authButton);
Intent i = getIntent();
int logout = i.getIntExtra("LOGOUT", 0);
//checking if already sign in
if(logout!=1 && mySharedPreferences.getString("email","")!="")//1 represent logout button preesed
{
String mString;
mString= mySharedPreferences.getString("email","");
lblEmail.setText(mString);
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
startActivity(intent);
finish();
}
authButton.setOnErrorListener(new OnErrorListener() {
#Override
public void onError(FacebookException error) {
Log.i(TAG, "Error " + error.getMessage());
}
});
// set permission list, Don't foeget to add email
authButton.setReadPermissions(Arrays.asList("public_profile","user_friends","email"));
// session state call back event
authButton.setSessionStatusCallback(new Session.StatusCallback()
{
#Override
public void call(Session session, SessionState state, Exception exception)
{
Boolean open = session.isOpened();
if (open)
{
Log.i(TAG,"Access Token"+ session.getAccessToken());
accessToken = session.getAccessToken();
Request.newMeRequest (session, new Request.GraphUserCallback()
{
#Override
public void onCompleted(GraphUser user,Response response)
{
if (user != null)
{
Log.i(TAG,"User ID "+ user.getId());
Log.i(TAG,"Email "+ user.asMap().get("email"));
String str = user.asMap().get("email").toString();
lblEmail.setText(str);
editor.putBoolean("isLogIn",true);
editor.putString("email",str);
//save the changes that you made
editor.commit();
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
startActivity(intent);
finish();
}
}
}).executeAsync();
}
else
{
editor.putBoolean("isLogIn",false);
editor.putString("email","");
//save the changes that you made
editor.commit();
}
}
});
}
public static void callFacebookLogout(Context context) {
Session session = Session.getActiveSession();
if (session != null) {
if (!session.isClosed()) {
session.closeAndClearTokenInformation();
//clear your preferences if saved
}
} else {
session = new Session(context);
Session.setActiveSession(session);
session.closeAndClearTokenInformation();
//clear your preferences if saved
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
}
}

Related

Open specific tab from main menu while app is running in foreground using pending intent or other solution

In my app, there is a login activity first and a home activity. After logging in using volley and passing parameters to home activity in an intent, I'm able to start a foreground service that keeps the app running in background with notifications and getting back to home activity by clicking on the notification with the help of pending intent.
Now, I'm searching for how to open the app from main menu and accessing directly home activity with the pending intent of the foreground service. Maybe should I pass the parameters of the pending intent to the login activity and check them to redirect to home activity, but i'am stuck with this and don't understand.
Here is the login activity Page :
EditText username, password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Button login = (Button) findViewById(R.id.signIn);
// Login On Button Click
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
login();}
});
// THIS IS THE SOLUTION THAT I THOUGHT ABOUT : if the intent is not null open HomeActivity
Intent startinIntent = getIntent();
if (startinIntent.getStringExtra("userLogged") != null && !startinIntent.getStringExtra("userLogged").isEmpty()) {
String userLogged = startinIntent.getStringExtra("userLogged");
Intent startAgain = new Intent(this, HomeActivity.class);
tackBackWork.putExtra("userLogged", userLogged);
startActivity(startAgain);
Log.d("this is the ilue", userLogged);
}
}
private void login(){
username = (EditText)findViewById(R.id.username);
password = (EditText)findViewById(R.id.password);
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
JSONObject object = new JSONObject();
try {
//input your API parameters
object.put("u",username.getText());
object.put("p",password.getText());
} catch (JSONException e) {
e.printStackTrace();
}
// Enter the correct url for your api service site
String url = getResources().getString(R.string.loginUrl);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, object,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try{
String msg = response.getString("msg");
if(msg.contains("true")){
Intent loggedIn = new Intent(LoginActivity.this, HomeActivity.class);
loggedIn.putExtra("userLogged", response.toString());
startActivity(loggedIn);
finish();
}else{
Toast.makeText(getApplicationContext(), "Identifiants Incorrectes", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e){
Toast.makeText(getApplicationContext(), "erreur - 200 ", Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "Volley on error listener", Toast.LENGTH_SHORT).show();
}
});
requestQueue.add(jsonObjectRequest);
}
}
Here is the Home activity
public class HomeActivity extends AppCompatActivity implements View.OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
String userLogged = getIntent().getStringExtra("userLogged");
}
#Override
protected void onStart() {
super.onStart();
Intent serviceIntent = new Intent(this, ForegroundServiceNoPopup.class);
stopService(serviceIntent);
}
#Override
public void onResume(){
super.onResume();
Intent serviceIntent = new Intent(this, ForegroundServiceNoPopup.class);
stopService(serviceIntent);
}
#Override
protected void onStop() {
super.onStop();
Intent serviceIntent = new Intent(this, ForegroundService.class);
Intent intent = getIntent();
String userLogged = intent.getStringExtra("userLogged");
serviceIntent.putExtra("userLogged", userLogged);
startService(serviceIntent);
}
#Override
protected void onDestroy() {
super.onDestroy();
Intent serviceIntent = new Intent(this, ForegroundService.class);
Intent intent = getIntent();
String userLogged = intent.getStringExtra("userLogged");
serviceIntent.putExtra("userLogged", userLogged);
startService(serviceIntent);
}
#Override
protected void onPause() {
super.onPause();
Intent serviceIntent = new Intent(this, ForegroundService.class);
Intent intent = getIntent();
String userLogged = intent.getStringExtra("userLogged");
serviceIntent.putExtra("userLogged", userLogged);
startService(serviceIntent);
}
}
Here is foreground Service Page :
public class ForegroundService extends Service {
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
String input = intent.getStringExtra("inputExtra");
String userLogged = intent.getStringExtra("userLogged");
Intent backToHomeActivity = new Intent(this, HomeActivity.class);
backToHomeActivity.putExtra("userLogged", userLogged);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, backToHomeActivity, PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Example Service")
// .setLargeIcon()
// .setColor()
.setContentIntent(pendingIntent)
.setContentText(input)
.setSmallIcon(R.drawable.icon)
.setContentIntent(pendingIntent)
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setPriority(NotificationCompat.PRIORITY_MAX)
.build();
startForeground(1, notification);
return START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
I'm new to all of this. please help me.
The solution is to use SharedPreferences.
public class LoginActivity extends AppCompatActivity {
Button login;
SharedPreferences sp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
login = (Button) findViewById(R.id.loginBtn);
sp = getSharedPreferences("login",MODE_PRIVATE);
if(sp.getBoolean("logged",false)){
goToMainActivity();
}
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
goToMainActivity();
sp.edit().putBoolean("logged",true).apply();
}
});
}
public void goToMainActivity(){
Intent i = new Intent(this,MainActivity.class);
startActivity(i);
}
}
See the Tutorial below
https://medium.com/#prakharsrivastava_219/keep-the-user-logged-in-android-app-5fb6ce29ed65

application started crashing when trying to login using facebook after ide error

My application was working perfectly then, after adding the following code LoginManager.getInstance().logOut(); to disconnect from the current facebook account (a developper acount), the ide showed that an error occurred while running the app, but the application launched anyway, but when trying to login, it crashed and now it's not logging in, it keeps crashing! even though I changed nothing except adding that line of code to the next activity to make the app disconnect in case the user want to logout!
here's my java code:
public class ConnexionActivity extends AppCompatActivity {
Button b_bb, b_back, ee, b_inscrp_formulaire, fb;
EditText tb_pseudo, tb_mdp;
int id;
String name, gender, email, birthday;
private LoginButton loginButton;
private CallbackManager callbackManager;
Profile profile;
//new try:
private AccessTokenTracker accessTokenTracker;
private Button customFacebookLogin;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
/*List<String> permissionNeeds = Arrays.asList("user_photos", "email",
"user_birthday", "public_profile", "AccessToken");*/
setContentView(R.layout.activity_connexion);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitle("");
setSupportActionBar(toolbar);
b_inscrp_formulaire = (Button) findViewById(R.id.b_inscrip_formulaire);
fb = (Button) findViewById(R.id.fb);
loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setText("");
loginButton.setReadPermissions(Arrays.asList("public_profile", "email", "user_friends", "user_birthday"));
//"user_photos", "email","user_birthday", "public_profile"
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
graphRequest(loginResult.getAccessToken());
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException error) {
}
});
//getting the hash key
try {
PackageInfo info = getPackageManager().getPackageInfo(
"your.package",
PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
}
} catch (PackageManager.NameNotFoundException e) {
} catch (NoSuchAlgorithmException e) {
}
//2nd way to generate hash key (or get it)
try {
PackageInfo info = getPackageManager().getPackageInfo("your.package.name", PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
}
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
b_bb = (Button) findViewById(R.id.b_bb);
b_back = (Button) findViewById(R.id.b_back);
tb_pseudo = (EditText) findViewById(R.id.textbox_pseudo);
tb_mdp = (EditText) findViewById(R.id.textbox_mdp);
/////////////
ee = (Button) findViewById(R.id.button);
////////////
b_bb.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: {
b_bb.setBackgroundResource(R.drawable.button_bb_selec);
break;
}
case MotionEvent.ACTION_UP: {
b_bb.setBackgroundResource(R.drawable.button_bb);
break;
}
}
return false;
}
});
b_bb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isAuthorized()) {
Intent menu_p = new Intent(ConnexionActivity.this, MenuPActivity.class);
menu_p.putExtra("pseudo", tb_pseudo.getText().toString());
startActivity(menu_p);
} else {
openDialog();
}
}
});
b_back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ConnexionActivity.this.finish();
}
});
ee.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent menu_p = new Intent(ConnexionActivity.this, MenuPActivity.class);
menu_p.putExtra("pseudo", "Easter");
startActivity(menu_p);
}
});
b_inscrp_formulaire.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent menu_p = new Intent(ConnexionActivity.this, InscriptionActivity.class);
startActivity(menu_p);
}
});
LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
graphRequest(loginResult.getAccessToken());
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException error) {
}
});
fb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
LoginManager.getInstance().logInWithReadPermissions(ConnexionActivity.this, Arrays.asList("user_photos", "email",
"user_birthday", "public_profile"));
profile = Profile.getCurrentProfile().getCurrentProfile();
if (profile != null) {
// user has logged in
Intent menu_p = new Intent(ConnexionActivity.this, MenuPActivity.class);
menu_p.putExtra("pseudo", profile.getFirstName());
startActivity(menu_p);
Toast.makeText(getApplicationContext(), "Connecté : " + profile.getFirstName() + " " + profile.getLastName(), Toast.LENGTH_SHORT).show();
} else {
// user has not logged in
Toast.makeText(getApplicationContext(), "Non-Connecté : Erreur de connexion!!", Toast.LENGTH_SHORT).show();
}
}
});
//To log out of FB:
/*LoginManager.getInstance().logOut();*/
//TODO: check if the user is logged in or not
/* profile = Profile.getCurrentProfile().getCurrentProfile();
if (profile != null) {
// user has logged in
} else {
// user has not logged in
}*/
}
private Boolean isAuthorized() {
if (tb_pseudo.getText().toString().equals("Admin")
&& tb_mdp.getText().toString().equals("0000")
) {
return true;
} else
return false;
}
public void openDialog() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage("Mauvaise combinaison \"Pseudo\", \"Mot de passe\"");
alertDialogBuilder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
public void graphRequest(AccessToken token) {
GraphRequest request = GraphRequest.newMeRequest(token, new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
Toast.makeText(getApplicationContext(), object.toString(), Toast.LENGTH_LONG).show();
}
});
Bundle b = new Bundle();
b.putString("fields", "id,email,first_name,last_name,picture.type(large)");
request.setParameters(b);
request.executeAsync();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
}
I guess the problem was just in the IDE, something about indexation!! I closed and reopened the IDE and everything is working just fine.

How to reduce this below java code?

Here I've written some code to navigate to different links using different buttons in android. Is there anyway to reduce my code further than I've coded. If it is possible please do help me to reduce the code. here is my code:
Button tv = (Button) findViewById(R.id.my1);
tv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
v.startAnimation(myscale);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
try {
Intent intent = new Intent(
Intent.ACTION_VIEW,
Uri.parse("link1"));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
} catch (Exception e) {
Log.e("Exception Caught", e.toString());
}
}
}, 50);
}
});
Button tv1 = (Button) findViewById(R.id.my2);
tv1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
v.startAnimation(myscale);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
try {
Intent intent = new Intent(
Intent.ACTION_VIEW,
Uri.parse("link2"));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
} catch (Exception e) {
Log.e("Exception Caught", e.toString());
}
}
}, 50);
}
});
Button tv2 = (Button) findViewById(R.id.my3);
tv2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
v.startAnimation(myscale);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
try {
Intent intent = new Intent(
Intent.ACTION_VIEW,
Uri.parse("link3"));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
} catch (Exception e) {
Log.e("Exception Caught", e.toString());
}
}
}, 50);
}
});
Once try as follows take a method for re usability
public void openLink(final String link){
v.startAnimation(myscale);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
try {
Intent intent = new Intent(
Intent.ACTION_VIEW,
Uri.parse(link));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
} catch (Exception e) {
Log.e("Exception Caught", e.toString());
}
}
}, 50);
}
and implements onClickListener and in onClick
#Override
public void onClick(View v) {
super.onClick(v);
switch (v.getId()) {
case R.id.my1:
openLink(link1);
break;
case R.id.my2:
openLink(link2);
break;
case R.id.my3:
openLink(link3);
break;
}
Hope this will helps you.
Button tv = (Button) findViewById(R.id.my1);
tv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
startAnotherActivity("link1");
}
});
Button tv1 = (Button) findViewById(R.id.my2);
tv1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
startAnotherActivity("link2");
}
});
Button tv2 = (Button) findViewById(R.id.my3);
tv2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
startAnotherActivity("link3");
}
});
private void startAnotherActivity(final String link){
v.startAnimation(myscale);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
try {
Intent intent = new Intent(
Intent.ACTION_VIEW,
Uri.parse(link));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
} catch (Exception e) {
Log.e("Exception Caught", e.toString());
}
}
}, 50);
}
Create one method for click listener and use if condition.
Here is sample code.
Your OnCreate Code:
Button tv = (Button) findViewById(R.id.my1);
onClick(tv);
tv1 = (Button) findViewById(R.id.my2);
onClick(tv1);
Button tv2 = (Button) findViewById(R.id.my3);
onClick(tv2);
Common Method : Declare mLink Variable as Global
public void onClick(View v)
{
v.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(v == tv)
mLink = "link1";
else if(v == tv1)
mLink = "link2";
else if(v == tv2)
mLink = "link3";
v.startAnimation(myscale);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
try {
Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse(mLink));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
} catch (Exception e) {
Log.e("Exception Caught", e.toString());
}
}
}, 50);
}
});
}
implement onClickListener on your activity and override the onClick() method and write your code in this manner
#Override
public void onClick(View v) {
super.onClick(v);
switch (v.getId()) {
case R.id.my1:
//your code here
break;
case R.id.my2:
//your code here
break;
}
OK, I'll post an example, but only because there's a little non-trivial concept that needs explaining:
Button tv = (Button) findViewById(R.id.my1);
setListenerForButton(tv, "link1");
Button tv1 = (Button) findViewById(R.id.my2);
setListenerForButton(tv1, "link2");
Button tv2 = (Button) findViewById(R.id.my3);
setListenerForButton(tv1, "link3");
private void setListenerForButton(Button button, final String link) {
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
v.startAnimation(myscale);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
try {
Intent intent = new Intent(
Intent.ACTION_VIEW,
Uri.parse(link));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
} catch (Exception e) {
Log.e("Exception Caught", e.toString());
}
}
}, 50);
}
});
}
The detail is that for link to be used in the anonymous inner class that you're setting up for the listener, link has to be final.
I've looked this over and believe it will work, but I haven't tried it.

Authenticate user when wants to buy book in Android application

I had make a bookstore in android with eclipse . I have a main page If user click on login icon , go to login and put username and password then press login button,
If user found show massage that”user found”and if user doesn't found show alert message ”not found”
I want if user login and see message "user found"
When user want to buy book can buy
And when don’t login can’t buy book
It means when goto user page(the user page is for buy book)
When user login , this page show
And when doesn't login this page goto the login activity
,
I use flag but I don’t know how to use it ? if flag=0 the user dosn't login and if flag=1 user login .but how transfer this to user page?
Can help me please ?
And is there any site for this?
loginactivity.java
public class LoginActivity extends Myactionbar {
EditText userNmae,pass;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
ProgressDialog dialog = null;
Button btnLinkToRegister;
Button btnLogin;
int flag=0;
public void gotosearch() {
Intent intent = new Intent(this, Search.class);
startActivity(intent);}
public void gotologin() {
Intent m = new Intent(this, LoginActivity.class);
startActivity(m);}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
userNmae=(EditText)findViewById(R.id.usernameedittext);
pass=(EditText)findViewById(R.id.passwordedittext);
Typeface font1 = Typeface.createFromAsset(getAssets(),
"font/bnazanin.TTF");
//emailtext
TextView userName = (TextView) findViewById(R.id.usernametv);
///tv.setText(booksote.utils.DariGlyphUtils.reshapeText("email"));
userName.setTypeface(font1);
userName.setTextSize(26);
//passwordtext
TextView password1 = (TextView) findViewById(R.id.passwordtv);
//tv.setText(booksote.utils.DariGlyphUtils.reshapeText("password"));
password1.setTypeface(font1);
password1.setTextSize(26);
//login
btnLogin= (Button) findViewById(R.id.btnLogin);
btnLogin.setTypeface(font1);
btnLogin.setTextSize(26);
**btnLogin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog = ProgressDialog.show(LoginActivity.this, "",
"Validating user...", true);
new Thread(new Runnable() {
public void run() {
login();
}
}).start();
}
});
}
void login(){
try{
httpclient=new DefaultHttpClient();
httppost= new HttpPost("http://10.0.2.2/project/login1.php");
//add your data
nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("user_name",userNmae.getText().toString().trim())); // $Edittext_value = $_POST['Edittext_value'];
nameValuePairs.add(new BasicNameValuePair("password",pass.getText().toString().trim()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//Execute HTTP Post Request
response=httpclient.execute(httppost);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpclient.execute(httppost, responseHandler);
System.out.println("Response :" + response);
runOnUiThread(new Runnable() {
public void run() {
dialog.dismiss();
}
});
if(response.equalsIgnoreCase("User Found")){
runOnUiThread(new Runnable() {
public void run() {
//Toast.makeText(LoginActivity.this,"Login Success", Toast.LENGTH_SHORT).show();
//this I use flag but I dontknow how to use ?
flag=1;
**Intent intent = new Intent(getApplicationContext(),UserPage.class);
intent.putExtra("flag", flag);**
startActivity(intent);**
}
});
}else{
flag=0;
showAlert();
}
}catch(Exception e){
dialog.dismiss();
System.out.println("Exception : " + e.getMessage());
}
}
public void showAlert(){
LoginActivity.this.runOnUiThread(new Runnable() {
public void run() {
AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
builder.setTitle("Login Error.");
builder.setMessage("not found")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
}
}
userpage.java
public class UserPage extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_page);
Intent intent = getIntent();
int myflag = intent.getIntExtra("flag");
}

Service starts when I open the activity without reason

I'm using this code:
public class ActivityMain extends Activity {
private static final String TAG = "MainActivity";
private ServiceSpeechRecognition service;
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder binder) {
ServiceSpeechRecognition.MyBinder b = (ServiceSpeechRecognition.MyBinder) binder;
service = b.getService();
Log.e(TAG, "Service connected");
}
public void onServiceDisconnected(ComponentName className) {
savePrefs();
service = null;
Log.e(TAG, "Service disconnected");
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.e(TAG, "onCreate");
setContentView(R.layout.activity_ui_main);
getPackageManager().setComponentEnabledSetting(new ComponentName(this, getPackageName() + ".MainActivity-Alias"), PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
}
#Override
protected void onResume() {
super.onResume();
Log.e(TAG, "onResume");
GoogleSearchApi.registerQueryGroup(this, ReceiverGoogleSearch.group);
// Load prefs
SharedPreferences prefs = ActivityMain.getPrefs(this);
String key_phrase = prefs.getString(Preferences.KEY_PHRASE_KEY, Preferences.DEFAULT_KEY_PHRASE);
boolean require_charge = prefs.getBoolean(Preferences.KEY_REQUIRE_CHARGER, true);
// Update Ui
EditText text = (EditText) findViewById(R.id.key_phrase);
text.setText(key_phrase);
CheckBox checkbox = (CheckBox) findViewById(R.id.require_battery);
checkbox.setChecked(require_charge);
// If should, start intent
if (!require_charge || Util.isCharging(this)) {
bindIntent();
}
}
#Override
protected void onPause() {
if (service != null) {
Log.e(TAG, "Unbind");
unbindService(mConnection);
}
super.onPause();
}
private void bindIntent() {
Log.e(TAG, "Bind intent");
Intent intent = new Intent(this, ServiceSpeechRecognition.class);
startService(intent);
bindService(intent, mConnection, 0);
}
public void setKeyPhrase(View view) {
savePrefs();
if (service != null) {
EditText text = (EditText) findViewById(R.id.key_phrase);
String key_phrase = text.getText().toString();
service.setKeyPhrase(key_phrase);
}
Toast.makeText(this, R.string.str_key_phrase_updated, Toast.LENGTH_SHORT).show();
}
public void setRequireCharge(View view) {
savePrefs();
CheckBox checkbox = (CheckBox) view;
boolean require_charge = checkbox.isChecked();
if (service != null) {
service.setRequiresCharge(require_charge);
} else if (!require_charge || Util.isCharging(this)) {
bindIntent();
}
}
public void savePrefs() {
EditText text = (EditText) findViewById(R.id.key_phrase);
String key_phrase = text.getText().toString();
CheckBox checkbox = (CheckBox) findViewById(R.id.require_battery);
boolean require_charge = checkbox.isChecked();
SharedPreferences.Editor prefs = ActivityMain.getPrefs(this).edit();
prefs.putString(Preferences.KEY_PHRASE_KEY, key_phrase);
prefs.putBoolean(Preferences.KEY_REQUIRE_CHARGER, require_charge);
prefs.commit();
}
public static SharedPreferences getPrefs(Context context) {
return context.getSharedPreferences(Preferences.KEY, Context.MODE_PRIVATE | Context.MODE_MULTI_PROCESS);
}
}
this is an activity in which starts a service.. The problem is that the service starts as soon as the activity it opens. I would create a button or checkbox to start it. But now when I open the activity it starts the service. I didn't write any startService() in the onCreate() method.
Here You Start Your Service in On Resume so Replace
private void bindIntent() {
Log.e(TAG, "Bind intent");
Intent intent = new Intent(this, ServiceSpeechRecognition.class);
startService(intent);
bindService(intent, mConnection, 0);
}
to
private void bindIntent() {
Log.e(TAG, "Bind intent");
Intent intent = new Intent(this, ServiceSpeechRecognition.class);
bindService(intent, mConnection, 0);
}
Put below code in your button click event.
Intent intent = new Intent(this, ServiceSpeechRecognition.class);
startService(intent);
Thats it....

Categories