Retrieve the parseUser through a pointer with Java - java

I am trying to display an user who posted something to the app, I have been able to retrieve the Content of the post but not the user. However the User is being saved because in my IOS version I can Clearly see the Posts I have made to test the App out. I need to display the user however the user Pointer<_user>does not save as a string.
How would I get the username behind the pointer?
IOS Version:
var findUser:PFQuery = PFUser.query()
findUser.whereKey("objectId", equalTo: posts.objectForKey("user").objectId)
Posts Class:
#ParseClassName("Posts")
public class Posts extends ParseObject {
public ParseUser getUser() {
return getParseUser("user");
}
public void setUser(ParseUser value) {
put("user", value);
}
public String getContent(){
return getString("content");
}
public void setContent(String content){
put("content", content);
}
#Override
public String toString(){
return getString("user") + "\n" + getString("content");
}
}
List Activity:
List<Posts> posts = new ArrayList<Posts>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.parse_list);
ParseQuery<Posts> query = new ParseQuery<Posts>("Posts");
query.orderByDescending("createdAt");
query.findInBackground(new FindCallback<Posts>() {
#Override
public void done(List<Posts> list, ParseException e) {
if (e != null) {
Toast.makeText(ParseListActivity.this, "Error " + e, Toast.LENGTH_SHORT).show();
}
for (Posts post : list) {
Posts newPost = new Posts();
newPost.setUser(post.getUser());
newPost.setContent(post.getContent());
posts.add(newPost);
}
ArrayAdapter<Posts> adapter = new ArrayAdapter<Posts>(ParseListActivity.this, android.R.layout.simple_list_item_1, posts);
setListAdapter(adapter);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.my, menu);
return true;
}
/*
* Creating posts and refreshing the list will be controlled from the Action
* Bar.
*/
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_refresh: {
updatePostList();
break;
}
case R.id.action_new: {
newPost();
break;
}
}
return super.onOptionsItemSelected(item);
}
private void newPost() {
Intent i = new Intent(this, newPost.class);
startActivityForResult(i, 0);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
// If a new post has been added, update
// the list of posts
updatePostList();
}
}
private void updatePostList() {
ParseQuery<Posts> query = new ParseQuery<Posts>("Posts");
query.orderByDescending("createdAt");
query.findInBackground(new FindCallback<Posts>() {
#Override
public void done(List<Posts> list, ParseException e) {
if (e != null) {
Toast.makeText(ParseListActivity.this, "Error " + e, Toast.LENGTH_SHORT).show();
}
for (Posts post : list) {
Posts newPost = new Posts();
newPost.setContent(post.getContent());
posts.add(newPost);
}
ArrayAdapter<Posts> adapter = new ArrayAdapter<Posts>(ParseListActivity.this, android.R.layout.simple_list_item_1, posts);
setListAdapter(adapter);
}
});
}
}

Related

How do i add another In-App Item with a different Coin Value?

billingClient = BillingClient.newBuilder(this)
.enablePendingPurchases()
.setListener(new PurchasesUpdatedListener() {
#Override
public void onPurchasesUpdated(#NonNull BillingResult billingResult, #Nullable List<Purchase> list) {
if(billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK && list != null){
for(Purchase purchase: list) {
if (purchase.getPurchaseState() == Purchase.PurchaseState.PURCHASED &&
!purchase.isAcknowledged()) {
//test
try {
coinsHandler.addCoins(150, coinsTextView);
} catch (IOException e) {
System.err.println("Could not add coins from bonus !!!!");
}
verifyPurchase(purchase);
}
}
}
}
}).build();
connectToGooglePlayBilling();
I´m not sure where to put the added Coins, this place works fine, but i dont know how to implement more Items with different values.
private void connectToGooglePlayBilling(){
billingClient.startConnection(
new BillingClientStateListener() {
#Override
public void onBillingServiceDisconnected() {
connectToGooglePlayBilling();
}
#Override
public void onBillingSetupFinished(#NonNull BillingResult billingResult) {
if(billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK){
getProductDetails();
}
}
}
);
}
private void verifyPurchase(Purchase purchase) {
String requestUrl = "https://xxxxxxx?" +
"purchaseToken=" + purchase.getPurchaseToken() + "&" +
"purchaseTime" + purchase.getPurchaseTime()+ "&" +
"orderId" + purchase.getOrderId();
Activity activity = this;
StringRequest stringRequest = new StringRequest(
Request.Method.POST,
requestUrl,
new com.android.volley.Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject purchaseInfoFromServer = new JSONObject(response);
if(purchaseInfoFromServer.getBoolean("isValid")) {
ConsumeParams consumeParams = ConsumeParams.newBuilder().setPurchaseToken(purchase.getPurchaseToken()).build();
billingClient.consumeAsync(
consumeParams,
new ConsumeResponseListener() {
#Override
public void onConsumeResponse(#NonNull BillingResult billingResult, #NonNull String s) {
if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) {
Toast.makeText(activity, "Consumed!", Toast.LENGTH_LONG).show();
}
}
}
);
}
} catch (Exception err) {
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
Volley.newRequestQueue(this).add(stringRequest);
}
here some more code
private void getProductDetails(){
List<String> productIds = new ArrayList<>();
productIds.add("itemone");
//item2 test
productIds.add("itemtwo");
SkuDetailsParams getProductDetailsQuery = SkuDetailsParams
.newBuilder()
.setSkusList(productIds)
.setType(BillingClient.SkuType.INAPP)
.build();
Activity activity = this;
billingClient.querySkuDetailsAsync(
getProductDetailsQuery,
new SkuDetailsResponseListener() {
#Override
public void onSkuDetailsResponse(#NonNull BillingResult billingResult, #Nullable List<SkuDetails> list) {
if(billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK &&
list != null){
TextView itemNameTextView = findViewById(R.id.itemName);
Button itemPriceButton = findViewById(R.id.itemPrice);
SkuDetails itemInfo = list.get(0);
//item2 test
TextView itemName2TextView = findViewById(R.id.itemName2);
Button itemPrice2Button = findViewById(R.id.itemPrice2);
SkuDetails itemInfo2 = list.get(1);
itemNameTextView.setText(itemInfo.getTitle());
itemPriceButton.setText(itemInfo.getPrice());
//item2 test
itemName2TextView.setText(itemInfo2.getTitle());
itemPrice2Button.setText(itemInfo2.getPrice());
itemPriceButton.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view) {
billingClient.launchBillingFlow(
activity,
BillingFlowParams.newBuilder().setSkuDetails(itemInfo).build()
);
}
}
);
//item2 test
itemPrice2Button.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view) {
billingClient.launchBillingFlow(
activity,
BillingFlowParams.newBuilder().setSkuDetails(itemInfo2).build()
);
}
});
}
}
}
);
}
here i got the two different buy buttons working, with different prices and Ingame Items, but i dont know how to give the right item on the right button.

How to insert Scanned data in FireBase Realtime DataBase from QR/Barcode?

This is my code it is working fine it scans Qr/Barcode, but I want scanned data to insert in fire-base database. This app is connected with fire-base and using ML kit for barcode scanning. This app also has login signup connected with fire-base auth and scanner app. but I don't know how to push scanned data in fire-base realtime database in android studio.
public class MainActivity extends AppCompatActivity {
View view;
CameraView camera_view;
boolean isDetected= false;
Button btn_start_again;
private static final String TAG = "MainActivity";
FirebaseVisionBarcodeDetectorOptions options;
FirebaseVisionBarcodeDetector detector;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FirebaseVisionBarcodeDetector detector = FirebaseVision.getInstance()
.getVisionBarcodeDetector();
Dexter.withActivity(this)
.withPermissions(new String[]{Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO})
.withListener(new MultiplePermissionsListener() {
#Override
public void onPermissionsChecked(MultiplePermissionsReport report) {
setupCamera();
}
#Override
public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {
}
}).check();
}
public void logout(View view) {
FirebaseAuth.getInstance().signOut();//logout
startActivity(new Intent(getApplicationContext(),login.class));
finish();
}
private void setupCamera()
{
btn_start_again= (Button)findViewById(R.id.btn_again);
btn_start_again.setEnabled(isDetected);
btn_start_again.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
isDetected = !isDetected;
}
});
camera_view = (CameraView)findViewById(R.id.cameraView);
camera_view.setLifecycleOwner(this);
camera_view.addFrameProcessor(new FrameProcessor() {
#Override
public void process(#NonNull Frame frame)
{
processImage(getVisionImageFromFrame(frame));
}
});
options = new FirebaseVisionBarcodeDetectorOptions.Builder()
.setBarcodeFormats(FirebaseVisionBarcode.FORMAT_QR_CODE)
.build();
detector = FirebaseVision.getInstance().getVisionBarcodeDetector(options);
}
private void processImage(FirebaseVisionImage image){
if(!isDetected)
{
detector.detectInImage(image)
.addOnSuccessListener(new OnSuccessListener<List<FirebaseVisionBarcode>>() {
#Override
public void onSuccess(List<FirebaseVisionBarcode> firebaseVisionBarcodes) {
processResult(firebaseVisionBarcodes);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, ""+e.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}
}
private void processResult(List<FirebaseVisionBarcode> firebaseVisionBarcodes){
if (firebaseVisionBarcodes.size()>0)
{
isDetected = true;
btn_start_again.setEnabled(isDetected);
for(FirebaseVisionBarcode item: firebaseVisionBarcodes)
{
int value_type = item.getValueType();
switch (value_type)
{
case FirebaseVisionBarcode.TYPE_TEXT:
{
createDialog(item.getRawValue());
}
break;
case FirebaseVisionBarcode.TYPE_URL:
{
//start browser intent
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(item.getRawValue()));
startActivity(intent);
}
break;
case FirebaseVisionBarcode.TYPE_CONTACT_INFO:
{
String info = new StringBuilder("Name: ")
.append(item.getContactInfo().getName().getFormattedName())
.append("\n")
.append("Address: ")
.append(item.getContactInfo().getAddresses().get(0).getAddressLines())
.append("\n")
.append("Email: ")
.append(item.getContactInfo().getEmails().get(0).getAddress())
.toString();
createDialog(info);
}
break;
default:
break;
}
}
}
}
private void createDialog(String text)
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(text)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
private FirebaseVisionImage getVisionImageFromFrame(Frame frame){
byte[] data= frame.getData();
FirebaseVisionImageMetadata metadata = new FirebaseVisionImageMetadata.Builder()
.setFormat(FirebaseVisionImageMetadata.IMAGE_FORMAT_NV21)
.setHeight(frame.getSize() .getHeight())
.setWidth(frame.getSize() .getWidth())
//.setRotation(frame.getRotation())
.build();
return FirebaseVisionImage.fromByteArray(data,metadata);
}
}

Room LiveData onChange called too fast. Many Activities stacked atop

#Dao
public interface LibraryCoverContentDao {
#Query("SELECT * FROM LibraryCoverContent where rush_id = :rush_id")
LiveData<List<LibraryCoverContent>> getContentsFromRushID(String rush_id);
#Query("DELETE FROM library_cover where rush_id = :rush_id")
void deleteContentsFromRushID(String rush_id);
#Insert(onConflict = REPLACE)
void insertCoverContents(LibraryCoverContent... contents);
}
I want to open another activity once a list LiveData> mLibraryCoverContents is not null.
I am inserting the items downloaded from a retrofit call one by one into the room database, so apparently, my startActivity() call for the next activity happens many a times and multiple-same activities are opened over this activity.
I want only a single activity on top by calling onChanged only after all items of the retrofit call are inserted into db.
Please see the following related code for reference:
public void openReadRushScreen(final int index) {
int count = mCoversList.size();
if(count > index){
mRushIDContent = mLibraryContentRepository.getContentsFromID(mCoversList.get(index).getRush_id());
mRushIDContent.observe(this, new Observer<List<LibraryCoverContent>>() {
#Override
public void onChanged(#Nullable List<LibraryCoverContent> libraryCoverContents) {
Toast.makeText(getActivity(), "ON CHANGED", Toast.LENGTH_SHORT).show();
if(libraryCoverContents!=null && libraryCoverContents.size()>0){
mRushIDContentsList = libraryCoverContents;
if(mRushIDContentsList.size()>0 && mRushIDContentsList.get(0).getRush_id().equals(mCoversList.get(index).getRush_id())){
mRushIDContentsList = new ArrayList<>();
startActivity(ReadRushActivity.getStartIntent(getActivity(), mCoversList.get(index).getRush_id(),
mCoversList.get(index).isRush_audio(),
mCoversList.get(index).getTitle()));
}
}
else {
if(mCoversList!=null && mCoversList.size()>index) getContent(mCoversList.get(index).getRush_id());
}
}
});
}
else Toast.makeText(getActivity(), "Empty Cover", Toast.LENGTH_SHORT).show();
}
public void getContent(String mRushId) {
mApiService = ApiClient.getClient().create(ApiInterface.class);
Call<List<Content>> call = mApiService.getRushContent(mRushId);
if(call!=null){
call.enqueue(new Callback<List<Content>>() {
#Override
public void onResponse(#NonNull Call<List<Content>> call, #NonNull Response<List<Content>> response) {
mContents = response.body();
if(mContents!=null && mContents.size()>0){
//noinspection ConstantConditions
List<LibraryCoverContent> coverContent = new ArrayList<>();
for(int i=0; i<mContents.size(); i++){
coverContent.add(new LibraryCoverContent
(mContents.get(i).getContent_id(), mContents.get(i).getRush_id(),
mContents.get(i).getContent(), mContents.get(i).getAttr(),
mContents.get(i).getDatetime(), mContents.get(i).getPage_no()));
}
mLibraryContentRepository.insertContentItems(coverContent);
}
}
#Override
public void onFailure(#NonNull Call<List<Content>> call, #NonNull Throwable t) {
// if(getActivity()!=null) Toast.makeText(getActivity(), "Network Error while downloading rush content", Toast.LENGTH_LONG).show();
}
});
}
}
#SuppressLint("StaticFieldLeak")
public void insertContentItems(final List<LibraryCoverContent> items) {
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... voids) {
for(int i=0; i<items.size(); i++){
mLibraryCoverContentDao.insertCoverContents(items.get(i));
}
return null;
}
}.execute();
}

Correct code location to check Firebase if a user has been created already?

I've created a method to take a users facebook data, after they login, and create a "user" for them on my firebase database. this method, addUser(), also creates and sets the variables for said user. But I have to leave the method in, login, so it creates my variables, then comment the method out for future testing, or it will reset all the values.
So where can I add "addUser()" to create said user the first time, and make sure it never call it again, as long as the user already exists?
The MainActivity (start and login)
public class MainActivity extends AppCompatActivity {
CallbackManager callbackManager;
ShareDialog shareDialog;
LoginButton login;
ProfilePictureView profile;
Dialog details_dialog;
TextView details_txt;
JSONObject response;
/* Used to track user logging in/out off Facebook */
private AccessTokenTracker mFacebookAccessTokenTracker;
/* A reference to the Firebase */
private Firebase mFirebaseRef;
/* A reference to the Firebase */
private Firebase userRef;
/* Data from the authenticated user */
public static AuthData mAuthData;
/* Listener for Firebase session changes */
private Firebase.AuthStateListener mAuthStateListener;
public static String uName = null;
public static String uEmail = null;
public static String uUrl = null;
public static int mTokens = 50;
public static String uID = null;
public static int getLiveTokens() {
return liveTokens;
}
public static void setLiveTokens(int liveTokens) {
MainActivity.liveTokens = liveTokens;
}
public static int liveTokens = 0;
public static int getLiveSpins() {
return liveSpins;
}
public static void setLiveSpins(int liveSpins) {
MainActivity.liveSpins = liveSpins;
}
public static int liveSpins = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mFirebaseRef = new Firebase("https://<url>.firebaseio.com/");
callbackManager = CallbackManager.Factory.create();
login = (LoginButton) findViewById(R.id.login_button);
profile = (ProfilePictureView) findViewById(R.id.picture);
shareDialog = new ShareDialog(this);
login.setReadPermissions("public_profile email");
details_dialog = new Dialog(this);
details_dialog.setContentView(R.layout.dialog_details);
details_dialog.setTitle("Details");
details_txt = (TextView) details_dialog.findViewById(R.id.details);
getLoginDetails(login);
mFacebookAccessTokenTracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken currentAccessToken) {
//Log.i(Tag, "Facebook.AccessTokenTracker.OnCurrentAccessTokenChanged");
// Toast.makeText(getApplicationContext(), "FBAccessTokenChange", Toast.LENGTH_LONG).show();
MainActivity.this.onFacebookAccessTokenChange(currentAccessToken);
}
};
if (AccessToken.getCurrentAccessToken() != null) {
RequestData();
getLoginDetails(login);
getUserInfo();
Toast.makeText(getApplicationContext(), "Already Logged In", Toast.LENGTH_LONG).show();
}
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (AccessToken.getCurrentAccessToken() != null) {
profile.setProfileId(null);
}
}
});
mAuthStateListener = new Firebase.AuthStateListener() {
#Override
public void onAuthStateChanged(AuthData authData) {
// mAuthProgressDialog.hide();
setAuthenticatedUser(authData);
}
};
/* Check if the user is authenticated with Firebase already. If this is the case we can set the authenticated
* user and hide hide any login buttons */
mFirebaseRef.addAuthStateListener(mAuthStateListener);
}
public void addUser() {
this.uID = mAuthData.getUid();
Toast.makeText(getApplicationContext(), "Setting Up User Account", Toast.LENGTH_LONG).show();
Firebase rootRef = new Firebase("https://<url>.firebaseio.com/users/");
Firebase userRef = rootRef.child(mAuthData.getUid() + "/");
userRef.child("name").setValue(mAuthData.getProviderData().get("displayName"));
userRef.child("provider").setValue(mAuthData.getProvider());
userRef.child("email").setValue(mAuthData.getProviderData().get("email"));
userRef.child("tokens").setValue("100");
userRef.child("spins").setValue("100");
userRef.child("totalspins").setValue("0");
userRef.child("topwin").setValue("0");
}
protected void getLoginDetails(LoginButton login){
login.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult login_Result) {
getUserInfo();
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException exception) {
}
});
}
// LoginResult login_result
protected void getUserInfo() {
// LoginResult login_result.getAccessToken()
GraphRequest data_request = GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject json_object, GraphResponse response) {
Intent intent = new Intent(MainActivity.this, HomeActivity.class);
intent.putExtra("jsondata", json_object.toString());
intent.putExtra("Uid", uID);
startActivity(intent);
}
});
Bundle permission_param = new Bundle();
permission_param.putString("fields", "id,name,email,picture.width(120).height(120)");
data_request.setParameters(permission_param);
data_request.executeAsync();
}
public void RequestData() {
GraphRequest request = GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
JSONObject json = response.getJSONObject();
try {
if (json != null) {
String text = "<b>Name :</b> " + json.getString("name") + "<br><br><b>Email :</b> " + json.getString("email") + "<br><br><b>Profile link :</b> " + json.getString("link");
details_txt.setText(Html.fromHtml(text));
profile.setProfileId(json.getString("id"));
uName = json.getString("name");
uEmail = json.getString("email");
uUrl = json.getString("id");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,link,email,picture");
request.setParameters(parameters);
request.executeAsync();
}
/**
* This method will attempt to authenticate a user to firebase given an oauth_token (and other
* necessary parameters depending on the provider)
*/
private void authWithFirebase(final String provider, Map<String, String> options) {
if (options.containsKey("error")) {
showErrorDialog(options.get("error"));
} else {
//mAuthProgressDialog.show();
// if the provider is not twitter, we just need to pass in the oauth_token
mFirebaseRef.authWithOAuthToken(provider, options.get("oauth_token"), new AuthResultHandler(provider));
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
private void setAuthenticatedUser(AuthData authData) {
if (authData != null) {
/* show a provider specific status text */
String name = null;
if (authData.getProvider().equals("facebook")) {
name = (String) authData.getProviderData().get("displayName");
} else if (authData.getProvider().equals("anonymous")
|| authData.getProvider().equals("password")) {
name = authData.getUid();
} else {
Toast.makeText(getApplicationContext(), "invalid provider", Toast.LENGTH_LONG).show();
}
if (name != null) {
//success
// Toast.makeText(getApplicationContext(), "Log " + name + " (" + authData.getProvider() + ")", Toast.LENGTH_LONG).show();
}
} else {
}
// Firebase Authenticated
this.mAuthData = authData;
MainActivity.uID = mAuthData.getUid();
//addUser();
/* invalidate options menu to hide/show the logout button */
supportInvalidateOptionsMenu();
}
/**
* Show errors to users
*/
private void showErrorDialog(String message) {
new AlertDialog.Builder(this)
.setTitle("Error")
.setMessage(message)
.setPositiveButton(android.R.string.ok, null)
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
private class AuthResultHandler implements Firebase.AuthResultHandler {
private final String provider;
public AuthResultHandler(String provider) {
this.provider = provider;
}
#Override
public void onAuthenticated(AuthData authData) {
// mAuthProgressDialog.hide();
// Toast.makeText(getApplicationContext(), "Auth Success", Toast.LENGTH_LONG).show();
// Toast.makeText(getApplicationContext(), authData.getUid(), Toast.LENGTH_LONG).show();
// createUser();
setAuthenticatedUser(authData);
String mEmail = authData.getUid();
// uID = authData.getUid();
String mProvide = mAuthData.getProvider();
}
#Override
public void onAuthenticationError(FirebaseError firebaseError) {
//mAuthProgressDialog.hide();
showErrorDialog(firebaseError.toString());
}
}
public void createUser(){
Firebase rootRef = new Firebase("https://<url>.firebaseio.com/");
Firebase userRef = rootRef.child("users").child(mAuthData.getUid());
userRef.child("provider").setValue(mAuthData.getProvider());
userRef.child("provider").setValue(mAuthData.getProviderData().get("displayName)"));
rootRef.createUser(mAuthData.getProviderData().get("email").toString(), mAuthData.getProviderData().get("id").toString(), new Firebase.ValueResultHandler<Map<String, Object>>() {
#Override
public void onSuccess(Map<String, Object> result){
Toast.makeText(getApplicationContext(), "Yes-UID=" + result.get("Uid") , Toast.LENGTH_LONG).show();
}
#Override
public void onError(FirebaseError firebaseError){
Toast.makeText(getApplicationContext(), "Not Created", Toast.LENGTH_LONG).show();
}
});
}
private void logout() {
if (this.mAuthData != null) {
/* logout of Firebase */
mFirebaseRef.unauth();
/* Logout of any of the Frameworks. This step is optional, but ensures the user is not logged into
* Facebook/Google+ after logging out of Firebase. */
if (this.mAuthData.getProvider().equals("facebook")) {
/* Logout from Facebook */
LoginManager.getInstance().logOut();
}
/* Update authenticated user and show login buttons */
setAuthenticatedUser(null);
}
}
#Override
protected void onResume() {
super.onResume();
AppEventsLogger.activateApp(this);
}
#Override
protected void onPause() {
super.onPause();
AppEventsLogger.deactivateApp(this);
}
/* ************************************
* FACEBOOK *
**************************************
*/
private void onFacebookAccessTokenChange(AccessToken token) {
if (token != null) {
//mAuthProgressDialog.show();
mFirebaseRef.authWithOAuthToken("facebook", token.getToken(), new AuthResultHandler("facebook"));
} else {
// Logged out of Facebook and currently authenticated with Firebase using Facebook, so do a logout
if (this.mAuthData != null && this.mAuthData.getProvider().equals("facebook")) {
mFirebaseRef.unauth();
setAuthenticatedUser(null);
}
}
}
public static int getmTokens() {
return getLiveTokens();
}
public static void setmTokens(int mTokens) {
MainActivity.mTokens = mTokens;
}
public static void takemTokens(int mTokens) {
MainActivity.mTokens -= mTokens;
}
public static void givemTokens(final int ttokens) {
//MainActivity.mTokens += tokens;
// TODO
// if (ttokens > MainActivity.getmTopWin()){
// MainActivity.setmTopWin(ttokens);
//}
Firebase ref = new Firebase("https://<url>.firebaseio.com/users/" + MainActivity.uID + "/");
final Firebase tokensRef = ref.child("tokens");
tokensRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
int iii = new Integer(dataSnapshot.getValue().toString());
iii += ttokens;
tokensRef.setValue(iii);
setLiveTokens(iii);
checkmTopWin(ttokens);
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
//tokensRef.removeEventListener(MainActivity);
}
public static int mSpins = 30;
public static int getmSpins() {
return getLiveSpins();
}
public static void setmSpins(int mspins) {
MainActivity.mSpins = mspins;
}
public static void takemSpins(final int mspins) {
Firebase ref = new Firebase("https://<url>.firebaseio.com/users/" + MainActivity.uID + "/");
final Firebase tokensRef = ref.child("spins");
tokensRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
int i = Integer.valueOf(dataSnapshot.getValue().toString());
i -= mspins;
tokensRef.setValue(i);
setLiveSpins(i);
}
#Override
public void onCancelled(FirebaseError firebaseError) {}
});
}
public static void givemSpins(final int mspins){
Firebase ref = new Firebase("https://<url>.firebaseio.com/users/" + MainActivity.uID + "/");
final Firebase tokensRef = ref.child("spins");
tokensRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
int i = Integer.valueOf(dataSnapshot.getValue().toString());
i += mspins;
tokensRef.setValue(i);
}
#Override
public void onCancelled(FirebaseError firebaseError) {}
});
}
public static int slotVari = 0;
public static int getSlotVari() {
return slotVari;
}
public static void setSlotVari(int slotVari) {
MainActivity.slotVari = slotVari;
}
public static int mTotalSpins;
public static int getmTotalSpins() {
return mTotalSpins;
}
public static void setmTotalSpins(int mTotalSpins) {
MainActivity.mTotalSpins = mTotalSpins;
}
public static void incmTotalSpins(){
Firebase ref = new Firebase("https://<url>.firebaseio.com/users/" + MainActivity.uID + "/");
final Firebase tokensRef = ref.child("totalspins");
tokensRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
int i = Integer.valueOf(dataSnapshot.getValue().toString());
i++;
tokensRef.setValue(i);
}
#Override
public void onCancelled(FirebaseError firebaseError) {}
});
MainActivity.mTotalSpins++;
}
public static int mTopWin;
public static int getmTopWin() {
return mTopWin;
}
public static void setmTopWin(int mTopWin) {
Firebase ref = new Firebase("https://<url>.firebaseio.com/users/" + MainActivity.uID + "/");
Firebase tokensRef = ref.child("topwin");
tokensRef.setValue(mTopWin);
MainActivity.mTopWin = mTopWin;
}
public static void checkmTopWin(final int mTokensWon) {
Firebase ref = new Firebase("https://<url>.firebaseio.com/users/" + MainActivity.uID + "/");
final Firebase tokensRef = ref.child("topwin");
tokensRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
int i = Integer.valueOf(dataSnapshot.getValue().toString());
if (i < mTokensWon){
tokensRef.setValue(mTokensWon);
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {}
});
}
}
You need to set a preference like FIRST_LAUNCH and check if its true each time your user logs in. First time the application launches, the FIRST_LAUNCH preference won't be found. So call your addUser() function to create a new entry in your FireBase database.
SharedPreferences pref = getSharedPreferences(Constants.ApplicationTag, Activity.MODE_PRIVATE);
if (!pref.contains(Constants.FIRST_LAUNCH)) {
addUser();
pref.edit().putBoolean(Constants.FIRST_LAUNCH, true).commit();
}
So you might be thinking of if an user uninstalls your application and then reinstalls it, the preferences will be gone and the addUser() function will be called again. No problem, you won't get a new Firebase entry as long as the path to the child attribute is the same. The values will be replaced to the specific path (if it does exist), with current information of user.
Now if you want to check if your user already exists in Firebase database you need to add a listener like this. I'm attaching a code sample for better understanding.
Firebase rootRef = new Firebase("https://<url>.firebaseio.com/users/");
Firebase userRef = rootRef.child(mAuthData.getUid() + "/");
userRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
// User exists. Do nothing
} else addUser();
}
#Override
public void onCancelled(FirebaseError firebaseError) {}
});

In app billing(purchase) linking app with items

I'm trying to implment in app puchase/billing in my app so when the user buys the item i remove the ads. I have and example code that is working with SKU = "android.test.purchased". Now my question is how can I link the app to my items - I have uploaded new apk with billing enabled, created and published the item one hour ago, but when I try to buy the item I get this:
here is my code:
public class RemoveAds extends AthanBaseActivity implements OnClickListener {
private static final String TAG = "inappbilling";
IabHelper mHelper;
//ID from playstore 16xxxx15_removeads.
//android.test.purchased
static final String ITEM_SKU = "com.myapppackage.16xxxx15_removeads.";
#Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
setContentView(R.layout.remove_ads);
findViewById( R.id.remove_ads_).setOnClickListener(this);
setupInAppPurchase();
}
public void consumeItem() {
mHelper.queryInventoryAsync(mReceivedInventoryListener);
}
IabHelper.QueryInventoryFinishedListener mReceivedInventoryListener = new IabHelper.QueryInventoryFinishedListener() {
public void onQueryInventoryFinished(IabResult result,
Inventory inventory) {
if (result.isFailure()) {
// Handle failure
} else {
mHelper.consumeAsync(inventory.getPurchase(ITEM_SKU),
mConsumeFinishedListener);
}
}
};
#Override
public void onDestroy() {
super.onDestroy();
if (mHelper != null)
mHelper.dispose();
mHelper = null;
}
IabHelper.OnConsumeFinishedListener mConsumeFinishedListener = new IabHelper.OnConsumeFinishedListener() {
public void onConsumeFinished(Purchase purchase, IabResult result) {
if (result.isSuccess()) {
Toast.makeText(RemoveAds.this, "SUCCESS", Toast.LENGTH_LONG)
.show();
} else {
Toast.makeText(RemoveAds.this, "ERROR purchase",
Toast.LENGTH_LONG).show();
// handle error
}
}
};
IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {
public void onIabPurchaseFinished(IabResult result, Purchase purchase) {
if (result.isFailure()) {
// Handle error
return;
} else if (purchase.getSku().equals(ITEM_SKU)) {
consumeItem();
// buyButton.setEnabled(false);
}
}
};
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (!mHelper.handleActivityResult(requestCode, resultCode, data)) {
super.onActivityResult(requestCode, resultCode, data);
}
}
private void setupInAppPurchase() {
String base64EncodedPublicKey = "MIIBIjANBgkqhkcccxxxxxdomr somelongstringdfsdfsdfsfsdofksdofkdsMXz0R4EJuw7YZkQ8jMPemymSbQGtLllH+fu85hfQIDAQAB";
mHelper = new IabHelper(this, base64EncodedPublicKey);
mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
public void onIabSetupFinished(IabResult result) {
if (!result.isSuccess()) {
Log.d(TAG, "In-app Billing setup failed: " + result);
} else {
Log.d(TAG, "In-app Billing is set up OK");
}
}
});
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.remove_ads_:
mHelper.launchPurchaseFlow(this, ITEM_SKU, 10001,
mPurchaseFinishedListener, "mypurchasetoken");
break;
}
}
}
You cannot make purchases if the primary account on your real android device is same as your developer account.

Categories