Authenticate user when wants to buy book in Android application - java

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

Related

how to display image without onclick button

help guys how to display image without using a button, I tried to put it on create but not working and I tried to make it as a function but still not working,but when in button (on click) it show image. I want to show the image without clicking the button.
I want to load the image without clicking the button, so when the user come the image automatically load without push of a button.
public class MainActivity extends AppCompatActivity {
TextView textViewdatashow;
EditText editTextvalue;
ImageView imageView;
Button buttonfetch;
String url ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textViewdatashow = (TextView) findViewById(R.id.tvshowdata);
editTextvalue = (EditText) findViewById(R.id.etvalue);
imageView = (ImageView) findViewById(R.id.image);
buttonfetch = (Button) findViewById(R.id.buttonfetchdata);
buttonfetch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String id = editTextvalue.getText().toString();
url = "https://PASTE_YOUR_IMAGE_URL"+id+".jpg";
getData();
}
});
}
private void getData() {
String id = editTextvalue.getText().toString().trim();
if (id.equals("")) {
Toast.makeText(this, "Check Detail!", Toast.LENGTH_LONG).show();
return;
}
String url = Config.DATA_URL + editTextvalue.getText().toString().trim();
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
showJSONS(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.getMessage().toString(), Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showJSONS(String response) {
String name = "";
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(Config.JSON_ARRAY);
JSONObject collegeData = result.getJSONObject(0);
name = collegeData.getString(Config.KEY_NAME);
} catch (JSONException e) {
e.printStackTrace();
}
textViewdatashow.setText("" + name);
ImageRetriveWithPicasso();
}
private void ImageRetriveWithPicasso() {
Picasso.get()
.load(url)
.placeholder(R.drawable.imageholder)
.into(imageView);
}
}
Put this code inside on create view
final Handler myHandler = new
Handler(Looper.getMainLooper());
new Thread(new Runnable() {
#Override
public void run() {
myHandler.post(new Runnable() {
#Override
public void run() {
getData()
}
});
}
})).start();
}

Login in android app using php and mysql database

I'm trying to login with four different users using php and mysql database in android, and after if any user login with email and password i'm trying to fetch their information like (Name, Address, ID, etc.) from mysql database.
And i want that whenever if any of user from those four users login they can able to see their own information from database like(Name, Address, ID, etc.)
I have already tried to separate those users with the user type and with if-else condition that is in code that i provided.
public class LoginActivity extends AppCompatActivity {
private static final String TAG="LoginActivity";
private TextView createaccount;
private EditText Ausername,Apassword;
private Button LoginButton;
private Context mContext;
//URLS class
//ALL URLs
URLs urLs;
RelativeLayout relativeLayout1,relativeLayout2;
Handler handler=new Handler();
Runnable runnable=new Runnable() {
#Override
public void run() {
relativeLayout1.setVisibility(View.VISIBLE);
relativeLayout2.setVisibility(View.VISIBLE);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
urLs = new URLs();
if (SharedPrefManager.getInstance(getApplicationContext()).isLoggedIn()){
finish();
Intent intentD = new Intent(LoginActivity.this, DashboardActivity.class);
startActivity(intentD);
}
relativeLayout1 = findViewById(R.id.rel3);
relativeLayout2 = findViewById(R.id.rel2);
Ausername = findViewById(R.id.etuname);
Apassword = findViewById(R.id.etpass);
LoginButton = findViewById(R.id.loginbutton);
handler.postDelayed(runnable, 2000);
createaccount = findViewById(R.id.tvregistration);
createaccount.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(LoginActivity.this, Rigistration_Option.class);
startActivity(intent);
}
});
LoginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
userLogin();
}
});
}
private void userLogin(){
//first getting the values
final String email = Ausername.getText().toString();
final String password = Apassword.getText().toString();
//validating inputs
if (TextUtils.isEmpty(email)) {
Ausername.setError("Please enter your username");
Ausername.requestFocus();
return;
}
if (TextUtils.isEmpty(password)) {
Apassword.setError("Please enter your password");
Apassword.requestFocus();
return;
}
//if everything is fine
class UserLogin extends AsyncTask<Void, Void, String> {
ProgressBar progressBar;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressBar = findViewById(R.id.progressbar);
progressBar.setVisibility(View.VISIBLE);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
progressBar.setVisibility(View.GONE);
try {
//converting response to json object
JSONObject obj = new JSONObject(s);
//if no error in response
if (!obj.getBoolean("error")) {
Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();
//getting the user from the response
JSONObject userJson = obj.getJSONObject("user");
//creating a new user object
CA_SIGNUP_GTST user = new CA_SIGNUP_GTST(
userJson.getInt("id"),
userJson.getString("name"),
userJson.getString("email"),
userJson.getString("mobile"),
userJson.getString("address")
);
//storing the user in shared preferences
SharedPrefManager.getInstance(getApplicationContext()).userLogin(user);
//starting the profile activity
finish();
Intent intentD = new Intent(LoginActivity.this, DashboardActivity.class);
startActivity(intentD);
} else {
Toast.makeText(getApplicationContext(), "Invalid username or password", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
protected String doInBackground(Void... voids) {
//creating request handler object
RequestHandler requestHandler = new RequestHandler();
HashMap<String, String> params = new HashMap<>();
URLs urLs = new URLs();
if (urLs.equals("cma_login")) {
params.put("email", email);
params.put("password", password);
return requestHandler.sendPostRequest(URLs.CMA_LOGIN, params);
}
else if (urLs.equals("ca_login")){
params.put("email", email);
params.put("password", password);
return requestHandler.sendPostRequest(URLs.CA_LOGIN, params);
}
else if (urLs.equals("cs_login")){
params.put("email", email);
params.put("password", password);
return requestHandler.sendPostRequest(URLs.CS_LOGIN, params);
}
else if (urLs.equals("adv_login")){
params.put("email", email);
params.put("password", password);
return requestHandler.sendPostRequest(URLs.ADV_LOGIN, params);
}
return null;
}
}
UserLogin ul = new UserLogin();
ul.execute();
}
}
i expect that after user login they can see their own information but when i try to login with second and the third user then they are unable to login.

intent to next activity, toast, progress bar not working

I am trying to make a login page where if user enters a correct mobile and pwd it should go in ProfileActivity.java
my code
public class LoginActivity extends AppCompatActivity {
EditText editTextUsername, editTextPassword;
ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
if (SharedPrefManager.getInstance(this).isLoggedIn()) {
finish();
startActivity(new Intent(this, ProfileActivity.class));
}
progressBar = (ProgressBar) findViewById(R.id.progressBar);
editTextUsername = (EditText) findViewById(R.id.editTextUsername);
editTextPassword = (EditText) findViewById(R.id.editTextPassword);
//if user presses on login
//calling the method login
Button login = (Button)findViewById(R.id.buttonLogin);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
userLogin();
}
});
//if user presses on not registered
findViewById(R.id.textViewRegister).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//open register screen
finish();
startActivity(new Intent(getApplicationContext(), MainActivity.class));
}
});
}
private void userLogin() {
//first getting the values
final String mobile = editTextUsername.getText().toString();
final String password = editTextPassword.getText().toString();
//validating inputs
if (TextUtils.isEmpty(mobile)) {
editTextUsername.setError("Please enter your username");
editTextUsername.requestFocus();
return;
}
if (TextUtils.isEmpty(password)) {
editTextPassword.setError("Please enter your password");
editTextPassword.requestFocus();
return;
}
//if everything is fine
StringRequest stringRequest = new StringRequest(Request.Method.POST, URLs.URL_LOGIN,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressBar.setVisibility(View.GONE);
try {
//converting response to json object
JSONObject obj = new JSONObject(response);
//if no error in response
if (!obj.getBoolean("error")) {
Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_SHORT).show();
//getting the user from the response
JSONObject userJson = obj.getJSONObject("user");
//creating a new user object
User user = new User(
userJson.getInt("id"),
userJson.getString("mobile"),
userJson.getString("password")
);
//storing the user in shared preferences
SharedPrefManager.getInstance(getApplicationContext()).userLogin(user);
//starting the profile activity
Intent intent = new Intent(LoginActivity.this, ProfileActivity.class);
startActivity(intent);
finish();
} else {
Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.e("TAG", response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("mobile", mobile);
params.put("password", password);
return params;
}
};
VolleySingleton.getInstance(this).addToRequestQueue(stringRequest);
}
}
In this code neither a toast, progressbar, nor the intent to redirect to next activity is working. I have also extended ProfileActivity with Activity. I have registerd profileactivity.java in manifest file.
What am i doing wrong here? thank you for your suggestions
finish() method should be put a end, because it will ignore all next lines.
Intent intent = new Intent(LoginActivity.this, ProfileActivity.class);
startActivity(intent);
finish();
You are using "id" field as an integer and it's an String ,Secondly from where you are getting
User user = new User(
userJson.getString("id"),
"", // please add mobile and password in JSON
""
);
I solved it. In the line ,
JSONObject userJson = obj.getJSONObject("user");
I named the object as user. But in PHP I named it as result As soon as I changed it, it started working.
Although, Thanks for your support community :).

Fetch data from db when logged in with Google

all of you great developers, which I'm not, since I'm posting this question ;-)
I have a site with a to-do list where you can log in to Google. Now I want to make an Android app to access my DB on my site. I have the login with Google part correct and from that login activity, I switch to the activity (via intent, that's how I know I'm logged in correctly, cause the intent is only started when logged in) to display my to-do list. This is where I'm stuck. I can't seem to fetch the data from the DB, even though I'm logged in. I searched a bit online (watched a few hours of youtube video on the topic, and also searched StackOverflow, the internet in general and the Google developer pages), but no result. I'm guessing I have to pass on the token from the login activity to the other, but other than that, I just don't know and I'm hoping someone of you can point me in the right direction. Extra info: site is written in PHP with PDO for DB functions and MySQL DB. I also managed to get the JSON output on the site. In the android app, I also use Volley and it's written in Java (not Kotlin). I would really appreciate the help and if you need more info (or maybe a part of the code), be sure to ask.
Regards
Christophe
Edit: hereby the requested code:
LoginActivity:
package package_name;
some imports...
public class LoginActivity extends AppCompatActivity {
private static final String TAG = "Scorpio To Do Login: ";
GoogleSignInOptions gso;
GoogleSignInClient mGoogleSignInClient;
SignInButton signInButton;
private int RC_SIGN_IN = 6;
private static final String URL_DATA = "https://some.url.be";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
// Configure sign-in to request the user's ID, email address, and basic
// profile. ID and basic profile are included in DEFAULT_SIGN_IN.
gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.server_client_id))
.requestEmail()
.build();
// Build a GoogleSignInClient with the options specified by gso.
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
}
#Override
protected void onStart() {
super.onStart();
// Check for existing Google Sign In account, if the user is already signed in
// the GoogleSignInAccount will be non-null.
GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this);
updateUI(account);
}
private void updateUI(GoogleSignInAccount account) {
Log.w(TAG, "account = " + account);
if(account == null){
// Set the dimensions of the sign-in button.
signInButton = findViewById(R.id.sign_in_button);
signInButton.setSize(SignInButton.SIZE_WIDE);
signInButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
signIn();
}
});
signInButton.setVisibility(View.VISIBLE);
} else {
Context context = LoginActivity.this;
/* This is the class that we want to start (and open) when the button is clicked. */
Class destinationActivity = TaskActivity.class;
/*
* Here, we create the Intent that will start the Activity we specified above in
* the destinationActivity variable. The constructor for an Intent also requires a
* context, which we stored in the variable named "context".
*/
Intent startChildActivityIntent = new Intent(context, destinationActivity);
/*
* Once the Intent has been created, we can use Activity's method, "startActivity"
* to start the ChildActivity.
*/
startActivity(startChildActivityIntent);
}
}
private void signIn() {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInClient.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
// The Task returned from this call is always completed, no need to attach
// a listener.
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
handleSignInResult(task);
}
}
private void handleSignInResult(Task<GoogleSignInAccount> completedTask) {
try {
GoogleSignInAccount account = completedTask.getResult(ApiException.class);
String idToken = account.getIdToken();
Log.d("Token: ", idToken);
// Signed in successfully, show authenticated UI.
updateUI(account);
} catch (ApiException e) {
// The ApiException status code indicates the detailed failure reason.
// Please refer to the GoogleSignInStatusCodes class reference for more information.
Log.w(TAG, "signInResult:failed code=" + e.getStatusCode());
updateUI(null);
}
}
}
TaskActivity:
package package_name;
some imports...
public class TaskActivity extends AppCompatActivity {
private static final String URL_DATA = "https://some.url.be";
private RecyclerView recyclerView;
private RecyclerView.Adapter scorpioAdapter;
private List<ListItem> listItems;
String JSON_STRING;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_task);
recyclerView = findViewById(R.id.rv);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
listItems = new ArrayList<>();
}
/*REAL DATA*/
/*try instead of loadRecyclerViewData*/
public void getJSON(View view){
new BackgroundTask().execute();
}
/*end try*/
private void loadRecyclerViewData() {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading data...");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.GET,
URL_DATA,
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
progressDialog.dismiss();
try {
JSONArray jsonArray = new JSONArray(s);
for(int i=0;i<jsonArray.length();i++){
JSONObject o = jsonArray.getJSONObject(i);
int id = o.getInt("id");
String name = o.getString("name");
int done = o.getInt("done");
String reminderDate = o.getString("reminderdate");
String reminderTime = o.getString("remindertime");
ListItem item = new ListItem(id, name, done, reminderDate, reminderTime);
listItems.add(item);
}
scorpioAdapter = new ScorpioAdapter(listItems, getApplicationContext());
recyclerView.setAdapter(scorpioAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Toast.makeText(getApplicationContext(), volleyError.getMessage(), Toast.LENGTH_LONG).show();
}
}
);
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
/*END REAL DATA*/
/* things I tried*/
class BackgroundTask extends AsyncTask<Void, Void, String> {
String json_url;
#Override
protected void onPreExecute() {
json_url = "https://some.url.be";
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
Log.i("Scorpio To Do: ", result);
TextView name = (TextView) findViewById(R.id.name);
name.setText(result);
}
#Override
protected String doInBackground(Void... voids) {
try {
URL url = new URL(json_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
while ((JSON_STRING = bufferedReader.readLine()) != null){
stringBuilder.append(JSON_STRING + "\n");
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return stringBuilder.toString().trim();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
/*end try*/
}

Save Session Android

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

Categories