I have a .sql database which I edit using PHPmyadmin and a android app that retrieves the login credentials from the database and tries to login to the app according to the user's credentials. But it keeps showing "Unable to login" error in the app even though I use the correct credentials from the database, which in this case is phoneno and password. The Login_Activity.JAVA is as below. Why is the app not logging in properly?
Login_Activity.java
package com.example.ankit.mrestro.Controller;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import com.baidu.android.pushservice.PushConstants;
import com.baidu.android.pushservice.PushManager;
import com.squareup.otto.Subscribe;
import com.example.ankit.mrestro.Bus.BusProvider;
import com.example.ankit.mrestro.Bus.LoginEvent;
import com.example.ankit.mrestro.Bus.LoginSuccessEvent;
import com.example.ankit.mrestro.Bus.PushRegisterEvent;
import com.example.ankit.mrestro.R;
import com.example.ankit.mrestro.model.LoginResult;
import com.example.ankit.mrestro.services.DataService;
import com.example.ankit.mrestro.services.RESTrepository;
public class LoginActivity extends Activity {
public static final String PREF_ACCOUNT_ID = "cust_id";
public static final String PREF_TOKEN = "accessToken";
public static final String SHARED_PREF_DB_NAME = "loginResult";
private ProgressDialog progressDialog;
public static Intent createIntent(Context c) {
return new Intent(c, LoginActivity.class);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DataService.init();
progressDialog = new ProgressDialog(this);
/**
* Check either we are already logged in
*/
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREF_DB_NAME, 0);
if (sharedPreferences.getString(PREF_TOKEN, "").length() != 0) {
RESTrepository.setToken(sharedPreferences.getString(PREF_TOKEN, ""));
RESTrepository.setUser_id(sharedPreferences.getInt(PREF_ACCOUNT_ID, 0));
goToMainActivity();
}
setContentView(R.layout.activity_login);
PushManager.startWork(getApplicationContext(), PushConstants.LOGIN_TYPE_API_KEY,
"hwfeocSIPlgKTasIuARPREnS");
//SharedPreferences preferences=getSharedPreferences("pushService",0);
//String userId=preferences.getString("user_id","no data");
//Toast.makeText(this,"user id is:"+userId,Toast.LENGTH_SHORT).show();
Button loginButton=(Button)findViewById(R.id.email_sign_in_button);
loginButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v){
String phoneno=((TextView)findViewById(R.id.email)).getText().toString();
String password=((TextView)findViewById(R.id.password)).getText().toString();
// Toast.makeText(getBaseContext(),"login..."+phoneno+"..."+password,Toast.LENGTH_SHORT).show();
progressDialog.show();
BusProvider.get().post(new LoginEvent(phoneno,password));
}
});
}
#Override
protected void onResume(){
super.onResume();
BusProvider.get().register(this);
}
#Override
protected void onPause(){
super.onPause();
BusProvider.get().unregister(this);
}
#Subscribe
public void onLoginSuccessEvent(LoginSuccessEvent loginSuccessEvent){
progressDialog.hide();
LoginResult result=loginSuccessEvent.getResult();
if (result != null) {
// Toast.makeText(this,result.getCust_id()+result.getCust_name()+result.getCust_access_token(),Toast.LENGTH_SHORT).show();
//Toast.makeText(this,"Login Success",Toast.LENGTH_SHORT).show();
SharedPreferences preferences = this.getSharedPreferences(SHARED_PREF_DB_NAME, MODE_PRIVATE);
preferences.edit().putString(PREF_TOKEN,result.getCust_access_token()).commit();
preferences.edit().putInt(PREF_ACCOUNT_ID,result.getCust_id()).commit();
SharedPreferences pushPreferences=this.getSharedPreferences("pushService",0);
BusProvider.get().post(new PushRegisterEvent
(result.getCust_id(),result.getCust_access_token(),pushPreferences.getString("user_id","")));
goToMainActivity();
} else {
Toast.makeText(this, "Unable to login, please retry", Toast.LENGTH_SHORT).show();
}
}
private void goToMainActivity() {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
finish();
}
}
Related
Unfortunately the button I tried to design doesn't work. I have three activities: Login, Register and MainActivity (which is a blank activity) and on the Login activity I have this register button ("button") that I want to redirect to Register activity but it redirects me to a blank page when I run the app. What should I do?
package com.example.scooterzapp;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
public class Register extends AppCompatActivity {
FirebaseAuth fAuth;
EditText etEmail,etParola,etNume,etPrenume,etUsername,etVarsta,etNumarDeTelefon;
Button bReg;
ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
etNume = findViewById(R.id.etNume);
etPrenume = findViewById(R.id.etPrenume);
etUsername = findViewById(R.id.etUsername);
etParola = findViewById(R.id.etParola);
etEmail = findViewById(R.id.etEmail);
etNumarDeTelefon = findViewById(R.id.etNumarDeTelefon);
etVarsta = findViewById(R.id.etVarsta);
bReg= findViewById(R.id.bReg);
fAuth=FirebaseAuth.getInstance();
progressBar=findViewById(R.id.progressBar);
if(fAuth.getCurrentUser()!= null){
startActivity(new Intent(getApplicationContext(),MainActivity.class));
finish();
}
bReg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String Email = etEmail.getText().toString().trim();
String Parola = etParola.getText().toString().trim();
if (TextUtils.isEmpty(Email)) {
etEmail.setError("Campul trebuie completat.");
return;
}
if (TextUtils.isEmpty(Parola)) {
etParola.setError("Campul trebuie completat.");
return;
}
if (Parola.length() < 6) {
etParola.setError("Parola trebuie sa fie formata din cel putin 6 caractere");
return;
}
progressBar.setVisibility(View.VISIBLE);
fAuth.createUserWithEmailAndPassword(Email,Parola).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
Toast.makeText(Register.this, "V-ati inregistrat cu succes!", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(),Login.class));
}else{
Toast.makeText(Register.this, "Inregistrare esuata.", Toast.LENGTH_SHORT).show();
}
}
});
}
});
}
}
Greet from Nice ;) try below code
button.setOnClickListener (new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this,Register.class));
}
});
I have problem, dont know what to do, Goal is to make QR scanner, you enter value then press OK it should store the values in object podaci and to use same values in other activitiy.
But what happens it scans QR code but it doesnt show real value it shows something like this : "com.google.android.gms.vision.barcode.Barcode#ecd6456" and there is no value stored in object podaci in MainActivity.
here is my QR class :
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.SparseArray;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.example.irhad.mytestapplication.data.Podaci;
import com.google.android.gms.common.api.CommonStatusCodes;
import com.google.android.gms.vision.CameraSource;
import com.google.android.gms.vision.Detector;
import com.google.android.gms.vision.barcode.Barcode;
import com.google.android.gms.vision.barcode.BarcodeDetector;
import java.io.IOException;
public class QRActivity extends AppCompatActivity{
SurfaceView camera_preview;
Intent main;
EditText txtUnosUplacenog;
TextView txtQRIspis;
Button btnOK;
private Podaci podaci;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.qr_activity);
camera_preview = findViewById(R.id.camera_preview);
txtUnosUplacenog = findViewById(R.id.txtUnosUplacenog);
btnOK = findViewById(R.id.btnOK);
txtQRIspis = findViewById(R.id.txtQRIspis);
podaci = new Podaci();
createCameraSource();
}
private void createCameraSource() {
BarcodeDetector barcodeDetector = new BarcodeDetector.Builder(this).build();
final CameraSource cameraSource = new CameraSource.Builder(this, barcodeDetector)
.setAutoFocusEnabled(true)
.setRequestedPreviewSize(620, 480)
.build();
camera_preview.getHolder().addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceCreated(SurfaceHolder holder) {
try {
if (ActivityCompat.checkSelfPermission(QRActivity.this,
Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
return;
}
cameraSource.start(camera_preview.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
cameraSource.stop();
}
});//camera_preview
barcodeDetector.setProcessor(new Detector.Processor<Barcode>() {
#Override
public void release() {}
#Override
public void receiveDetections(Detector.Detections<Barcode> detections) {
final SparseArray<Barcode> barcodes = detections.getDetectedItems();
if(barcodes.size() > 0){
podaci.setQrvalue(barcodes.valueAt(0).toString());
podaci.setUplata(Double.parseDouble(txtUnosUplacenog.getText().toString()));
txtQRIspis.setText(podaci.getQrvalue());
}
}
});//barcodeDetector
}//CreateCameraSource
public void btnOK(View view){
if(podaci.getUplata() != 0 && podaci.getQrvalue() != "")
izadji(podaci);
}
public void izadji(Podaci podatak){
main = new Intent(this, MainActivity.class);
main.putExtra("barcode", podatak.getQrvalue() );
main.putExtra("vrijednost", podatak.getUplata() );
startActivity(main);
finish();
}
public void izadji(View view){
main = new Intent(this, MainActivity.class);
startActivity(main);
finish();
}
}
And here is my MainActivity class :
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.BatteryManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.example.irhad.mytestapplication.data.Podaci;
import com.google.android.gms.common.api.CommonStatusCodes;
import com.google.android.gms.vision.barcode.Barcode;
public class MainActivity extends AppCompatActivity {
Button btnSkenirajQR;
Button btnOpcije;
Button btnExit;
TextView txtIspis;
boolean baterija_ispisano = false;
BroadcastReceiver batteryInfo = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
if(level <= 10 && !baterija_ispisano){
Toast.makeText(getApplicationContext(),
"Molim vas napunite bateriju (<10%)",Toast.LENGTH_LONG);
baterija_ispisano = true;
}else if(level >= 11 && baterija_ispisano){
baterija_ispisano = false;
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSkenirajQR = findViewById(R.id.btnSkener);
btnOpcije = findViewById(R.id.btnOpcije);
btnExit = findViewById(R.id.btnExit);
txtIspis = findViewById(R.id.txtIspis);
}
public void open_Skener(View view){
Intent qrskeniranje = new Intent(this, QRActivity.class);
startActivityForResult(qrskeniranje,0);
finish();
}
public void open_Opcije(View view){
Intent opcije = new Intent(this, OpcijeActivity.class);
startActivity(opcije);
finish();
}
public void izadji(View view){
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(0);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(data != null){
String qr = data.getParcelableExtra("barcode");
String value = data.getParcelableExtra("vrijednost");
txtIspis.setText("Barcode vrijednost : " + qr);
} else {
txtIspis.setText("Nije ocitalo");
}
}
}
Ps :And it is changing value while im holding in front of QR code.
#gr54943, #ac45c04 etc...
I am developing a chat app using Firebase Realtime Database. I have been able to send and receive messages properly. Now, I want to implement notification whenever new message is received.i.e whenever any user sends a message a push notification triggers at other user device who have that app just like whatsapp.
My main concern is how to do that part in my given below code?
OnlineActivity.java
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.text.format.DateFormat;
import android.widget.Toast;
import com.firebase.ui.auth.AuthUI;
import com.firebase.ui.database.FirebaseListAdapter;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import hani.momanii.supernova_emoji_library.Actions.EmojIconActions;
import hani.momanii.supernova_emoji_library.Helper.EmojiconEditText;
import hani.momanii.supernova_emoji_library.Helper.EmojiconTextView;
import static com.yef.youthempower.youth.R.layout.activity_online;
public class OnlineActivity extends AppCompatActivity {
private static int SIGN_IN_REQUEST_CODE = 1;
private FirebaseListAdapter<ChatMessage> adapter;
RelativeLayout activity_online;
//Add Emojicon
EmojiconEditText emojiconEditText;
ImageView emojiButton,submitButton;
EmojIconActions emojIconActions;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent
data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == SIGN_IN_REQUEST_CODE)
{
if(resultCode == RESULT_OK)
{
Snackbar.make(activity_online, "Successfully signed
in.Welcome!", Snackbar.LENGTH_SHORT).show();
displayChatMessage();
}
else{
Snackbar.make(activity_online,"We couldn't sign you in.Please
try again later", Snackbar.LENGTH_SHORT).show();
finish();
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_online);
activity_online=(RelativeLayout)findViewById(R.id.activity_online);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
emojiButton = (ImageView)findViewById(R.id.emoji_button);
submitButton = (ImageView)findViewById(R.id.submit_button);
emojiconEditText =
(EmojiconEditText)findViewById(R.id.emojicon_edit_text);
emojIconActions = new
EmojIconActions(getApplicationContext(),
activity_online,emojiButton,emojiconEditText);
emojIconActions.ShowEmojicon();
submitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FirebaseDatabase.getInstance().getReference().push().setValue(new ChatMessage(emojiconEditText.getText().toString(),
FirebaseAuth.getInstance().getCurrentUser().getEmail()));
emojiconEditText.setText("");
emojiconEditText.requestFocus();
}
});
//Check if not sign-in then navigate Signin page
if(FirebaseAuth.getInstance().getCurrentUser() == null)
{
startActivityForResult(AuthUI.getInstance().createSignInIntentBuilder().build(),SIGN_IN_REQUEST_CODE);
}
else
{
Snackbar.make(activity_online,"Welcome "+FirebaseAuth.getInstance().getCurrentUser().getEmail(),Snackbar.LENGTH_SHORT).show();
//Load content
displayChatMessage();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home)
finish();
return super.onOptionsItemSelected(item);
}
private void displayChatMessage() {
ListView listOfMessage = (ListView)findViewById(R.id.list_of_message);
adapter = new FirebaseListAdapter<ChatMessage>(this,ChatMessage.class,R.layout.list_items,FirebaseDatabase.getInstance().getReference())
{
#Override
protected void populateView(View v, ChatMessage model, int position) {
//Get references to the views of list_items.xml
TextView messageText, messageUser, messageTime;
messageText = (EmojiconTextView) v.findViewById(R.id.message_text);
messageUser = (TextView) v.findViewById(R.id.message_user);
messageTime = (TextView) v.findViewById(R.id.message_time);
messageText.setText(model.getMessageText());
messageUser.setText(model.getMessageUser());
messageTime.setText(DateFormat.format("dd-MM-yyyy (HH:mm:ss)", model.getMessageTime()));
}
};
listOfMessage.setAdapter(adapter);
}
}
You can easily send notifications from firebase console,
Refer the docs : https://firebase.google.com/docs/cloud-messaging/
https://proandroiddev.com/mastering-firebase-notifications-36a3ffe57c41
But you are asking for sort of automatic notification, this is a bit tricky but you can do this by
Using firebase cloud functions.
Video tutorial : https://www.youtube.com/playlist?list=PLGCjwl1RrtcRHjHyZAxm_Mq4qvtnundo0
By a post request to your firebase server,
Docs : https://firebase.google.com/docs/cloud-messaging/send-message
How to send device to device messages using Firebase Cloud Messaging?
Im creating an application with 2 different users and i want to redirect them in different activity after they login. everytime that you sign up or register in the app. it will ask you if you are student or teacher. after the registration. all information you filled up are stored in firebase database including Name, Phone, Account Type and User Id. This is my code. i hope someone here could help me because this is our thesis project.
This is my LoginActivity.java codes
package com.example.vincedamsel.firebase;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.Typeface;
import android.support.annotation.NonNull;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
#SuppressWarnings("ConstantConditions")
public class LoginActivity extends AppCompatActivity {
private TextInputLayout emailField;
private TextInputLayout passwordField;
private View btnLogin,btnRegister,btnForgotPassword;
private ProgressDialog progressDialog;
private FirebaseAuth auth;
private Spinner spinAccountType;
private DatabaseReference ref;
private FirebaseAuth.AuthStateListener mAuthListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
emailField = (TextInputLayout) findViewById(R.id.email_field);
passwordField = (TextInputLayout) findViewById(R.id.password_field);
btnLogin = findViewById(R.id.login);
btnRegister = findViewById(R.id.register);
btnForgotPassword = findViewById(R.id.forgotpassword);
//Get Firebase auth instance
auth = FirebaseAuth.getInstance();
emailField.requestFocus();
btnRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder2=new AlertDialog.Builder(LoginActivity.this);
builder2.setTitle("Register");
builder2.setMessage("Sign up for Attendance");
builder2.setPositiveButton(" Professor ",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
final String type2="Professor";
Intent intent = new Intent(LoginActivity.this, SignupActivity.class);
intent.putExtra("Type",type2);
startActivity(intent);
}
});
builder2.setNegativeButton(" Student ", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
final String type1="Student";
Intent intent = new Intent(LoginActivity.this, SignupActivity.class);
intent.putExtra("Type",type1);
startActivity(intent);
}
});
AlertDialog dialog = builder2.show();
TextView messageView = (TextView)dialog.findViewById(android.R.id.message);
messageView.setGravity(Gravity.CENTER);
messageView.setTextSize(17);
}
});
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!Utils.hasText(emailField)) {
Utils.showToast(LoginActivity.this, "Please input your email");
} else if (!Utils.hasText(passwordField)) {
Utils.showToast(LoginActivity.this, "Please input your password");
} else {
//requesting Firebase server
showProcessDialog();
authenticateUser(Utils.getText(emailField), Utils.getText(passwordField));
}
}
});
btnForgotPassword.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(LoginActivity.this, ResetPasswordActivity.class);
startActivity(intent);
}
});
}
private void authenticateUser(String email, String password) {
auth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
// When login failed
if (!task.isSuccessful()) {
progressDialog.dismiss();
Utils.showToast(LoginActivity.this, "Login error!");
} else {
//When login successful, redirect user to main activity
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
progressDialog.dismiss();
finish();
}
}
});
}
private void showProcessDialog() {
progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Login");
progressDialog.setMessage("Logging in Firebase server...");
progressDialog.show();
}
}
this is my Database image
this is my Rules image
If you want redirect to different activities, you need user type, when user login success, you need retrieve the type of user and redirect to specific activity for example:
String USER_TYPE_1 = "student";
String USER_TYPE_2 = "profesor";
/**After login success you add logic:**/
Intent intent = null;
if(user.equals(USER_TYPE_1)){
intent = new Intent(this, Activity1.class);
}else if(user.equals(USER_TYPE_2)){
intent = new Intent(this, Activity2.class);
}
if(intent!=null){
startActivity(intent);
}
Remember the user type need retrieve of database or storage whatever you want.
you can use if statement to check account type and use two intents to direct users to the activities
you need to save the status of login type(foe ex:if the student has login u have to save the status as student..if it is professor u have to save it professor)in shared prefernces..at the time of sign up..and at the time of login again u have to fetch the status from shared prefernce by that u can call the activities
I have a simple app that has an unlock feature in it. When a user purchases this they can unlock more content in the app.
When I debug the app I don't get any errors, but I am unable to retrieve a list of products using the google billing services.
On my main activity I would like to check if the user has all ready purchased the "upgrade" if they have do something with that information.
I have been following the api documentation but its not really helping.
In App Billing Reference
Implementation
Testing
I have 1 item in my In-app products, I have followed the testing document and added an apk to my Alpha testing. The problem here is that apk cant have debugging enabled, so when I use the debugger in android studio the app may perform differently??
I think my code is OK,but any help or guidance in how to test this would be great.
MainActivity.java
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import com.android.vending.billing.IInAppBillingService;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends Activity {
IInAppBillingService mService;
ServiceConnection connection;
Intent serviceIntent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
Button start = (Button) findViewById(R.id.startgame);
Button settings = (Button) findViewById(R.id.about);
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), StartGame.class);
startActivity(i);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
}
});
settings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), Settings.class);
startActivity(i);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
}
});
/// check for pro unlock
serviceIntent = new Intent("com.android.vending.billing.InAppBillingService.BIND");
serviceIntent.setPackage("com.android.vending");
// first this
connection = new ServiceConnection() {
#Override
public void onServiceDisconnected(ComponentName name) {
mService = null;
}
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
Log.d("BILLING", "Connected");
//purchse info
mService = IInAppBillingService.Stub.asInterface(service);
checkPurchaseInfo();
}
};
bindService(serviceIntent, connection, Context.BIND_AUTO_CREATE);
}
private void checkPurchaseInfo() {
try {
Bundle ownedItems = mService.getPurchases(3, getPackageName(), "inapp", null);
int responseCode = ownedItems.getInt("RESPONSE_CODE");
Log.d("BILLING","Request Code: " + responseCode);
if(responseCode == 0){
ArrayList<String> ownedSkus = ownedItems.getStringArrayList("INAPP_PURCHASE_ITEM_LIST");
ArrayList<String> purchaseDataList = ownedItems.getStringArrayList("INAPP_PURCHASE_DATA_LIST");
ArrayList<String> signatureList = ownedItems.getStringArrayList("INAPP_DATA_SIGNATURE_LIST");
String continuationToken = ownedItems.getString("INAPP_CONTINUATION_TOKEN");
Log.d("OWNED",ownedSkus.toString());
Log.d("purcahseList",purchaseDataList.toString());
Log.d("SIGNLIST",signatureList.toString());
/////////
//all of these arrays come back as empty []
////////
}
} catch (RemoteException e) {
e.printStackTrace();
}
}
#Override
public void onDestroy() {
super.onDestroy();
if (connection != null) {
unbindService(connection);
}
}
}