Fetch data from db when logged in with Google - java

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*/
}

Related

How to get data from database without refreshing the android app?

I developed an android application in which I want to get data from the database without refreshing the app. I tried different methods but no one works for me. I am using PHP for fetching data from the database into my android app. Below is my code which is for now only fetching data from a database but I have to refresh the app if I update data in the database to get the updated value in the app. I want realtime values from the database, like, if I update data in the database, I want the same update in the app but without refreshing it.
public class Profile extends AppCompatActivity implements View.OnClickListener {
private TextView textViewUsername,textViewHr,textViewBp;
private Button button;
private ProgressDialog progressDialog;
private SwipeRefreshLayout swipeRefreshLayout;
private ImageView imageViewWet, imageViewTempered;
String username;
private static int wet,tempered;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile2);
username = SharedPrefManager.getInstance(this).getUsername();
textViewUsername = (TextView) findViewById(R.id.pUsername);
textViewHr = (TextView) findViewById(R.id.heartRate);
textViewBp = (TextView) findViewById(R.id.bloodPressure);
swipeRefreshLayout = findViewById(R.id.swipeToRefresh);
imageViewTempered = (ImageView) findViewById(R.id.imageViewTempered);
imageViewWet =(ImageView) findViewById(R.id.imageViewWet);
button = (Button) findViewById(R.id.refresh);
wet = SharedPrefManager.getInstance(getApplicationContext()).getWetStatus();
tempered = SharedPrefManager.getInstance(getApplicationContext()).getTemperedStatus();
textViewUsername.setText(SharedPrefManager.getInstance(this).getUsername());
textViewHr.setText(String.valueOf(SharedPrefManager.getInstance(this).getHeartRate()));
textViewBp.setText(String.valueOf(SharedPrefManager.getInstance(this).getTemperature()));
if(wet==1){
imageViewWet.setImageResource(R.drawable.tick);
}
else{
imageViewWet.setImageResource(R.drawable.cross);
}
if(tempered == 1){
imageViewTempered.setImageResource(R.drawable.tick);
}
else{
imageViewTempered.setImageResource(R.drawable.cross);
}
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
data();
swipeRefreshLayout.setRefreshing(false);
}
});
button.setOnClickListener(this);
/*if(!SharedPrefManager.getInstance(this).isLoggedIn()){
finish();
startActivity(new Intent(this,ProfileActivity.class));
return;
}*/
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Please Wait...");
}
public void data(){
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.POST, Constants.URL_DATA,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
try {
JSONObject obj = new JSONObject(response);
if(!obj.getBoolean("error")){
System.out.println("IN SHARED SET VALES");
SharedPrefManager.getInstance(getApplicationContext()).data(obj.getInt("Id"),obj.getString("Username"),obj.getInt("Heart_Rate"),obj.getInt("Temperature"),obj.getInt("Wet"),obj.getInt("Tempered"));
textViewUsername.setText(SharedPrefManager.getInstance(getApplicationContext()).getUsername());
textViewHr.setText(String.valueOf(SharedPrefManager.getInstance(getApplicationContext()).getHeartRate()));
textViewBp.setText(String.valueOf(SharedPrefManager.getInstance(getApplicationContext()).getTemperature()));
wet = SharedPrefManager.getInstance(getApplicationContext()).getWetStatus();
tempered = SharedPrefManager.getInstance(getApplicationContext()).getTemperedStatus();
if(wet==1){
imageViewWet.setImageResource(R.drawable.tick);
}
else{
imageViewWet.setImageResource(R.drawable.cross);
}
if(tempered == 1){
imageViewTempered.setImageResource(R.drawable.tick);
}
else{
imageViewTempered.setImageResource(R.drawable.cross);
}
}else{
Toast.makeText(getApplicationContext(),obj.getString("message"),Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(),error.getMessage(),Toast.LENGTH_LONG).show();
}
}
){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<>();
params.put("Username",username);
return params;
}
};
RequestHandler.getInstance(this).addToRequestQueue(stringRequest);
}
#Override
public void onClick(View v) {
if(v == button){
data();
}
}
}
Below is the layout of my app. Basically I want to update Heart Rate and Temperature continuously without refreshing the app.
Please help me, how I can get data from the database into my app without refreshing the app?
Thanks in Advance
Try using reactive programming tools like RxJava or RxAndroid. Reactive Programming is basically event-based asynchronous programming.
Use time Outs to automatically refresh the content after few minutes .
Server Side app rendering and sockets could also be useful for such cases.

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.

How to get data from text view in first activity and post it from another activity?

I want the data of textview in the second activity to pass in the third but i dont want to display it in the third activity. I want to directly send the data from the second activity to Pass in my sql db after clicking the button in the final activity. Is is achievable?
This is my first activity.
public class MainActivity extends AppCompatActivity {
private EditText email, password;
private Button btn_login;
private ProgressBar loading;
private static String URL_LOGIN ="http://192.168.1.83/Attendance/login.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loading= findViewById(R.id.loading);
email = findViewById(R.id.editTextUserEmail);
password = findViewById(R.id.editTextPassword);
btn_login = findViewById(R.id.buttonRegister);
btn_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String mEmail = email.getText().toString().trim();
String mPassword = password.getText().toString().trim();
if (!mEmail.isEmpty() || !mPassword.isEmpty()) {
Login(mEmail, mPassword);
}else{
email.setError("Please Enter Email");
password.setError("Please Enter Password");
}
}
});
}
private void Login(final String email, final String password) {
loading.setVisibility(View.VISIBLE);
btn_login.setVisibility(View.GONE);
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_LOGIN,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
Log.d("JSON", jsonObject.toString());
String success = jsonObject.getString("success");
JSONArray jsonArray =
jsonObject.getJSONArray("login");
if (success.equals("1"))
{
for (int i = 0; i<jsonArray.length(); i++){
JSONObject object =
jsonArray.getJSONObject(i);
String name =
object.getString("name").trim();
String email =
object.getString("email").trim();
// Toast.makeText(MainActivity.this,
"Success Login \nYour name: "+name+"\nYour Email: "+email,
// Toast.LENGTH_LONG).show();
Intent intent = new
Intent(MainActivity.this, HomeActivity.class);
intent.putExtra("name",name);
intent.putExtra("email", email);
startActivity(intent);
loading.setVisibility(View.GONE);
}
}
} catch (JSONException e) {
e.printStackTrace();
loading.setVisibility(View.GONE);
btn_login.setVisibility(View.VISIBLE);
Toast.makeText(MainActivity.this, "Error"
+e.toString(),
Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "Error"
+error.toString(),
Toast.LENGTH_LONG).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("email", email);
params.put("password", password);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
This is my second activity
public class HomeActivity extends AppCompatActivity {
private TextView name,email;
private TextView welcome;
private Button Send;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
name = findViewById(R.id.name);
email = findViewById(R.id.email);
Send = findViewById(R.id.btn_send);
welcome = findViewById(R.id.welcome);
final Intent intent = getIntent();
String extraName = intent.getStringExtra("name");
String extraEmail = intent.getStringExtra("email");
name.setText(extraName);
email.setText(extraEmail);
Send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent1 = new Intent(HomeActivity.this,StatusActivity.class);
intent1.putExtra("wel", welcome.getText().toString());
intent1.putExtra("name1", name.getText().toString());
intent1.putExtra("email1", email.getText().toString());
startActivity(intent1);
}
});
}
And this is my final activity but Here i dont want to show the text view i just want to post it from here.
public class StatusActivity extends AppCompatActivity {
private TextView welcome, name, email;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_status);
welcome = findViewById(R.id.abcd);
name = findViewById(R.id.name1);
email = findViewById(R.id.email1);
final Intent intent = getIntent();
String extraName1 = intent.getStringExtra("name1");
String extraEmail1 = intent.getStringExtra("email1");
String extraWelcome = intent.getStringExtra("wel");
name.setText(extraName1);
email.setText(extraEmail1);
welcome.setText(extraWelcome);
}
Your question is pretty clear until you put MySql to the topic. Why you want to pass the data from one activity to another through the database. Why involve database operations which take time and resources.
You may pass data from one activity to another through Intents (primitive values, Strings and Parcelables)!
All you have to do is:
Get the data (int your case from TextView).
Create the Intent to navigate to the next Activity.
Put the data to the Intent.
Start the Activity.
Retrieve the data from the Intent.
For example if will navigate to the next Activity via button click then in that button's onClick():
// 1.
String data = myTextView.getText();
// 2.
Intent intent = new Intent(yourContext,YourNextActivity.class);
// 3.
intent.putStringExtra("MY DATA KEY",data);
// 4.
yourContext.startActivity(intent);
// 5. Now in YourNextActivity's onCreate();
String retrievedData = YourNextActivity.this.getIntent().getStringExtra("MY DATA KEY");
// Done!

onCreate(Bundle) is already defined in .com

How do I fix this duplication of onCreate.
I tried changing onCreate to onCreate1
but #Override gets an error saying
"Method does not override method from its superclass"
how do i fix this pls help thank you so much
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
email = (EditText) findViewById(R.id.email);
password = (EditText) findViewById(R.id.password);
login = (Button) findViewById(R.id.login);
signup = (TextView) findViewById(R.id.open_signup);
progressDialog = new ProgressDialog(this);
session = new UserSession(this);
userInfo = new UserInfo(this);
if (session.isUserLoggedin()) {
startActivity(new Intent(this, MainActivity.class));
finish();
}
login.setOnClickListener(this);
signup.setOnClickListener(this);
}
private void login(final String email, final String password) {
//Tag used to cancel the request
String tag_string_req = "req_login";
progressDialog.setMessage("Logging in....");
progressDialog.show();
StringRequest strReq = new StringRequest(Request.Method.POST,
Utils.LOGIN_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Login Response: " + response.toString());
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
//check for error node in json
if (!error) {
//now store the user in SQLite
JSONObject user = jObj.getJSONObject("user");
String uName = user.getString("username");
String email = user.getString("email");
//Inserting row in users table
userInfo.setEmail(email);
userInfo.setUsername(uName);
session.setLoggedin(true);
startActivity(new Intent(Login.this, MainActivity.class));
finish();
} else {
//error in login, get the error message
String errorMsg = jObj.getString("error_msg");
toast(errorMsg);
}
} catch (JSONException e) {
//json error
e.printStackTrace();
toast("Json error: " + e.getMessage());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Login Error: " + error.getMessage());
toast("Unknown Error occured");
progressDialog.hide();
}
}) {
#Override
protected Map<String, String> getParams() {
//Posting parameters to login url
Map<String, String> params = new HashMap<>();
params.put("email", email);
params.put("password", password);
return params;
}
;
//Adding request to request queue
AndroidLoginController.getInstance();
addToRequestQueue(strReq, tag_string_req);
}
private void toast(String x) {
Toast.makeText(this, x, Toast.LENGTH_SHORT).show();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.login:
String uName = email.getText().toString().trim();
String pass = password.getText().toString().trim();
login(uName, pass);
break;
case R.id.open_signup:
startActivity(new Intent(this, SignUp.class));
break;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
public Action getIndexApiAction() {
Thing object = new Thing.Builder()
.setName("Login Page") // TODO: Define a title for the content shown.
// TODO: Make sure this auto-generated URL is correct.
.setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
.build();
return new Action.Builder(Action.TYPE_VIEW)
.setObject(object)
.setActionStatus(Action.STATUS_TYPE_COMPLETED)
.build();
}
#Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
AppIndex.AppIndexApi.start(client, getIndexApiAction());
}
#Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
AppIndex.AppIndexApi.end(client, getIndexApiAction());
client.disconnect();
}
}
You don't need two onCreate methods. You need to do all what you need into one of these two methods.
Delete the other one
It's not possible to have two methods with the same signature in Java.
Furthermore onCreate is called automatically by Android, so creating a onCreate1 method should resolve in non executed code.
Remove
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
add below line in your First and only onCreate
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
eg:
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
email = (EditText) findViewById(R.id.email);
password = (EditText) findViewById(R.id.password);
login = (Button) findViewById(R.id.login);
signup = (TextView) findViewById(R.id.open_signup);
progressDialog = new ProgressDialog(this);
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
session = new UserSession(this);
userInfo = new UserInfo(this);
if (session.isUserLoggedin()) {
startActivity(new Intent(this, MainActivity.class));
finish();
}
login.setOnClickListener(this);
signup.setOnClickListener(this);
}
Method does not override method from its superclass
means your override method can't find the superclassmethod, because there is no superclass method by that name
For me quoting this answer
Why are we forced to call super.method()?
The classes that make up the Android SDK can be incredibly complex. For instance, both activities and fragments must perform a number of operations in order to function properly (i.e. managing life cycle, optimizing memory usage, drawing the layout to the screen, etc.). Requiring the client to make a call to the base class (often at the beginning of the method) ensures that these operations are still performed, while still providing a reasonable level of abstraction for the developer.
How do we know that a function method requires super to be called?
The documentation should tell you whether or not this is required. If it doesn't I'd Google-search for some sample code (or check the API demos... or better yet, look at the source code!). It shouldn't be too difficult to figure out.

AsyncTask and Handler always Start Activity twice after Logout

i have a problem to send fbid to my server after logged out once. and if i want to login again it always send twice request and start the activity twice.
MainActivity.java:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i("TheGaffer", "ONCREATE");
mFacebook = new Facebook(APP_ID);
SessionStore.restore(mFacebook, this);
setContentView(R.layout.login_view);
mLoginButton = (LoginButton) findViewById(R.id.login);
SessionEvents.addAuthListener(new SampleAuthListener());
mLoginButton.init(this, mFacebook);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
mFacebook.authorizeCallback(requestCode, resultCode, data);
}
public class SampleAuthListener implements AuthListener {
public void onAuthSucceed() {
new fbRequest().execute("/user_profiles/registerUser");
}
private class fbRequest extends AsyncTask<String, Void, String> {
protected void onPreExecute() {
progressDialog = ProgressDialog.show(TheGaffer.this , null,
"Loading...");
}
protected String doInBackground(String... urls) {
String fbid = null;
Bundle params = new Bundle();
params.putString("fields", "id,name");
try {
JSONObject jsonObjSend = new JSONObject();
JSONObject fbData = new JSONObject(mFacebook.request("me", params));
fbid = fbData.getString("id");
jsonObjSend.put("fbid", fbData.getString("id"));
jsonObjSend.put("username", fbData.getString("name"));
jsonObjSend.put("playerPhoto", "http://graph.facebook.com/"+ fbData.getString("id") +"/picture");
HttpClient.SendHttpPost(urls[0], jsonObjSend);
} catch (Exception e) {
Log.e("FACEBOOK", "Error parsing data " + e.toString());
}
return fbid;
}
#Override
protected void onPostExecute(String fbid) {
Toast.makeText(getApplicationContext(), "Login successful", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
Intent intent = new Intent(TheGaffer.this, TeamActivity.class);
intent.putExtra("fbid", fbid);
startActivity(intent);
}
}
TeamActivity.java:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_create_team:
intent = new Intent(TeamActivity.this, CreateTeam.class);
return true;
case R.id.menu_logout:
Log.i("Logout", "Logged out");
Intent intent = new Intent(TeamActivity.this, TheGaffer.class);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Once I was trapped in similar situation where Activity call twice one after another.
To avoid this after lots of research I find a very easy solution.
May be solution is not perfect but works for me
in manifest.xml file
in your activity just add
android:launchMode="singleTask"

Categories