Related
I'm not being able to publish messages with Nearby.Messages, although the Subscribe method seems to be working well. I've already created new credentials for Nearby in my Google Developer Console, made sure both the SHA-1's of my computer, and the app in the PlayStore are associated with those credentials, as well as the app's package name.
As I added an OnSuccessListener to both Publish, and Subscribe, within onStart, I noticed that the Subscribe method works well, while the Publish one Fails. The error code is 2806 - Forbidden.
It used to work just the way it is. Only after I uploaded the app to the Play Store, and had to add a new OAuth 2.0 Client ID, did it stop working, on publishing the desired Message. I've maintained the previous ID, as well, so I continue testing on my device, installing from Android Studio. Meanwhile, I've also re-created both ID's in the Console, but the problem still occurs. The Nearby function is also active, on the Console.
Adding the Fragment's code below:
package co.thanker.fragments;
import android.graphics.PorterDuff;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import com.bumptech.glide.Glide;
import com.google.android.gms.nearby.Nearby;
import com.google.android.gms.nearby.messages.Message;
import com.google.android.gms.nearby.messages.MessageListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import co.thanker.R;
public class FindFragment extends Fragment {
private final String TAG = "FindFragment";
private final String OUR_USER_ID = "our-user-id";
private final String OUR_USER_COUNTRY = "our-user-country";
private final String USER_ID_STRING = "user-id-string";
private final String THANKER_ID_STRING = "thanker-id-string";
private final String USER_COUNTRY = "user-country";
private final String CONTINUE_SENDING_ID = "continue-sending-user-id";
private final String ACTIVATED_THANKS = "activated-thanks";
private Message mSendingMessage;
private MessageListener mMessageListener;
private FirebaseAuth mAuth;
private String mCountry;
private String mUserId;
private boolean mActivatedThanks;
private ImageView mGifFind;
private ProgressBar mProgressBar;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View view = inflater.inflate(R.layout.fragment_find, container, false);
Log.v(TAG, "Entering FindFragment");
mAuth = FirebaseAuth.getInstance();
mActivatedThanks = true;
mGifFind = (ImageView) view.findViewById(R.id.gif_find);
mProgressBar = (ProgressBar) view.findViewById(R.id.progress_bar);
if(getArguments() != null){
Log.v(TAG, "Finding passing Country. Thanks Fragment. GetArguments() exists");
mUserId = getArguments().getString(THANKER_ID_STRING);
mCountry = getArguments().getString(OUR_USER_COUNTRY);
}
else {
Log.v(TAG, "Finding passing Country. Thanks Fragment. GetArguments() does not exist");
mUserId = mAuth.getCurrentUser().getUid();
}
Log.v(TAG, "Nearby. Thanks got in Thanks Fragment: " + mCountry + ". User ID: " + mUserId);
if(getActivity() != null){
Glide.with(getActivity()).load(R.drawable.nearby_search).into(mGifFind);
mProgressBar.getIndeterminateDrawable().setColorFilter(ContextCompat.getColor(getActivity(), R.color.colorPrimaryDark), PorterDuff.Mode.SRC_IN );
}
mMessageListener = new MessageListener() {
#Override
public void onFound(Message message) {
Log.d(TAG, "Nearby. Found message: " + new String(message.getContent()));
final String otherUserId = new String(message.getContent()).trim();
if(!otherUserId.equalsIgnoreCase(mAuth.getCurrentUser().getUid())){
Fragment otherUserProfileFragment = new OtherProfileFragment();
Bundle userInfoBundle = new Bundle();
userInfoBundle.putString(USER_ID_STRING, otherUserId);
userInfoBundle.putString(OUR_USER_ID, mUserId);
userInfoBundle.putString(OUR_USER_COUNTRY, mCountry);
userInfoBundle.putBoolean(ACTIVATED_THANKS, mActivatedThanks);
userInfoBundle.putBoolean(CONTINUE_SENDING_ID, true);
otherUserProfileFragment.setArguments(userInfoBundle);
if(getActivity() != null){
mProgressBar.setVisibility(View.GONE);
getActivity().getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container, otherUserProfileFragment).addToBackStack(null).commit();
}
}
}
#Override
public void onLost(Message message) {
Log.d(TAG, "Nearby. Lost sight of message: " + new String(message.getContent()));
}
};
byte [] userIdInBytes = mUserId.getBytes();
mSendingMessage = new Message(userIdInBytes);
Log.v(TAG, "Nearby. Sending Message: " + new String(mSendingMessage.getContent()));
return view;
}
#Override
public void onStart(){
super.onStart();
if(getActivity() != null){
Nearby.getMessagesClient(getActivity()).publish(mSendingMessage).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.v(TAG, "Nearby. Publishing key");
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.v(TAG, "Nearby. Couldn\'t publish key. Error: " + e.toString());
}
});
Nearby.getMessagesClient(getActivity()).subscribe(mMessageListener).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.v(TAG, "Nearby. Subscribing incoming message");
}
});
}
}
#Override
public void onStop(){
if(getActivity() != null){
Nearby.getMessagesClient(getActivity()).unpublish(mSendingMessage);
Nearby.getMessagesClient(getActivity()).unsubscribe(mMessageListener);
Log.v(TAG, "Nearby. Unpublished keys");
}
super.onStop();
}
}
Really appreciate your help!
Best regards,
I have this code in android studio for an app, I am trying to read from a file for the information of the login but anything after BufferedReader is not executing.
both the registration and login page open, the first page in the app i have sa login button and a registration button, when i click on the login button nothng happen, not even checking if the user exist or not
I tried many ways for reading and writing to a file but I couldn't figure out the error
it is not reading anything and not writing any thing, it simply does nothing.
this is the login page
package com.example.admin.projectfinal;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TextInputEditText;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.example.admin.projectfinal.val.inputValidation;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.StringTokenizer;
public class LoginActivity extends AppCompatActivity {
private inputValidation InputValidation;
private TextInputLayout IDLayout;
private TextInputLayout PASSWORDlayout;
private TextInputEditText LogID;
private TextInputEditText PASS;
Button SI;
TextView TV;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
getSupportActionBar().hide();
PASS = findViewById(R.id.password);
LogID = findViewById(R.id.idd);
IDLayout = findViewById(R.id.IDLayout);
PASSWORDlayout = findViewById(R.id.PasswordLayout);
TV = findViewById(R.id.tv);
SI = findViewById(R.id.signin);
SI.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
login();
}
});
TV.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Navigate to RegisterActivity
Toast.makeText(LoginActivity.this, "we are in tv.", Toast.LENGTH_LONG).show();
Intent intentRegister = new Intent(LoginActivity.this, RegisterActivity.class);
startActivity(intentRegister);
}
});
InputValidation = new inputValidation(LoginActivity.this);
}
private void login() {
if (!InputValidation.isInputEditTextFilled(LogID, IDLayout, "ID not filled ")) return;
if (!InputValidation.isInputEditTextFilled(PASS, PASSWORDlayout, "Password not filled"))
return;
TextView FileContentTextView = findViewById(R.id.tv_file_content);
try {
File f = new File ("User.txt");
BufferedReader reader = new BufferedReader(new FileReader(f));
if (reader.ready()) {
FileContentTextView.setText("No User registered");
return;
} else {
Toast.makeText(LoginActivity.this, "else", Toast.LENGTH_LONG).show();
boolean found = false;
String role = null;
String line;
while ((line = reader.readLine()) != null) {
Toast.makeText(LoginActivity.this, "while", Toast.LENGTH_LONG).show();
StringTokenizer user = new StringTokenizer(line);
String name = user.nextToken();
String Id = user.nextToken();
String dob = user.nextToken();
String pas = user.nextToken();
String Campus = user.nextToken();
String gender = user.nextToken();
role = user.nextToken();
if (LogID.equals(Id)) {
Toast.makeText(LoginActivity.this, "id is good", Toast.LENGTH_LONG).show();
if (PASS.equals(pas)) {
Toast.makeText(LoginActivity.this, "pass good", Toast.LENGTH_LONG).show();
found = true;
break;
}
}
if (found) {
Toast.makeText(LoginActivity.this, "break.", Toast.LENGTH_LONG).show();
break;
}
}
if (found) {
Toast.makeText(LoginActivity.this, "found", Toast.LENGTH_LONG).show();
if (role.equals("Security")) {
Intent accountsIntent = new Intent(LoginActivity.this, SecurityPage.class);
accountsIntent.putExtra("ID", LogID.getText().toString().trim());
} else {
Intent accountsIntent = new Intent(LoginActivity.this, StudentPage.class);
accountsIntent.putExtra("ID", LogID.getText().toString().trim());
}
} else
reader.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
}
this is the registration code, it has the same problem where anything after the BufferedReader is not executing.
package com.example.admin.projectfinal;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TextInputEditText;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
import com.example.admin.projectfinal.val.inputValidation;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class RegisterActivity extends AppCompatActivity implements View.OnClickListener{
private TextInputLayout textInputLayoutName;
private TextInputLayout textInputLayoutId;
private TextInputLayout textInputLayoutPassword;
private TextInputLayout textInputLayoutDate;
TextInputEditText Name;
TextInputEditText id;
TextInputEditText Password;
TextInputEditText DOB;
Spinner campus;
Spinner Role;
Spinner Gender;
Button btn;
Button Cancel;
private inputValidation InputValidation;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
Name = findViewById(R.id.name);
id = findViewById(R.id.ID);
Password = findViewById(R.id.password);
DOB = findViewById(R.id.dob);
btn = findViewById(R.id.next);
Cancel = findViewById(R.id.cancel);
campus = findViewById(R.id.campus);
Gender = findViewById(R.id.gender);
Role = findViewById(R.id.role);
textInputLayoutName = findViewById(R.id.NameLayout);
textInputLayoutId = findViewById(R.id.IdLayout);
textInputLayoutPassword = findViewById(R.id.PasswordLayout);
textInputLayoutDate = findViewById(R.id.DOBLayout);
//list for campus
String[] CampusList = new String[]{"MainCampus", "SasAlNakhlCampus", "MasdarCampus"};
ArrayAdapter<String> adapter1 = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, CampusList);
campus.setAdapter(adapter1);
//list for gender
String[] gen = new String[]{"Male", "Female"};
ArrayAdapter<String> genAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, gen);
Gender.setAdapter(genAdapter);
//list for role
String[] rolee = new String[]{"Student", "Security"};
ArrayAdapter<String> roleAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, rolee);
Role.setAdapter(roleAdapter);
// Buttons validation
btn.setOnClickListener(this);
Cancel.setOnClickListener(this);
InputValidation = new inputValidation(RegisterActivity.this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.next:
try {
validate();
} catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
break;
case R.id.cancel:
// Navigate to RegisterActivity
Intent intentRegister = new Intent(this, LoginActivity.class);
startActivity(intentRegister);
break;
}
}
private void validate() throws IOException {
boolean filled = true;
if (!InputValidation.isInputEditTextFilled(Name, textInputLayoutName, "Fill Name")) {
filled = false;
return;
}
if (!InputValidation.isInputEditTextFilled(id, textInputLayoutId, "Fill ID")) {
filled = false;
return;
}
if (!InputValidation.isInputEditTextFilled(DOB, textInputLayoutDate, "Fill Date")) {
filled = false;
return;
}
if (!InputValidation.isInputEditTextFilled(Password, textInputLayoutPassword, "Invalid Password")) {
filled = false;
return;
}
if (filled){
//if (!UserInfo.exists()) UserInfo.createNewFile();
String line;
boolean found = false;
BufferedReader reader= new BufferedReader(new FileReader("User.txt"));
Toast.makeText(getBaseContext(), "ready", Toast.LENGTH_LONG).show();
while ((line = reader.readLine()) != null) {
Toast.makeText(getBaseContext(), "while", Toast.LENGTH_LONG).show();
String[] user = line.split(" ");
String name = user[0];
String Id = user[1];
String dob = user[2];
String password = user[3];
String Campus = user[4];
String gender = user[5];
String role = user[6];
if (id.equals(Id)) {
found = true;
Toast.makeText(getBaseContext(), "User Exist", Toast.LENGTH_LONG).show();
break;
}
if (!found) {
// Adds a line to the file
PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter("User.txt")));
writer.append(Name + " " + id + " " + DOB + " " + Password + " "
+ campus.getSelectedItem() + " " + Gender.getSelectedItem() + " " + Role.getSelectedItem() + "/n" );
}
}
reader.close();
}
}
}
Input validation class I used in the code:
package com.example.admin.projectfinal.val;
import android.app.Activity;
import android.content.Context;
import android.support.design.widget.TextInputEditText;
import android.support.design.widget.TextInputLayout;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
public class inputValidation {
private static Context context;
/**
* constructor
*
* #param context
*/
public inputValidation(Context context) {
this.context = context;
}
/**
* method to check InputEditText filled .
*
* #param textInputEditText
* #param textInputLayout
* #param message
* #return
*/
public static boolean isInputEditTextFilled(TextInputEditText textInputEditText, TextInputLayout textInputLayout, String message) {
String value = textInputEditText.getText().toString().trim();
if (value.isEmpty()) {
textInputLayout.setError(message);
hideKeyboardFrom(textInputEditText);
return false;
} else {
textInputLayout.setErrorEnabled(false);
}
return true;
}
/**
* method to Hide keyboard
*
* #param view
*/
private static void hideKeyboardFrom(View view) {
InputMethodManager imm = (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}
}
I was able to implement a Facebook login for a social networking app i am developing for android. I used Facebook's android sdk to do so, as well as getting first/last name, gender and age and displaying it on a profile page. Now i want to know how i can store this information on a database in order to display it to other users who visit the profile. Thanks in advance! Here is the code i am using for the profile page.
import android.content.Intent;
import android.graphics.Typeface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.TypedValue;
import android.widget.ImageView;
import android.widget.TextView;
import com.facebook.AccessToken;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.Profile;
import com.squareup.picasso.Picasso;
import org.json.JSONObject;
public class ProfileActivity extends AppCompatActivity {
private Profile profile = Profile.getCurrentProfile();
public ImageView profileActivityPicture;
public TextView nameFirst, nameLast, age, gend, user_location;
private String userID, email, gender, picture, birthday, name, city;
private String profilePicUrl;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar2);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null){
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setTitle("My Profile");
}
nameFirst = (TextView) findViewById(R.id.profileActivityFirstName);
nameLast = (TextView) findViewById(R.id.profileActivityLastName);
age = (TextView) findViewById(R.id.profileActivityAge);
gend = (TextView) findViewById(R.id.profileActivityGender);
profileActivityPicture = (ImageView) findViewById(R.id.profileActivityPic);
user_location = (TextView) findViewById(R.id.profileActivityCity);
if(profile != null) {
nameFirst.setText(getString(R.string.hello_user, profile.getFirstName()));
nameLast.setText(getString(R.string.hello_user, profile.getLastName()));
}
nameFirst.setTextSize(TypedValue.COMPLEX_UNIT_SP,20);
nameFirst.setTypeface(null, Typeface.BOLD);
nameLast.setTextSize(TypedValue.COMPLEX_UNIT_SP,20);
nameLast.setTypeface(null, Typeface.BOLD);
GraphRequest request = GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject data,
GraphResponse response) {
try {
data = response.getJSONObject();
if (data.has("id"))
userID = data.getString("id");
if (data.has("name"))
name = data.getString("name");
if (data.has("location"))
city = data.getJSONObject("location").getString("name");
user_location.setText(city);
user_location.setTextSize(TypedValue.COMPLEX_UNIT_SP,14);
if (data.has("picture"))
Picasso.with(ProfileActivity.this).load("https://graph.facebook.com/" + userID+ "/picture?width=3000&height=4000").into(profileActivityPicture);
if (data.has("birthday"))
birthday = data.getString("birthday");
age.setText(birthday);
age.setTextSize(TypedValue.COMPLEX_UNIT_SP,20);
age.setTypeface(null, Typeface.BOLD);
if (data.has("gender"))
gender = data.getString("gender");
gend.setText(gender);
gend.setTextSize(TypedValue.COMPLEX_UNIT_SP,18);
} catch(Exception e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,gender,cover,picture.type(large),location");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
#Override
public void onBackPressed() {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
#Override
public void onDestroy(){
super.onDestroy();
}
}
When you get response in completed callback simply Parse like this
JSONObject jobj = response.getJSONObject();
if (jobj != null) {
try {
ProfileBean profileBean = new ProfileBean();
profileBean.id = jobj.getString("id");
profileBean.name = jobj.getString("name");
profileBean.email = jobj.getString("email");
profileBean.link = jobj.getString("link");
profileBean.last_name = jobj.getString("last_name");
profileBean.first_name = jobj.getString("first_name");
profileBean.gender = jobj.getString("gender");
JSONObject pic = jobj.getJSONObject("picture");
JSONObject data = pic.getJSONObject("data");
profileBean.profile_pic = data.getString("url");
} catch (Exception e) {
// print exception
}
}
here you FB data are stored in a profileBean so like this you can get your data..
i am currently developping an application for my third year project, it's an android app (i used android studio) that will access a database that i created on my wamp server, the connection works perfectly from the application when i debug it on my android phone( i used in my code the "HttpURLConnection" with the url being my pc ip adress that i got from (cmd/ipconfig) ) .
The problem is that once i disconnect my phone from my pc and try to run the application from the phone, the connection with the database won't work, and also if i connect my pc to another modem, my pc ip changes, which is pretty much normal, but i don't think supposed to change the ip everytime the modem i connect to change ( although i'm not really sure, server connexions are clearly not something i'm an expert at ) , so i tried to use the ip of my pc on the internet that i got from "ipaddress.com" but it won't work, not even if i debug the application directly from android studio,
i don't have much time left to present the application , so i need a quick answer, thank you in advance
P.S : i guess i gotta mention that i need to acces the database to read AND write on it from the phone since it's an app that permits login/registration and will get the data that the user will enter and store it in the database .
I don't know wheter understanded, when you disconnect your phone from your pc, the app dead? or simplely it don't connect with db. Regard router, you need an account in "no-ip" and configure forguard's router on port 80 to redirect your computer's static IP. i need more details and information to help you. Regards
Try to connect the Phone and Mobile in same network.
your connection Url would be Like this 192.10.20.2 which is your ip or computer. as your get it form cmd using ipconfig command.
but whenever your networks changes your have to decompile to change the ip. or provide ip via textview.
take a Editview to take ip. and the concat it to your url. this will work. as it worked for me.
i'm working on an external server
The php code (for the connection to the db)
<?php
$db_name="pfe";
$mysql_username="root";
$mysql_password="";
$server_name="localhost";
$conn = mysqli_connect($server_name,$mysql_username,$mysql_password,$db_name);
?>
then i got another php file which handles the login part
<?php
require "connexion.php";
$user_email =$_POST["user-email"];
$user_pass =$_POST["password"];
$mysql_qry = "select id from donateur where email like '$user_email' and
password like '$user_pass'";
$result = mysqli_query($conn , $mysql_qry);
if(($row=mysqli_fetch_assoc($result))!=null){
$a = array('myarray' => array("donateur", $row["id"]));
echo json_encode($a);}
else {
$mysql_qry2 = "select id, username from association where email like
'$user_email' and password like '$user_pass'";
$result2 = mysqli_query($conn , $mysql_qry2);
if(($row=mysqli_fetch_assoc($result2))!=null) { $a = array('myarray' =>
array("association", $row["id"]));
echo json_encode($a);
}
else { echo "rien";}}
$conn->close();
the java code :
package applis.pfe;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.CursorLoader;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static android.Manifest.permission.READ_CONTACTS;
public class LoginActivity extends AppCompatActivity implements
LoaderCallbacks<Cursor> {
/**
* Id to identity READ_CONTACTS permission request.
*/
private static final int REQUEST_READ_CONTACTS = 0;
DonateurDAO donateurdao= new DonateurDAO(this);
AssociationDAO associationdao=new AssociationDAO(this);
/**
* Keep track of the login task to ensure we can cancel it if requested.
*/
String ip="http://105.101.179.155/";
private UserLoginTask mAuthTask = null;
// UI references.
private AutoCompleteTextView mEmailView;
private EditText mPasswordView;
private View mProgressView;
private View mLoginFormView;
public static String qui;
public static int id;
public static String username;
SessionManager session;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
///////////////////// POUR AFFICHER LE MESSAGE DIINSCRIPTION REUSSIE /////////////////////////////////////
if(getIntent().getStringExtra("inscription")!=null &&
getIntent().getStringExtra("inscription").equals("oui"))
{ AlertDialog a= new AlertDialog.Builder(LoginActivity.this).create();
a.setTitle("Inscription réussie !");
a.setMessage("Votre inscription a été validé, veuillez vous connecter
pour pouvoir continuer");
a.show();}
session = new SessionManager(this);
// Set up the login form.
mEmailView = (AutoCompleteTextView) findViewById(R.id.email);
// populateAutoComplete();
mPasswordView = (EditText) findViewById(R.id.password);
mPasswordView.setOnEditorActionListener(new
TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView textView, int id, KeyEvent
keyEvent) {
if (id == R.id.login || id == EditorInfo.IME_NULL) {
attemptLogin();
return true;
}
return false;
}
});
Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
mEmailSignInButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {attemptLogin();
}
});
mLoginFormView = findViewById(R.id.login_form);
mProgressView = findViewById(R.id.login_progress);
ImageButton btn;
btn =(ImageButton)findViewById(R.id.InscriptionDonateurButton);
btn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {Intent in= new
Intent(LoginActivity.this,InscriptionDonateurActivity.class);
startActivity(in);
}
});
ImageButton btn1;
btn1 =(ImageButton)findViewById(R.id.InscriptionAssociationButton);
btn1.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {Intent in= new
Intent(LoginActivity.this,InscriptionAssociationActivity.class);
startActivity(in);
}
});
}
private void attemptLogin() {
if (mAuthTask != null) {
return;
}
// Reset errors.
mEmailView.setError(null);
mPasswordView.setError(null);
// Store values at the time of the login attempt.
String email = mEmailView.getText().toString();
String password = mPasswordView.getText().toString();
boolean cancel = false;
View focusView = null;
// Check for a valid password, if the user entered one.
if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
mPasswordView.setError(getString(R.string.error_invalid_password));
focusView = mPasswordView;
cancel = true;
}
// Check for a valid email address.
if (TextUtils.isEmpty(email)) {
mEmailView.setError(getString(R.string.error_field_required));
focusView = mEmailView;
cancel = true;
} else if (!isEmailValid(email)) {
mEmailView.setError(getString(R.string.error_invalid_email));
focusView = mEmailView;
cancel = true;
}
if (cancel) {
// There was an error; don't attempt login and focus the first
// form field with an error.
focusView.requestFocus();
} else {
// Show a progress spinner, and kick off a background task to
// perform the user login attempt.
showProgress(true);
mAuthTask = new UserLoginTask(email, password);
mAuthTask.execute((Void) null);
}
}
private boolean isEmailValid(String email) {
//TODO: Replace this with your own logic
return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
private boolean isPasswordValid(String password) {
//TODO: Replace this with your own logic
return password.length() > 4;
}
/**
* Shows the progress UI and hides the login form.
*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
private void showProgress(final boolean show) {
// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
// for very easy animations. If available, use these APIs to fade-in
// the progress spinner.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
mLoginFormView.animate().setDuration(shortAnimTime).alpha(
show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
});
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mProgressView.animate().setDuration(shortAnimTime).alpha(
show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
}
});
} else {
// The ViewPropertyAnimator APIs are not available, so simply show
// and hide the relevant UI components.
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
}
#Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
return new CursorLoader(this,
// Retrieve data rows for the device user's 'profile' contact.
Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI,
ContactsContract.Contacts.Data.CONTENT_DIRECTORY), ProfileQuery.PROJECTION,
// Select only email addresses.
ContactsContract.Contacts.Data.MIMETYPE +
" = ?", new String[]{ContactsContract.CommonDataKinds.Email
.CONTENT_ITEM_TYPE},
// Show primary email addresses first. Note that there won't be
// a primary email address if the user hasn't specified one.
ContactsContract.Contacts.Data.IS_PRIMARY + " DESC");
}
#Override
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
List<String> emails = new ArrayList<>();
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
emails.add(cursor.getString(ProfileQuery.ADDRESS));
cursor.moveToNext();
}
addEmailsToAutoComplete(emails);
}
#Override
public void onLoaderReset(Loader<Cursor> cursorLoader) {
}
private void addEmailsToAutoComplete(List<String> emailAddressCollection) {
//Create adapter to tell the AutoCompleteTextView what to show in its dropdown list.
ArrayAdapter<String> adapter =
new ArrayAdapter<>(LoginActivity.this,
android.R.layout.simple_dropdown_item_1line, emailAddressCollection);
mEmailView.setAdapter(adapter);
}
private interface ProfileQuery {
String[] PROJECTION = {
ContactsContract.CommonDataKinds.Email.ADDRESS,
ContactsContract.CommonDataKinds.Email.IS_PRIMARY,
};
int ADDRESS = 0;
int IS_PRIMARY = 1;
}
/**
* Represents an asynchronous login/registration task used to authenticate
* the user.
*/
public class UserLoginTask extends AsyncTask<Void, Void, String> {
private final String mEmail;
private final String mPassword;
UserLoginTask(String email, String password) {
mEmail = email;
mPassword = password;
}
#Override
protected String doInBackground(Void... params) {
// TODO: attempt authentication against a network service.
String login_url= ip.concat("login.php");
try {
URL url= new URL(login_url);
HttpURLConnection httpURLConnection=(HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
OutputStream outputStream= httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter= new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
String Post_data= URLEncoder.encode("user-email","UTF-8")+"="+URLEncoder.encode(mEmail,"UTF-8")+"&"
+URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(mPassword,"UTF-8");
bufferedWriter.write(Post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream=httpURLConnection.getInputStream();
qui=null;
id=0;
BufferedReader bufferedReader= new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String resultat="";
String ligne="";
while((ligne=bufferedReader.readLine())!=null)
resultat += ligne;
if (resultat.equals("rien")) return resultat; else {
JSONObject jsonObject = new JSONObject(resultat);
JSONArray json_data = jsonObject.getJSONArray("myarray");
qui=json_data.getString(0);
id=json_data.getInt(1);
username= json_data.getString(2);}
/* for(int i=0;i<json_data.length();i++)
{
k++;
qui= json_data.getString(1);
id= json_data.getInt(2);
//r.add(json_data.getString("categorie"));
}*/
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return resultat;
} catch (MalformedURLException e) {
e.printStackTrace();return e.toString();
} catch (IOException e) {
e.printStackTrace();return e.toString();
} catch (JSONException e) {
e.printStackTrace(); return e.toString();
}
}
/* for (String credential : DUMMY_CREDENTIALS) {
String[] pieces = credential.split(":");
if (pieces[0].equals(mEmail)) {
// Account exists, return true if the password matches.
return pieces[1].equals(mPassword);
}
}*/
// TODO: register the new account here.
#Override
protected void onPostExecute(String resultat) {
mAuthTask = null;
showProgress(false);
/////////////////////////////////////////////////////////////////////////////////
Intent i;
AlertDialog a;
if (resultat.equals("rien")){i= new Intent(LoginActivity.this,LoginActivity.class);
a= new AlertDialog.Builder(LoginActivity.this).create();
a.setTitle("Erreur");
a.setMessage(" Email et/ou mot de passe erroné(s)");
a.show();} else {
try {
session.createLoginSession(mEmail,username,qui,id);
session.checkLogin();
if (qui.equals("donateur")) {
i = new Intent(LoginActivity.this, Suite_Inscription_Donateur.class);
i.putExtra("id", id);
startActivity(i);
} else if (qui.equals("association")) {
session.createLoginSession(mEmail,username,qui,id);
i = new Intent(LoginActivity.this, Suite_Inscription_Association.class);
i.putExtra("id", id);
startActivity(i);
}
} catch (Exception e) {
e.printStackTrace();
a= new AlertDialog.Builder(LoginActivity.this).create();
a.setTitle("Erreur");
a.setMessage("Erreur :".concat(e.toString()));
a.show();
}
}
#Override
protected void onCancelled() {
mAuthTask = null;
showProgress(false);
}
}
}
package symca.gescoe.com.sampleparseapp.payment_task;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import symca.gescoe.com.sampleparseapp.R;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.parse.FindCallback;
import com.parse.GetCallback;
import com.parse.ParseACL;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseUser;
import com.parse.SaveCallback;
import java.util.List;
public class PayRent extends Activity {
TextView ownerName, ownerEmail, ownerPropType, ownerLocation, ownerAccountNo, renterAccountNo;
EditText propId;
int confirmFlag = 0;
int rentFinal = 0, mainFinal = 0, totalFinal = 0;
int rent;
int maintenance;
String ownerNameStr;
String ownerEmailStr;
String ownerPropTypeStr;
String ownerLocationStr;
String ownerAccountNoStr;
String renterAccountNoStr;
String propIdStr;
Button btnpayRent;
ImageView btnConfirm;
int payInterestFlag = 1;
ProgressDialog progressDialog;
String proType, location, email, fname, lname, ownerAccount, renterAccount;
String ownerObjId,ownerAvlBal;
int bhk;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pay_rent);
// ParseACL defaultACL = new ParseACL();
// defaultACL.setPublicWriteAccess(true);//------temp
btnConfirm = (ImageView) findViewById(R.id.btnConfirmIDPay);
btnpayRent = (Button) findViewById(R.id.btnPayRent);
propId = (EditText) findViewById(R.id.tvPropIDPay);
ownerName = (TextView) findViewById(R.id.tvNamePay);
ownerEmail = (TextView) findViewById(R.id.tvEmailPay);
ownerPropType = (TextView) findViewById(R.id.tvPropTypePay);
ownerLocation = (TextView) findViewById(R.id.tvLocPay);
ownerAccountNo = (TextView) findViewById(R.id.tvLandAccountNoPay);
renterAccountNo = (TextView) findViewById(R.id.tvRenterAccountNoPay);
final RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.relativeLauPropertyPay);
btnConfirm.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
confirmFlag = 1;
progressDialog = ProgressDialog.show(PayRent.this, "Please Wait...", "Property Details Loading..");
String propIdStr = propId.getText().toString();
if (!propIdStr.equals(""))
{
final ParseQuery<ParseObject> query = ParseQuery.getQuery("PostAdd");
query.whereEqualTo("objectId", propIdStr);
query.getFirstInBackground(new GetCallback<ParseObject>()
{
#Override
public void done(ParseObject object, ParseException e)
{
if (e == null)//-----from Post Add Table--------------
{
email = object.getString("PostEmail");
bhk = object.getInt("BHK");
proType = object.getString("PropType");
location = object.getString("Location");
rent = object.getInt("ERent");
maintenance = object.getInt("Emaintainance");
//-------------from User Table-------
ParseQuery query = ParseUser.getQuery();
query.whereEqualTo("email", email);
query.getFirstInBackground(new GetCallback()
{
#Override
public void done(ParseObject object, ParseException e)
{
String interest = object.getString("PaymentInterest");
if (interest.equals("Interested"))
{
payInterestFlag = 0;
fname = object.getString("FirstName");
lname = object.getString("LastName");
ownerAccount = object.getString("AccountNo");
renterAccount = ParseUser.getCurrentUser().getString("AccountNo");
ownerName.setText(fname + " " + lname);
ownerAccountNo.setText(ownerAccount);
renterAccountNo.setText(renterAccount);
ownerEmail.setText(email);
ownerLocation.setText(location);
ownerPropType.setText(bhk + " " + "BHK " + proType);
progressDialog.dismiss();
} else
{
progressDialog.dismiss();
payInterestFlag = 1;
AlertDialog.Builder alertPayInterest = new AlertDialog.Builder(PayRent.this);
alertPayInterest.setTitle("Not Interested!");
alertPayInterest.setIcon(R.drawable.notonline);
alertPayInterest.setMessage("Ohhh!!!\nSelected Add Owner Not Interested In Online Payment");
alertPayInterest.show();
}
}
});
} else
{
progressDialog.dismiss();
propId.setError("Property Id is Not Valid!!!");
}
}
});
}//if
else {
progressDialog.dismiss();
propId.setError("Property Id Blank");
}
}
});
//----------------------------------------------------------------------
btnpayRent.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Toast.makeText(getApplicationContext(), "Click Rent", Toast.LENGTH_SHORT).show();
if ((!propId.getText().toString().equals("")) && (confirmFlag == 1))
{
LayoutInflater factory = LayoutInflater.from(PayRent.this);
final View textEntryView = factory.inflate(R.layout.custom_dialogue_payrent, null);
final EditText inputRent = (EditText) textEntryView.findViewById(R.id.edtRentCustom);
inputRent.setEnabled(false);
final EditText inputMain = (EditText) textEntryView.findViewById(R.id.edtMainCustom);
inputMain.setEnabled(false);
ImageView imgRent = (ImageView) textEntryView.findViewById(R.id.edtImgRentPay);
ImageView imgMain = (ImageView) textEntryView.findViewById(R.id.edtImgMainPay);
// Toast.makeText(getApplicationContext(),"rent is "+rent,Toast.LENGTH_SHORT).show();
inputRent.setText("" + rent);
inputMain.setText("" + maintenance);
imgRent.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
inputRent.setEnabled(true);
//inputRent.requestFocus();
}
});
imgMain.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
inputMain.setEnabled(true);
}
});
final AlertDialog.Builder alert = new AlertDialog.Builder(PayRent.this);
alert.setIcon(R.drawable.donation);
alert.setTitle("Payment Details");
alert.setView(textEntryView);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int whichButton)
{
//-------------Positive Button
rentFinal = Integer.parseInt(inputRent.getText().toString());
mainFinal = Integer.parseInt(inputMain.getText().toString());
totalFinal = rentFinal + mainFinal;
//--transaction table-------
ParseObject objTrans = new ParseObject("Transactions");
objTrans.put("Debtor", renterAccount);//renter
objTrans.put("Creditor", ownerAccount);//owner
objTrans.put("TotalAmt", totalFinal);
objTrans.saveInBackground();
//--------------------------------
final ParseQuery<ParseObject> querypradip = ParseQuery.getQuery("Pay");
querypradip.whereEqualTo("AccountNo", ownerAccount);
querypradip.getFirstInBackground(new GetCallback<ParseObject>() {
public void done(ParseObject object, ParseException e) {
if (object == null) {
Log.d("score", "The getFirst request failed."+e.getMessage());
} else {
Log.d("score", "Retrieved the object.");
ownerObjId=object.getObjectId();
ownerAvlBal=object.getString("AvailableBal");
Log.d("Oid", ownerObjId);
Log.d("OBal", ownerAvlBal);
Toast.makeText(getApplicationContext(), "ownerId"+ownerObjId+"\nAval Bal"+ownerAvlBal, Toast.LENGTH_LONG).show();
//--------------------UPDATE--------------
ParseQuery query = new ParseQuery("Pay");
query.getInBackground(ownerObjId, new GetCallback()
{
public void done(final ParseObject object, ParseException e)
{
if (e == null)
{
object.put("Bal", 5000);
object.saveInBackground();
Toast.makeText(getApplicationContext(), "After Save In Back", Toast.LENGTH_LONG).show();
object.saveInBackground(new SaveCallback()
{
public void done(ParseException e)
{
object.put("AvailableBal", 7000);
object.saveInBackground();
}
});
}
else
{
e.printStackTrace();
Log.e("In Update",e.getMessage());
}
}
});
}
}
});
//---reter table---------------
ParseQuery<ParseObject> queryPay = new ParseQuery<ParseObject>("Pay");
queryPay.whereEqualTo("AccountNo", renterAccount);
queryPay.getFirstInBackground(new GetCallback<ParseObject>() {
#Override
public void done(ParseObject object, ParseException e) {
String AvailBal = object.getString("AvailableBal");
String renterID = object.getObjectId();
final int remainsBal = Integer.parseInt(AvailBal) - totalFinal;
Log.e("Renter", "************" + remainsBal);
Log.e("RenterID", "************" + renterID);
//----------------Update------------------
ParseQuery queryUpdatePay = new ParseQuery("Pay");
queryUpdatePay.getInBackground(renterID, new GetCallback() {
#Override
public void done(ParseObject Obj, ParseException e) {
if (e == null) {
Obj.put("AvailableBal", "" + remainsBal);
Log.e("Update", "************" + remainsBal);
Obj.saveInBackground();
} else {
// do something with the error...
}
}
});
}//done
});
}
});//Ok
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
}
}
);
alert.show();
} else
if (propId.getText().toString().equals(""))
{
propId.setError("Property Id Blank!");
}
if (confirmFlag == 0)
{
Toast.makeText(getApplicationContext(), "Please Confirm Property Id before Pay", Toast.LENGTH_SHORT).show();
}
}
});
}//OnCreate
}
I am able to store(Simply put using object) data in Pay table as well as also get from table but when I am trying to update it doesn't show any change in table..........
same I am applying for Current User(renter data) it done all get data,update but except current user others users data not update
I do not want to try and understand such a large block of code. In the future please try and boil down the relevant pieces. However:
Looks like you do a query right after saving. Note that saveInBackground() is async, thus it starts (as the name suggests) to contact parse.com and save in a background thread. If the query depend on the object being saved, then you need to wait for it to complete by adding the SaveCallback parameter saveInBackground(new SaveCallback)
If it is because the update fails, then again implement the SaveCallback to see what Exception is thrown saveInBackground(new SaveCallback)
You should never be able to update any other User objects than your own. That would be a huge security issue. A work around could be to create a cloud function using useMasterKey() and call that function from your app.