Unable to store data into firebase database - android

Help, I cant save my data in firebase realtime database, it keeps my app force close. Please help im new at android.
private void SReport(){
String name = etfulln.getText().toString().trim();
String reason = etreason.getText().toString().trim();
String address = etaddr.getText().toString().trim();
String contact = etcontn.getText().toString().trim();
if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(reason) && !TextUtils.isEmpty(address) && !TextUtils.isEmpty(contact)){
String id = DBReport.push().getKey();
Report report = new Report(id,name,reason,address,contact);
DBReport.child(id).setValue(report);
Toast.makeText(this, "Report added", Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(this, "Fill details", Toast.LENGTH_LONG).show();
}
}

Related

check playerSSign fail

When verifying the signature, the background server displays {"rtnCode":-1,"errMsg":"check playerSSign fail"}
The data provided by the client is
if(huaweiid != null){
PlayersClient player = Games.getPlayersClient(this, huaweiid);
player.getCurrentPlayer().addOnSuccessListener(new OnSuccessListener<Player>() {
#Override
public void onSuccess(Player player) {
String ts = player.getSignTs();
String playerId = player.getPlayerId();
int playerLevel = player.getLevel();
String playerSign = player.getPlayerSign();
//String displayName = player.getDisplayName();
//Uri hiResImageUri = player.getHiResImageUri();
//Uri iconImageUri = player.getIconImageUri();
JSONObject jo = new JSONObject();
try {
jo.put("signTs", ts);
jo.put("playerId", playerId);
jo.put("playerLevel", playerLevel);
jo.put("playerSign", playerSign);
EditText ed = findViewById(R.id.editText);
ed.setText(jo.toString());
Log.i("huawei user info", jo.toString());
} catch (JSONException e) {
e.printStackTrace();
Log.i("huawei user info", Objects.requireNonNull(e.getMessage()));
}
}
});
}
Use the preceding four data items and the following description document:
https://developer.huawei.com/consumer/cn/doc/HMSCore-References-V5/verify-login-signature-0000001050123503-V5
An error always occurs during the verification in the background.
{"rtnCode":-1,"errMsg":"check playerSSign fail"}
appId/cpid is obtained from agconnect-services.json and agconnect-services.json is downloaded from the background.
what’s the reason?
The following table describes the typical setting errors of the input parameters. Please verify the parameter settings.
https://developer.huawei.com/consumer/cn/doc/development/AppGallery-connect-Guides/faq-check-login-0000001050746133-V5

Flutterwave Android payment integration - cannot process payment - error unable to retrieve transaction fee

I'm using Rave for the first time, it looked so flexible and easier to integrate, but along the line. I got stuck with testing, I'm using only card and bank payments methods.
when I choose the card to and enter some test cards from the test card link https://developer.flutterwave.com/reference#test-cards-1
I get 2 errors, => "unable to retrieve transaction fees" but in my logcat I see => " only test cards ree allowed," of which were using the test cards. And am also on staging mode which I assume is correct while testing with test keys.
When I use the bank tab I get some error in JSON toasted, but display later => "parents_limit not defined". Not just that I give this errors, I still found transactions of the bank payment types recorded on my dashboard. This confuses me more since I didn't get the payment success message so I can verify and give value to the customer.
I have integrated everything as per guideline in Rave docs, which calls my make payment. from https://github.com/Flutterwave/rave-android
variable for implementation
//online payment
String[] fullname;
String email = "";
String fName = "";
String lName = "";
String narration = "Payment for Riidit App activation";
String txRef;
String country = "NG";
String currency = "NGN";
private String mUsername, userID, mEmail;
the payment method
private void makePayment(int amount) {
txRef = email + " " + UUID.randomUUID().toString();
try {
fullname = mUsername.split(" ");
fName = fullname[0];
lName = fullname[1];
} catch (NullPointerException ex) {
ex.printStackTrace();
}
/*
Create instance of RavePayManager
*/
new RavePayManager(this).setAmount(amount)
.setCountry(country)
.setCurrency(currency)
.setEmail(email)
.setfName(fName)
.setlName(lName)
.setNarration(narration)
.setPublicKey(RiiditUtilTool.getPublicKey())
.setEncryptionKey(RiiditUtilTool.getEncryptionKey())
.setTxRef(txRef)
.acceptAccountPayments(true)
.acceptCardPayments(true)
.acceptMpesaPayments(false)
.acceptGHMobileMoneyPayments(false)
.onStagingEnv(false)
.allowSaveCardFeature(true)
.withTheme(R.style.DefaultTheme)
.initialize();
}
//called from below
private void payOnline()
{
makePayment(amount);
}
public void onActivateOnlineClick(View v) {
payOnline();
}
// expecting result of payment here either fail or success
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RaveConstants.RAVE_REQUEST_CODE && data != null) {
String message = data.getStringExtra("response");
if (resultCode == RavePayActivity.RESULT_SUCCESS) {
Toast.makeText(this, "SUCCESS " + message, Toast.LENGTH_LONG).show();
// get a PIN and SERIAL no when payment succeeds
getGetPinAndSerialForPaidUser();
} else if (resultCode == RavePayActivity.RESULT_ERROR) {
Toast.makeText(this, "ERROR " + message, Toast.LENGTH_LONG).show();
} else if (resultCode == RavePayActivity.RESULT_CANCELLED) {
Toast.makeText(this, "Payment CANCELLED " + message, Toast.LENGTH_LONG).show();
}
}
}
I want when this event is triggered, it will make the payment to using the value set in the amount and return status in the onActivityResult above where I can check and give value to the user
First of all make sure you are using the api keys which are for testing and if you are on staging mode(testing) then set this to true .onStagingEnv(true) and test after that.

Get image path from an ImageView

I am trying to get the image path string from an imageView.
The imageView is charged using a string path store in SQLite db.
When I modify an item of my Db in some fiels other than image path one, I can't read back the path from imageView to correctly update the db. So the field image path become null after any kind of update.
In code, when I click the save button I call the saveProduct() method:
private void saveProduct() {
// Read from input field
//Use trim to eliminate leading or trailing white space
String nameString = mNameEditText.getText().toString().trim();
String qtyString = mQtyEditText.getText().toString().trim();
String priceString = mPriceEditText.getText().toString().trim();
String mailString = mEmailEditText.getText().toString().trim();
String phoneString = mPhoneEditText.getText().toString().trim();
// Check if this is a new product or an existing one
if (mcurrentProdUri == null &&
TextUtils.isEmpty(nameString) && TextUtils.isEmpty(qtyString)
&& TextUtils.isEmpty(priceString)&& TextUtils.isEmpty(mailString)
&& TextUtils.isEmpty(phoneString)) {
return;
}
//Create a ContentValues object to populate the database
ContentValues values = new ContentValues();
values.put(InventoryContract.ProductEntry.COLUMN_PRODUCT_NAME, nameString);
values.put(InventoryContract.ProductEntry.COLUMN_PRODUCT_QTY, qtyString);
values.put(InventoryContract.ProductEntry.COLUMN_PRODUCT_PRICE, priceString);
values.put(InventoryContract.ProductEntry.COLUMN_EMAIL, mailString);
values.put(InventoryContract.ProductEntry.COLUMN_PHONE, phoneString);
values.put(InventoryContract.ProductEntry.COLUMN_PRODUCT_PIC, picPath);
//Determine if this is a new product or not by checking if mCurrentProdUri is null or not
if (mcurrentProdUri == null) {
Uri newUri = getContentResolver().insert(InventoryContract.ProductEntry.CONTENT_URI, values);
// check if newUri is null or not
if (newUri == null){
//Show an error toast message
Toast.makeText(this, "There has been an error inserting a new product", Toast.LENGTH_SHORT).show();
} else {
//Otherwise show a successful addition message
Toast.makeText(this, "A new product has been added!", Toast.LENGTH_SHORT).show();
}
} else {
//Otherwise if this is an existing product proceed updating it with new data
int rowsAffected = getContentResolver().update(mcurrentProdUri, values, null, null);
if (rowsAffected == 0) {
// If no rows were affected show error toast message
Toast.makeText(this, "There has been an error in updating the product", Toast.LENGTH_SHORT).show();
} else {
// Otherwise the update was successful and we can show the related Toast message
Toast.makeText(this, "The product has been updated!", Toast.LENGTH_SHORT).show();
}
}
}
I already read all related posts, but I really don't know how I can make the method read the imageView to get out the related image path (or Uri)
Many thanks for support
You need to keep track of the uri at the activity/fragment level before you load the imageview as it's not the responsibility of a regular ImageView to remember it's source.
You can, however, build an extended ImageView that is responsible for that if it helps your case:
class MyImageView extends ImageView {
private Uri mImageUri;
public MyImageView(Context context) {
super(context);
}
#Override
public void setImageURI(#Nullable Uri uri) {
super.setImageURI(uri);
mImageUri = uri;
}
public Uri getImageUri(){
return mImageUri;
}
}
If you do go that route, you have to take view state saving into consideration during config changes or you may lose that uri.

Android Studio Login/Register System ideas

I want to make a diet helper app for android devices, using android studio and
I need ideas on what to use to implement the login/register system, I followed a tutorial on youtube but it was outdated and I ended up wasting my time, then I've read on google, that android studio has a library called volley that I can use with PHP and MySql to make the login system.
Do you have other ideas, or is that the best one to go with?
I'm open to suggestions so shoot!
Update:
I've created a post about how to do this using a PHP backend for your Android application. https://keithweaver.ca/posts/4/android-php-custom-login
Additionally to the link above, this is how you can setup a server.
https://github.com/kweaver00/tutorials/blob/master/setup-server.md
https://keithweaver.ca/posts/9/setup-ubuntu-server-quickly
Original Post:
This is one solution and isn't guaranteed to be the best.
You can really use anything to communicate with a server. Async Tasks or Retrofit are both popular.
Assuming you have set up a server with a LAMP stack. Make sure you have an SSL so you don't pass user information that isn't encrypted.
Create a user table in mysql
Ex.
id int default->NULL AI primary-key
user varchar 250 default->null
pass varchar 250 default->null
signupdate date default-> null
Create a log in sessions table of some sort
Ex.
id int default->NULL AI primary-key
user varchar 250 default->null
token varchar 250 default->null
addedDate date default->null
Create a log in php script (I know this probably isnt the best way to right php code)
$connection = mysqli_connect("localhost", "phpmysqluser", "password", "dbname") or die("Error 404: unable to connect");
$username = $_POST['user'];
$pass = $_POST['pass'];
//add code to remove slashes and etc.
$result = mysqli_query($connection, "SELECT * FROM userTable WHERE user='$username' AND pass='$pass'") or die("Error: this line has error");
class response{
public $loggedin =0;
public $message = "";
}
$response = new response();
if(mysqli_num_rows($result) == 1){
$logInToken = generateLogInToken();
//have a function that creates a unique token and stores it for X days or minutes
$response->loggedin = 1;
$response->message = $logInToken;
}else{
$response->message = "wrong info";
}
echo json_decode($response);
This should output a json file like this depending on your user and pass variables.
{
"loggedin" : 1,
"message" : "asdnlansdkansd"
}
Right another script that passes in the log in token and user name to check if it's valid.
$connection .... //same as above
//well it really should be a include_once cause if you change credentials
$token = $_POST['token'];
$user = $_POST['user'];
$registeredDate = "";
$today = date('Y-m-d');
$result = mysqli_query($connection, "SELECT * FROM tokenTable WHERE user='$user' AND token='$token'") or die("Error...");
class response{
public $status = 0;
}
$response = new response();
if(mysqli_num_rows($result) == 1){
//check token has been register today and if not sign them out
while($row = mysqli_fetch_array($result)){
$registeredDate = $row['addedDate'];
}
if($registeredDate == $today){
//token is valid
$response->status = 3;
}else{
//expired
$response->status = 2;
}
}else{
//user and token are not valid
$response->status = 1;
}
echo json_decode($response);
Giving a json object like:
{
"status" : 3
}
In your Android app on open, run the code to check if the account is valid if there is anything stored locally. Or just go to log in screen.
On splash screen in the onCreate (you dont need a splash screen, its actually not recommended but its the easiest way to explain the process):
if(userNameAndTokenStoredInSharedPref()){
String token = getTokenFromSharedPref();
String userName = getUserNameFromSharedPref();
checkAgainstServer(token, userName);
}else{
Intent openLogInWindow = new Intent(this, LogInActivity.class);
startActivity(openLogInWindow);
}
still in the slash activity but out of the oncreate:
protected void checkAgainstServer(String token, String user){
//using retrofit
ThisAppRestClient.get().postCheckTokenAndUser(token, user, new Callback<UserStatusCallBack>() {
#Override
public void success(UserStatusCallBack userStatusCallback, retrofit.client.Response response) {
if(userStatusCallback.getStatus() == 1){
//Invalid token
}else if(userStatusCallback.getStatus() == 2){
//Expired token
}else if(userStatusCallback.getStatus() == 3){
//Success
Intent openMainWindow = new Intent(this, MainActivity.class);
startActivity(openMainWindow);
}
}
#Override
public void failure(RetrofitError error) {
//Retrofit errors like timeouts, etc.
}
}
}
The log in activity would be something like:
logBtn.setOnClickListener(new View.onClick...
String userName = userNameEditText.getText().toString().toLowerCase().trim();
String password = passwordEditText.getText().toString().trim();
if(!TextUtils.isEmpty(userName) && !TextUtils.isEmpty(password)){
callServerLogInScript(userName, password);
}
userNameEditText.setText("");
logBtn.setVisibility(View.GONE);
}
lower down the file:
protected void callServerLogInScript(String user, String pass){
//using retrofit
ThisAppRestClient.get().postCheckTokenAndUser(user, pass, new Callback<LogInCallBack>() {
#Override
public void success(LogInCallBack logInCallback, retrofit.client.Response response) {
if(logInCallback.getLoggedIn() == 1){
//succssful
storeUserNameInSharedPref(user);
storeTokenInSharedPref(logInCallback.getMessage());
Intent openMainActivity = new Intent(this, MainActivity.class);
startActivity(openMainActivity);
}else{
//incorrect log in
logBtn.setVisibility(View.VISIBLE);
}
}
#Override
public void failure(RetrofitError error) {
//Retrofit errors like timeouts, etc.
}
}
}
The reason for not storing the user name and password directly is if the device is rooted they can manipulate the data locally but not on your server.
It depends which you want to use. If you have your own server to host, then use php,mysql. If not, you can also use other third party which provides you to add if you know php,mysql to create.
Another option is if you don't want to use php mysql to store datas, then you can proceed with parse.com
So if you want to use parse.com, just register it. It's free to use.
Hope it will match your requirement, say for eg: if you want to create registration(everything saving in datas will be handled),you need to give exact object name that matches what you given in parse.com
Even you can also create in code itself without object name. I will show you a piece of example how to create and insert for registration..
ParseUser user = new ParseUser();
user.setEmail((txtEmail));//create an edittext and get the values in strings and store..
user.setPassword(txtPassword);//same for password
user.setUsername(txtUsername);//username
user.signUpInBackground(new SignUpCallback() {
public void done(ParseException e) {
if (e == null) {
//completed..it has been registered
Toast.makeText(getApplicationContext(),
"Successfully Signed up, please log in.",
Toast.LENGTH_LONG).show();
finish();
} else {
Toast.makeText(getApplicationContext(),
"Sign up Error", Toast.LENGTH_LONG)
.show();
}
}
});
Simple one if you don't want to use php,mysql. Well documentation and easy to integrate and use it. Happy coding.
FYI: Android studio is IDE for development. And volley is HTTP library that makes networking for Android.

set header on get request android

I try to set a http autentification with android
this is my class
http://pastebin.com/SB9TKtQZ
I use like this
EditText user = (EditText)findViewById(R.id.referent_login_input);
EditText password = (EditText)findViewById(R.id.referent_password_input);
Api login = new Api(getString(R.string.api_url));
login.updateUrl("login");
login.updateHeader(user.getText().toString(), password.getText().toString());
String connect = login.get();
My php is
if( !isset($_SERVER['PHP_AUTH_USER']) && !isset($_SERVER['PHP_AUTH_PW']) ) {
echo "no !!!";
}
else {
echo "yes";
}
and I always have no !!!
I set something in my EditText
Thanks

Categories

Resources