I have made an app in which first the user verifies its number with the help of sinch verification and then after succesfull verification it goes to the gameactivity but the problem is that every time the user opens the app he or she has to verify again which is a very bad out come.
i dont how o skip the verification process after again opening the app
Main Activity
public class MainActivity extends Activity {
public static final String SMS = "sms";
public static final String FLASHCALL = "flashcall";
public static final String INTENT_PHONENUMBER = "phonenumber";
public static final String INTENT_METHOD = "method";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TelephonyManager manager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
TextView phoneNumber = (TextView) findViewById(R.id.phoneNumber);
phoneNumber.setText(manager.getLine1Number());
}
private void openActivity(String phoneNumber, String method) {
Intent verification = new Intent(this, VerificationActivity.class);
verification.putExtra(INTENT_PHONENUMBER, phoneNumber);
verification.putExtra(INTENT_METHOD, method);
startActivity(verification);
}
private boolean checkInput() {
TextView phoneNumber = (TextView) findViewById(R.id.phoneNumber);
if (phoneNumber.getText().toString().isEmpty()) {
Toast.makeText(this, "Please input a phone number.", Toast.LENGTH_LONG).show();
return false;
}
return true;
}
public void onButtonClicked(View view) {
if (checkInput()) {
TextView phoneNumber = (TextView) findViewById(R.id.phoneNumber);
if (view == findViewById(R.id.smsVerificationButton)) {
openActivity(phoneNumber.getText().toString(), SMS);
} else if (view == findViewById(R.id.callVerificationButton)) {
openActivity(phoneNumber.getText().toString(), FLASHCALL);
}
}
}
}
Verification Activity
public class VerificationActivity extends Activity {
private static final String TAG = Verification.class.getSimpleName();
private final String APPLICATION_KEY = "af23************************";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_verification);
ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressIndicator);
progressBar.setVisibility(View.VISIBLE);
Intent intent = getIntent();
if (intent != null) {
String phoneNumber = intent.getStringExtra(MainActivity.INTENT_PHONENUMBER);
String method = intent.getStringExtra(MainActivity.INTENT_METHOD);
TextView phoneText = (TextView) findViewById(R.id.numberText);
phoneText.setText(phoneNumber);
createVerification(phoneNumber, method);
}
}
void createVerification(String phoneNumber, String method) {
Config config = SinchVerification.config().applicationKey(APPLICATION_KEY).context(getApplicationContext())
.build();
VerificationListener listener = new MyVerificationListener();
Verification verification;
if (method.equalsIgnoreCase(MainActivity.SMS)) {
verification = SinchVerification.createSmsVerification(config, phoneNumber, listener);
} else {
TextView messageText = (TextView) findViewById(R.id.textView);
messageText.setText(R.string.flashcalling);
verification = SinchVerification.createFlashCallVerification(config, phoneNumber, listener);
}
verification.initiate();
}
class MyVerificationListener implements VerificationListener {
#Override
public void onInitiated() {
Log.d(TAG, "Initialized!");
}
#Override
public void onInitiationFailed(Exception exception) {
Log.e(TAG, "Verification initialization failed: " + exception.getMessage());
hideProgress(R.string.failed, false);
}
#Override
public void onVerified() {
Log.d(TAG, "Verified!");
hideProgress(R.string.verified, true);
}
#Override
public void onVerificationFailed(Exception exception) {
Log.e(TAG, "Verification failed: " + exception.getMessage());
hideProgress(R.string.failed, false);
}
}
void hideProgress(int message, boolean success) {
if (success) {
ImageView checkMark = (ImageView) findViewById(R.id.checkmarkImage);
checkMark.setVisibility(View.VISIBLE);
}
ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressIndicator);
progressBar.setVisibility(View.INVISIBLE);
TextView progressText = (TextView) findViewById(R.id.progressText);
progressText.setVisibility(View.INVISIBLE);
TextView messageText = (TextView) findViewById(R.id.textView);
messageText.setText(message);
}
}
I just want that on re opening verification process should not be again called.
You can use SharedPreferences. add a key to your SharedPreferences object and initialize with value 0. You can do something like below
SharedPrefences prefences = PrefenceManager.getSharedPreferences("TAG",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
Now on successfull verification :
preferences.putInt("key",1);
so on next launch check for this key value, if its 1 skip the VerificationActivity and start GameActivtiy i.e
int value = preferences.getInt("key",0);
if(value == 0){
// Verify
}else{
// Skip Verification
}
Related
I am trying to create app that can connect to a MS SQL database when the user enters his username and password, I have tried multiple times and just cannot succeed. What would be the best way to connect my app?
This is the code that I have tried below.
public class LoginActivity extends AppCompatActivity {
private static String ip = "myip";
private static String port = "myportnum";
private static String Class = "net.sourceforge.jtds.jtbc.Driver";
private static String database = "name";
private static String username = "name";
private static String password = "password";
private static String url = "jdbc:jtds:sqlserver://"+ip+":"+port+"/"+database;
private Connection connection = null;
private EditText userNameET, passwordEt;
private Button loginBTN;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
userNameET = findViewById(R.id.userNameEditText);
passwordEt = findViewById(R.id.passEditText);
loginBTN = findViewById(R.id.loginBtn);
StrictMode.ThreadPolicy policy = null;
policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
// #android.support.annotation.RequiresApi(api = Build.VERSION_CODES.CUPCAKE)
private class DoLoginForUser extends AsyncTask<String, Void, String> {
String emailId, password;
#Override
protected void onPreExecute() {
super.onPreExecute();
emailId = userNameET.getText().toString();
password = passwordEt.getText().toString();
// progressBar.setVisibility(View.VISIBLE);
loginBTN.setVisibility(View.GONE);
}
#Override
protected String doInBackground(String... params) {
try {
ConnectionHelper con = new ConnectionHelper();
Connection connect = ConnectionHelper.CONN();
String query = "Select * from testDatabase where UserId='" + emailId + "'";
PreparedStatement ps = connect.prepareStatement(query);
Log.e("query",query);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
String passcode = rs.getString("password");
connect.close();
rs.close();
ps.close();
if (passcode != null && !passcode.trim().equals("") && passcode.equals(password))
return "success";
else
return "Invalid Credentials";
} else
return "User does not exists.";
} catch (Exception e) {
return "Error:" + e.getMessage();
}
}
#Override
protected void onPostExecute(String result) {
//Toast.makeText(signup.this, result, Toast.LENGTH_SHORT).show();
// ShowSnackBar(result);
// progressBar.setVisibility(View.GONE);
loginBTN.setVisibility(View.VISIBLE);
if (result.equals("success")) {
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("userdetails",0);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("email",userNameET.getText().toString());
editor.commit();
Intent i = new Intent(LoginActivity.this, MainActivity.class);
startActivity(i);
} else {
//ShowSnackBar(result);
}
}
}
//public void ShowSnackBar(String message) {
// Snackbar.make(lvparent, message, Snackbar.LENGTH_LONG)
// .setAction("CLOSE", new View.OnClickListener() {
// #Override
// public void onClick(View view) {
//// }
// })
// .setActionTextColor(getResources().getColor(android.R.color.holo_red_light))
// .show();
// }
public void DoLogin(View v)
{
DoLoginForUser login = null;
login = new DoLoginForUser();
login.execute("");
}
I am expecting it to connect and then take me to the next screen.
i have a fragment in that i made a button to collect user mobile number. In the same fragment i have made a button to toast the string value collected from edited text (mobile), I know it's a simple question but i don't know the answer please help me
this is my edit text
LayoutInflater inflater = getActivity().getLayoutInflater();
View layout = inflater.inflate(R.layout.dialog_set_mobile,(ViewGroup) view.findViewById(R.id.dialog_mobile));
new AlertDialog.Builder(getActivity()).setTitle("Please Input Contact Information").setIcon(
android.R.drawable.ic_dialog_dialer).setView(
layout).setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Dialog dialog = (Dialog) dialogInterface;
EditText inputMobile = (EditText) dialog.findViewById(R.id.dialog_et_mobile);
if (inputMobile.getText().toString().isEmpty()){
return;
}
try{
long number = Long.valueOf(inputMobile.getText().toString());
SPManipulation.getInstance(getActivity()).setMobile(inputMobile.getText().toString());
mTextMobile.setText(inputMobile.getText().toString());
String mobile = inputMobile.getText().toString();
//DatabaseReference mynum = database.getReference("number");
DatabaseReference mynum = database.getReference().child(userID).child("number");
mynum.setValue(mobile);
}catch (Exception e){
Toast.makeText(getActivity(), "Please Input Correct Phone Number!", Toast.LENGTH_SHORT).show();
}
This is my button code
mButtonCheckout = (Button) view.findViewById(R.id.checkout_pay);
mButtonCheckout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FirebaseAuth mAuth = FirebaseAuth.getInstance();
String userID = mAuth.getCurrentUser().getUid();
DatabaseReference mylocation = database.getReference().child(userID).child("location");
// mylocation.setValue(mobile); // here i need string
}
});
this is my whole code of fragment
package com.example.guanzhuli.foody.CartPage.fragment;
public class CheckoutFragment extends Fragment {
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();
// PayPal Initialization
private static final String TAG = "iCartPayment";
//private static final String CONFIG_ENVIRONMENT = PayPalConfiguration.ENVIRONMENT_NO_NETWORK;
private static final String CONFIG_ENVIRONMENT = PayPalConfiguration.ENVIRONMENT_SANDBOX;
// note that these credentials will differ between live & sandbox environments.
private static final String CONFIG_CLIENT_ID = "AfNfJY2QLMIzxPpAt97YVg4GKJtMa0k8wQICuFcwIdR6bR73oexStWMQfH0nirg-WlFradZHcPnCleZg";
private static final int REQUEST_CODE_PAYMENT = 1;
private static PayPalConfiguration config = new PayPalConfiguration()
.environment(CONFIG_ENVIRONMENT)
.clientId(CONFIG_CLIENT_ID)
// The following are only used in PayPalFuturePaymentActivity.
.merchantName("Example Merchant")
.merchantPrivacyPolicyUri(Uri.parse("https://www.example.com/privacy"))
.merchantUserAgreementUri(Uri.parse("https://www.example.com/legal"));
// Fragment Component Initialization
private RecyclerView mRecyclerView;
private TextView mTextMobile, mTextTotal, mTextEditAddress, mTextEditMobil;
public static TextView mTextAddress;
private Button mButtonCheckout, mButtonCancel;
public CheckoutFragment() {
// Required empty public constructor
}
DatabaseReference databaseReference;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_checkout, container, false);
mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerview_checkout);
mRecyclerView.setAdapter(new CheckoutAdapter(getContext()));
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
// initial button
mButtonCheckout = (Button) view.findViewById(R.id.checkout_pay);
mButtonCheckout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Toast.makeText(getContext(),abc, Toast.LENGTH_SHORT).show();
// payOrder();
FirebaseAuth mAuth = FirebaseAuth.getInstance();
String userID = mAuth.getCurrentUser().getUid();
DatabaseReference mylocation = database.getReference().child(userID).child("location");
// mylocation.setValue(mobile); // here i need string
}
});
mButtonCancel = (Button) view.findViewById(R.id.checkout_cancel);
mButtonCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
getActivity().finish();
}
});
// initial text
mTextMobile = (TextView) view.findViewById(R.id.checkout_mobile);
mTextMobile.setText(SPManipulation.getInstance(getActivity()).getMobile());
mTextAddress = (TextView) view.findViewById(R.id.checkout_address);
mTextAddress.setText(SPManipulation.getInstance(getContext()).getAddress());
mTextTotal = (TextView) view.findViewById(R.id.checkout_total);
mTextEditMobil = (TextView) view.findViewById(R.id.checkout_edit_mobile);
mTextEditMobil.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
Toast.makeText(getContext(), "Edit Number", Toast.LENGTH_SHORT).show();
LayoutInflater inflater = getActivity().getLayoutInflater();
View layout = inflater.inflate(R.layout.dialog_set_mobile,(ViewGroup) view.findViewById(R.id.dialog_mobile));
new AlertDialog.Builder(getActivity()).setTitle("Please Input Contact Information").setIcon(
android.R.drawable.ic_dialog_dialer).setView(
layout).setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Dialog dialog = (Dialog) dialogInterface;
EditText inputMobile = (EditText) dialog.findViewById(R.id.dialog_et_mobile);
if (inputMobile.getText().toString().isEmpty()){
return;
}
try{
long number = Long.valueOf(inputMobile.getText().toString());
SPManipulation.getInstance(getActivity()).setMobile(inputMobile.getText().toString());
mTextMobile.setText(inputMobile.getText().toString());
FirebaseAuth mAuth = FirebaseAuth.getInstance();
String userID = mAuth.getCurrentUser().getUid();
String mobile = inputMobile.getText().toString();
DatabaseReference mynum = database.getReference().child(userID).child("number");
mynum.setValue(mobile);
}catch (Exception e){
Toast.makeText(getActivity(), "Please Input Correct Phone Number!", Toast.LENGTH_SHORT).show();
}
}
}).setNegativeButton("Cancel", null).show();
}
});
mTextEditAddress = (TextView) view.findViewById(R.id.checkout_edit_addr);
mTextEditAddress.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
LayoutInflater inflater = getActivity().getLayoutInflater();
View layout = inflater.inflate(R.layout.dialog_set_location,(ViewGroup) view.findViewById(R.id.dialog_location));
new AlertDialog.Builder(getActivity()).setTitle("Please Input Delivery Location").setIcon(
android.R.drawable.ic_dialog_dialer).setView(
layout).setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Dialog dialog = (Dialog) dialogInterface;
EditText inputLocation = (EditText) dialog.findViewById(R.id.dialog_et_location);
if (inputLocation.getText().toString().isEmpty()){
return;
}
mTextAddress.setText(inputLocation.getText().toString());
String bbb = inputLocation.getText().toString();
Toast.makeText(getContext(),bbb, Toast.LENGTH_LONG).show();
}
})
.setNeutralButton("Show Map", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent mapAct = new Intent(getActivity(), MapsActivity.class);
startActivity(mapAct);
}
})
.setNegativeButton("Cancel", null)
.show();
}
});
mTextTotal.setText(String.valueOf(ShoppingCartItem.getInstance(getContext()).getPrice() * 1.06 + 1.99));
return view;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_PAYMENT) {
if (resultCode == getActivity().RESULT_OK) {
ShoppingCartItem.getInstance(getContext()).placeOrder(mTextAddress.getText().toString(), mTextMobile.getText().toString());
ShoppingCartItem.getInstance(getContext()).clear();
DBManipulation.getInstance(getActivity()).deleteAll();
PaymentConfirmation confirm =
data.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION);
if (confirm != null) {
try {
Log.i(TAG, confirm.toJSONObject().toString(4));
Log.i(TAG, confirm.getPayment().toJSONObject().toString(4));
/**
* TODO: send 'confirm' (and possibly confirm.getPayment() to your server for verification
* or consent completion.
* See https://developer.paypal.com/webapps/developer/docs/integration/mobile/verify-mobile-payment/
* for more details.
*
* For sample mobile backend interactions, see
* https://github.com/paypal/rest-api-sdk-python/tree/master/samples/mobile_backend
*/
registerOrder();
}
catch (JSONException e) {
Log.e(TAG, "an extremely unlikely failure occurred: ", e);
}
}
HomePageActivity.cartNumber.setText("0");
getActivity().finish();
} else if (resultCode == getActivity().RESULT_CANCELED) {
Log.i(TAG, "The user canceled.");
Toast.makeText(getContext(),"Cancel", Toast.LENGTH_LONG).show();
} else if (resultCode == PaymentActivity.RESULT_EXTRAS_INVALID) {
Log.i(
TAG,
"An invalid Payment or PayPalConfiguration was submitted. Please see the docs.");
}
}
}
#Override
public void onDestroy() {
super.onDestroy();
getActivity().stopService(new Intent(getContext(), PayPalService.class));
}
private void payOrder() {
/*
* PAYMENT_INTENT_SALE will cause the payment to complete immediately.
* Change PAYMENT_INTENT_SALE to
* - PAYMENT_INTENT_AUTHORIZE to only authorize payment and capture funds later.
* - PAYMENT_INTENT_ORDER to create a payment for authorization and capture
* later via calls from your server.
*
* Also, to include additional payment details and an item list, see getStuffToBuy() below.
*/
PayPalPayment thingToBuy = getStuffToBuy(PayPalPayment.PAYMENT_INTENT_SALE);
/*
* See getStuffToBuy(..) for examples of some available payment options.
*/
Intent intent = new Intent(getContext(), PaymentActivity.class);
// send the same configuration for restart resiliency
intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);
intent.putExtra(PaymentActivity.EXTRA_PAYMENT, thingToBuy);
startActivityForResult(intent, REQUEST_CODE_PAYMENT);
}
private PayPalPayment getStuffToBuy(String paymentIntent) {
//--- include an item list, payment amount details
PayPalItem[] items = new PayPalItem[ShoppingCartItem.getInstance(getContext()).getFoodTypeSize()];
for (int position = 0; position < ShoppingCartItem.getInstance(getContext()).getFoodTypeSize(); position++){
int id = ShoppingCartItem.getInstance(getContext()).getFoodInCart().get(position);
final Food curFood = ShoppingCartItem.getInstance(getContext()).getFoodById(id);
final int curFoodNumber = ShoppingCartItem.getInstance(getContext()).getFoodNumber(curFood);
Log.e("PRICE & NUMBER", "price: " + curFood.getPrice() + ", number: " + curFoodNumber);
items[position] = new PayPalItem("Item No." + curFood.getId(),
curFoodNumber,
new BigDecimal(String.valueOf(curFood.getPrice())),"USD", curFood.getName()
);
}
BigDecimal subtotal = PayPalItem.getItemTotal(items);
BigDecimal shipping = new BigDecimal("1.99");
BigDecimal tax = new BigDecimal("" + ShoppingCartItem.getInstance(getContext()).getPrice() * 0.06);
PayPalPaymentDetails paymentDetails = new PayPalPaymentDetails(shipping, subtotal, tax);
BigDecimal amount = subtotal.add(shipping).add(tax);
PayPalPayment payment = new PayPalPayment(amount, "USD", "Foody Inc.", paymentIntent);
payment.items(items).paymentDetails(paymentDetails);
//--- set other optional fields like invoice_number, custom field, and soft_descriptor
payment.custom("This is text that will be associated with the payment that the app can use.");
return payment;
}
private void registerOrder() {
}
}
you have two way
1 : Instead on mobile use this
Toast.makeText(getContext(),inputMobile.getText().toString(), Toast.LENGTH_SHORT).show();
2 : Create global string variable mobile like this
first create global mobile number above on onCreateView()
public String mobileNumber;
then in you button click in dialog init mobileNumber
try{
long number = Long.valueOf(inputMobile.getText().toString());
SPManipulation.getInstance(getActivity()).setMobile(inputMobile.getText().toString());
mTextMobile.setText(inputMobile.getText().toString());
FirebaseAuth mAuth = FirebaseAuth.getInstance();
String userID = mAuth.getCurrentUser().getUid();
mobileNumber = inputMobile.getText().toString();//THIS LINE CHANGED
DatabaseReference mynum = database.getReference().child(userID).child("number");
mynum.setValue(mobile);
}catch (Exception e){
Toast.makeText(getActivity(), "Please Input Correct Phone Number!", Toast.LENGTH_SHORT).show();
}
Now you can use mobileNumber anywhere like in button
mButtonCheckout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getContext(),mobileNumber, Toast.LENGTH_SHORT).show();
}
});
declare a String variable to store the value of the EditText
String mobileNumber = inputMobile.getText().toString();
Create your Toast inside the OnClickListener.
Toast.makeText(getContext, mobileNumber,Toast.LENGTH_LONG).show();
I have three activities, I capture all data but one from DetailActivity upon button click and save in database using Room; My intention is to insert all these data into the database and start ReviewActivity so as to get the arraylist of reviews and also insert it in the database. Everything seems to work fine until when I want to view review offline because I believe it has been saved, reviews does not get loaded.
This is my DetailActivity,
TextView overview_tv; ImageView image_tv; TextView name_tv; TextView ratings; Context context; TextView release_date; ImageView backdrop_poster; private ExpandableHeightListView trailers; public static ArrayList<Youtube> youtube; public static ArrayList<Review> reviews; TrailerViewAdapter adapter; public static DataObject data; DataObject dataObject; ArrayList<Review> savedReview; private static final String IMAGE_URL = "http://image.tmdb.org/t/p/w185/"; private static final String THE_MOVIEDB_URL2 = "https://api.themoviedb.org/3/movie/"; private static final String MOVIE_QUERY2 = "api_key"; private static final String API_KEY2 = "6cc4f47bd4a64e0117e157b79072ae37"; private static String SEARCH_QUERY2 = "videos"; public static int movieId; Button viewReviews; Button favourite; String movieRating; private static final int YOUTUBE_SEARCH_LOADER = 23; private static final int REVIEW_SEARCH_LOADER = 24; File file; String name; String overview; String releaseDate; int switcher; public static ArrayList<Review> favouriteReviews; TextView trev; AppDatabase mDb; //Navigation arrow on the action bar #Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == android.R.id.home) { NavUtils.navigateUpFromSameTask(this); } return super.onOptionsItemSelected(item); } #Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_detail); mDb = AppDatabase.getInstance(getApplicationContext()); youtube = new ArrayList<Youtube>(); reviews = new ArrayList<Review>(); adapter = new TrailerViewAdapter(this, youtube); //Credit to Paolorotolo #github trailers = findViewById(R.id.expandable_list); trailers.setAdapter(adapter); trailers.setExpanded(true); //Navigation arrow on the acton bar; check also override onOptionsItemSelected ActionBar actionBar = this.getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); } context = getApplicationContext(); Intent intent = getIntent(); if (intent == null) { closeOnError(); } switcher = getIntent().getIntExtra("switch", 3); overview_tv = findViewById(R.id.overview); image_tv = findViewById(R.id.image); name_tv = findViewById(R.id.name); ratings = findViewById(R.id.ratings); release_date = findViewById(R.id.release_date); backdrop_poster = findViewById(R.id.backdrop_poster); trev = findViewById(R.id.review_show); viewReviews = findViewById(R.id.review_button); favourite = findViewById(R.id.favourite_button); addListenerOnRatingBar(ratings); if (switcher != 2) { favourite.setVisibility(View.INVISIBLE); dataObject = (DataObject) getIntent().getParcelableExtra("array"); final String favouriteName = dataObject.getName(); final String favouriteOverview = dataObject.getOverview(); final String favouriteReleaseDate = dataObject.getReleaseDate(); ArrayList<Youtube> savedTrailer = dataObject.getTrailers(); savedReview = dataObject.getMovieReviews(); movieRating = dataObject.getRating(); name_tv.setText(favouriteName); overview_tv.setText(favouriteOverview); ratings.setText("Rating: " + movieRating); release_date.setText("Release Date: " + favouriteReleaseDate);// Toast.makeText(this, "Testing Reviews " + savedReview.get(0).getAuthor(), Toast.LENGTH_SHORT).show(); String imagePath = name_tv.getText().toString() + "0i"; String backdropPath = name_tv.getText().toString() + "1b"; try { DataObjectAdapter.downloadImage(imagePath, image_tv, this); } catch (Exception e) { e.printStackTrace(); } try { DataObjectAdapter.downloadImage(backdropPath, backdrop_poster, context); } catch (Exception e) { e.printStackTrace(); } if (savedTrailer != null) { TrailerViewAdapter lv = new TrailerViewAdapter(DetailActivity.this, savedTrailer); trailers.setAdapter(lv); switcher = 3; } } else { name = getIntent().getStringExtra("Name"); overview = getIntent().getStringExtra("Overview"); final String image = getIntent().getStringExtra("Image"); movieId = getIntent().getIntExtra("movieId", 1); final String backdrop = getIntent().getStringExtra("backdrop"); releaseDate = getIntent().getStringExtra("releaseDate"); movieRating = getIntent().getStringExtra("rating"); Log.i("this", "switch " + switcher); name_tv.setText(name); overview_tv.setText(overview); ratings.setText("Rating: " + movieRating); release_date.setText("Release Date: " + releaseDate); //load backdrop poster Picasso.with(context) .load(IMAGE_URL + backdrop) .fit() .placeholder(R.drawable.placeholder_image) .error(R.drawable.placeholder_image) .into(backdrop_poster); Picasso.with(context) .load(IMAGE_URL + image) .fit() .placeholder(R.drawable.placeholder_image) .error(R.drawable.placeholder_image) .into(image_tv); getSupportLoaderManager().initLoader(YOUTUBE_SEARCH_LOADER, null, this); //getSupportLoaderManager().initLoader(REVIEW_SEARCH_LOADER, null, this); //loadTrailers(); //loadReviews(); //populateKeys(); } /** * Here manages the views(list) for reviews */ viewReviews.setOnClickListener(new View.OnClickListener() { #Override public void onClick(View v) { if (switcher == 3) { startActivity(new Intent(DetailActivity.this, ReviewActivity.class) .putExtra("switch", 3)); } else { Log.i("this", "I am from initial" + switcher); startActivity(new Intent(DetailActivity.this, ReviewActivity.class).putExtra("id", movieId)); } } } ); favourite.setOnClickListener(new View.OnClickListener() { #Override public void onClick(View v) { data = new DataObject(); data.setName(name); data.setOverview(overview); data.setRating(movieRating); data.setReleaseDate(releaseDate); data.setTrailers(youtube);// data.setMovieReviews(reviews); try { saveImage(name_tv.getText().toString() + "0i", image_tv); saveImage(name_tv.getText().toString() + "1b", backdrop_poster); } catch (IOException e) { e.printStackTrace(); } Toast.makeText(context, "The movie is saved as a favourite", Toast.LENGTH_LONG).show(); AppExecutors.getInstance().diskIO().execute(new Runnable() { #Override public void run() { mDb.dataDao().insertData(data); } }); startActivity(new Intent(DetailActivity.this, ReviewActivity.class).putExtra("id", movieId) .putExtra(ReviewActivity.EXTRA_DATA_ID, 20)); } } ); }
And my ReviewActivity
public class ReviewActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<ArrayList<Review>>{ public static ArrayList<Review> reviews; public static List<DataObject> favouriteReviews; public static RecyclerView reviewList; ArrayList<Review> r; private static final int REVIEW_SEARCH_LOADER = 24; private static final String MOVIE_QUERY3 = "api_key"; private static final String API_KEY3 = "6cc4f47bd4a64e0117e157b79072ae37"; private static String SEARCH_QUERY3 = "reviews"; private static final String THE_MOVIEDB_URL3 = "https://api.themoviedb.org/3/movie/"; private static int movId; public static final String EXTRA_DATA_ID = "extraDataId"; private static final int DEFAULT_TASK_ID = -1; private int mTaskId = DEFAULT_TASK_ID; DataObject data1; AppDatabase mDb; ReviewAdapter revAdapter; int loaderSwitch; #Override protected void onResume() { super.onResume(); } #Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_review); mDb = AppDatabase.getInstance(getApplicationContext()); reviews = new ArrayList<Review>(); favouriteReviews = new ArrayList<DataObject>(); reviewList = findViewById(R.id.review_list); LinearLayoutManager layoutManager = new LinearLayoutManager(getApplicationContext()); reviewList.setLayoutManager(layoutManager); reviewList.setHasFixedSize(true); int switcher = getIntent().getIntExtra("switch", 1); Intent intent = getIntent(); if (intent == null) { finish(); } Log.i("this", "swithcer " + switcher); Log.i("this loader", "Loader " + loaderSwitch); if (switcher == 3){ DataObject dataObject = (DataObject) getIntent().getParcelableExtra("ArrayOfReviews"); if (dataObject != null){ ArrayList<Review> movieReviews = dataObject.getMovieReviews(); Toast.makeText(this, "There are reviews saved", Toast.LENGTH_LONG).show(); revAdapter = new ReviewAdapter(this, movieReviews ); reviewList.setAdapter(revAdapter); } } else { movId = getIntent().getIntExtra("id", 20); revAdapter = new ReviewAdapter(this, reviews); reviewList.setAdapter(revAdapter); loadReviews(); //populateReview(); } DividerItemDecoration decoration = new DividerItemDecoration(this, VERTICAL); reviewList.addItemDecoration(decoration); } #Override protected void onStart() { super.onStart(); //loadReviews(); } public static URL buildUrl3(String stringUrl) { Uri uri = Uri.parse(THE_MOVIEDB_URL3).buildUpon() .appendPath(stringUrl) .appendPath(SEARCH_QUERY3) .appendQueryParameter(MOVIE_QUERY3, API_KEY3) .build(); URL url = null; try { url = new URL(uri.toString()); } catch (MalformedURLException exception) { Log.e(TAG, "Error creating URL", exception); } return url; } public void loadReviews(){ // COMPLETED (19) Create a bundle called queryBundle Bundle queryBundle = new Bundle(); // COMPLETED (20) Use putString with SEARCH_QUERY_URL_EXTRA as the key and the String value of the URL as the value// queryBundle.putString(SEARCH_QUERY_URL_EXTRA, url.toString()); // COMPLETED (21) Call getSupportLoaderManager and store it in a LoaderManager variable LoaderManager loaderManager = getSupportLoaderManager(); // COMPLETED (22) Get our Loader by calling getLoader and passing the ID we specified Loader<ArrayList<Review>> movieReviews = loaderManager.getLoader(REVIEW_SEARCH_LOADER); // COMPLETED (23) If the Loader was null, initialize it. Else, restart it. if (movieReviews == null) { loaderManager.initLoader(REVIEW_SEARCH_LOADER, queryBundle, this); } else { loaderManager.restartLoader(REVIEW_SEARCH_LOADER, queryBundle, this); } } #Override public Loader<ArrayList<Review>> onCreateLoader(int id, Bundle args) { return new AsyncTaskLoader<ArrayList<Review>>(this) { #Override protected void onStartLoading() { super.onStartLoading(); forceLoad(); } #Override public ArrayList<Review> loadInBackground() { String g = String.valueOf(movId); // Create URL object URL url = buildUrl3(g); // Perform HTTP request on the URL and receive a JSON response back String jsonResponse = ""; try { jsonResponse = getResponseFromHttpUrl(url); } catch (Exception e) { e.printStackTrace(); } reviews = MovieJsonUtils.parseReview(jsonResponse); return reviews; } }; } #Override public void onLoadFinished(Loader<ArrayList<Review>> loader, ArrayList<Review> dat) { if (reviews != null) { Intent intent = getIntent(); if (intent != null && intent.hasExtra(EXTRA_DATA_ID)) { //mButton.setText(R.string.update_button); if (mTaskId == DEFAULT_TASK_ID) { mTaskId = intent.getIntExtra(EXTRA_DATA_ID, DEFAULT_TASK_ID); AppExecutors.getInstance().diskIO().execute(new Runnable() { #Override public void run() { data.setMovieReviews(reviews); mDb.dataDao().updateData(data); //mDb.dataDao().insertData(data); final List<DataObject> task = mDb.dataDao().loadById(mTaskId); runOnUiThread(new Runnable() { #Override public void run() { populateUI(task); } }); } }); } } else { ReviewAdapter lv = new ReviewAdapter(ReviewActivity.this, reviews); reviewList.setAdapter(lv); } } } #Override public void onLoaderReset(Loader<ArrayList<Review>> loader) { }
Data gets loaded from MainActivity, the saved data is passed on to other activities as a parcellable bundle via intent, the passed data is displayed in DetailActivity but not in ReviewActivity.
Alternatively, if I can load reviews alongside YouTube keys from DetailActivity, I believe I can handle the database issue from there, but two Loaders wouldn't just work together, the app crashes; I am aware two AsyncTasks concurrently run together solved this problem, but I prefer to use Loaders because of performance on configuration change
I was tring to request tomcat for register information into the mysql table, the android studio occured crushed.I was using the okhttp3 for a request method.But I really can't find the mistake. Can you have a look at it and give me some advice?
I wrote this method in an activity, it was right. I wondered why it is wrong then I write in the fragment.
public class RegisterFragment extends Fragment {
private static final String TAG = "RegisterFragment ";
private Button sendSMS, submit;
private EditText usernameEdit,phoneNumberEdit, identifyingCodeEdit, loginPasswordEdit, confirmingPasswordEdit;
private EditText idCardNumberEdit, deviceIdEdit, birthdayEdit, addressEdit, urgentNumberEdit;
private RadioButton maleRadioButton;
private RadioButton femaleRadioButton;
private EventHandler eventHandler;
private String username;
private String phoneNumber;
private String loginPassword;
private String confirmingPassword;
private String idCardNumber;
private String deviceId;
private String gender;
private String birthday;
private String address;
private String urgentNumber;
#Override
public void onCreate(Bundle savedInstanceState) {
MobSDK.init(getContext(), "****95ec99ff7","ba3e429bf5fa8b8d34412f****055ce5");
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_register, container, false);
usernameEdit = (EditText) v.findViewById(R.id.username);
phoneNumberEdit = (EditText) v.findViewById(R.id.phone_number);
identifyingCodeEdit = (EditText) v.findViewById(R.id.identifing_code);
loginPasswordEdit = (EditText) v.findViewById(R.id.login_password);
confirmingPasswordEdit = (EditText) v.findViewById(R.id.confirming_password);
idCardNumberEdit = (EditText) v.findViewById(R.id.id_card_number);
deviceIdEdit = (EditText)v.findViewById(R.id.device_id);
birthdayEdit = (EditText) v.findViewById(R.id.birthday);
addressEdit = (EditText) v.findViewById(R.id.address);
urgentNumberEdit = (EditText) v.findViewById(R.id.urgent_number);
maleRadioButton = (RadioButton) v.findViewById(R.id.radio_button_male);
femaleRadioButton = (RadioButton) v.findViewById(R.id.radio_button_female);
sendSMS = (Button) v.findViewById(R.id.send_SMS);
sendSMS.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
phoneNumber = phoneNumberEdit.getText().toString().trim();
SMSSDK.getVerificationCode("86",phoneNumber);
}
});
submit = (Button) v.findViewById(R.id.submit);
submit.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
username = usernameEdit.getText().toString().trim();
loginPassword = loginPasswordEdit.getText().toString().trim();
confirmingPassword = confirmingPasswordEdit.getText().toString().trim();
idCardNumber = idCardNumberEdit.getText().toString().trim();
deviceId = deviceIdEdit.getText().toString().trim();
birthday = birthdayEdit.getText().toString().trim();
address = addressEdit.getText().toString().trim();
urgentNumber = urgentNumberEdit.getText().toString().trim();
if(maleRadioButton.isChecked()){
gender = "男";
}else if(femaleRadioButton.isChecked()){
gender = "女";
}
if(TextUtils.isEmpty(phoneNumber) || TextUtils.isEmpty(username)||TextUtils.isEmpty(loginPassword)
||TextUtils.isEmpty(confirmingPassword)||TextUtils.isEmpty(idCardNumber)||TextUtils.isEmpty(deviceId)
||TextUtils.isEmpty(birthday)||TextUtils.isEmpty(address)||TextUtils.isEmpty(urgentNumber)||TextUtils.isEmpty(gender)){
Toast.makeText(getActivity(), "填写的注册信息不能为空!",Toast.LENGTH_SHORT).show();
return;
}
String number = identifyingCodeEdit.getText().toString();
SMSSDK.submitVerificationCode("86",phoneNumber,number);
}
});
eventHandler = new EventHandler(){
#Override
public void afterEvent(int event, int result, Object data) {
Message msg = new Message();
msg.arg1 = event;
msg.arg2 = result;
msg.obj = data;
mHandler.sendMessage(msg);
}
};
SMSSDK.registerEventHandler(eventHandler);
return v;
}
private Handler mHandler = new Handler(){
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
int event = msg.arg1;
int result = msg.arg2;
Object data = msg.obj;
Log.e("event", "event=" + event);
if (result == SMSSDK.RESULT_COMPLETE){
//回调完成
if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
//提交验证码成功
Toast.makeText(getActivity(),"验证成功",Toast.LENGTH_SHORT).show();
doRegister();
}else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE){
//获取验证码成功
Toast.makeText(getActivity(),"验证码已发送", Toast.LENGTH_SHORT).show();
}else if (event ==SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES){
}
}else{
((Throwable)data).printStackTrace();
Throwable throwable = (Throwable) data;
try {
JSONObject obj = new JSONObject(throwable.getMessage());
final String des = obj.optString("detail");
if (!TextUtils.isEmpty(des)){
Toast.makeText(getActivity(),"提交错误信息",Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
};
//注册方法
private void doRegister(){
String path = null;
try {
path = "http://192.168.1.105:8080/Web/registerServlet"+"?username="
+ URLEncoder.encode(username, "utf-8")+"&phoneNumber="
+URLEncoder.encode(phoneNumber, "utf-8")+"&loginPassword="
+URLEncoder.encode(loginPassword, "utf-8")+"&confirmingPassword="
+URLEncoder.encode(confirmingPassword, "utf-8")+"&idCardNumber="
+URLEncoder.encode(idCardNumber, "utf-8")+"&deviceId="
+URLEncoder.encode(deviceId, "utf-8")+"&gender="
+URLEncoder.encode(gender, "utf-8")+"&birthday="
+URLEncoder.encode(birthday, "utf-8")+"&address="
+URLEncoder.encode(address, "utf-8")+"&urgentNumber="
+URLEncoder.encode(urgentNumber, "utf-8");
HttpUtil.sendOkHttpRequest(path,new okhttp3.Callback(){
#Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
Log.e(TAG,"error!");
}
#Override
public void onResponse(Call call, Response response) throws IOException {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
String responseData = response.body().string();
if(!TextUtils.isEmpty(responseData)){
Toast.makeText(getActivity(), responseData, Toast.LENGTH_LONG).show();
Intent selectIntnet = new Intent(getActivity(), SelectionActivity.class);
startActivity(selectIntnet);
}
}
});
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
#Override
public void onDestroy() {
super.onDestroy();
SMSSDK.unregisterEventHandler(eventHandler);
}
}
The logcat information is that:
I am trying to develop an authentication android based webservice Rest,I am using the library Retrofit with async task as an inner class .
I have a variable called loginstatus returns true if the user exists otherwise false .
the problem is when the compiler out of the success method isloginstatus initializes to false.
Here is my activity code :
public class CheckLoginActivity extends Activity {
static AlertDialog dialog;
Button b;
UserModel userModel;
TextView statusTV;
EditText userNameET, passWordET;
String editTextUsername;
boolean loginStatus;
String editTextPassword;
String API_URL = "http://192.168.42.60/task_manager/v1/index.php";
SharedPreferences sharedpreferences;
public static final String USERPREFERENCE = "userPreference";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_check_login);
final TextInputLayout usernameWrapper = (TextInputLayout) findViewById(R.id.usernameWrapper);
final TextInputLayout passwordWrapper = (TextInputLayout) findViewById(R.id.passwordWrapper);
usernameWrapper.setHint("Username");
passwordWrapper.setHint("Password");
dialog = new SpotsDialog(this, "Chargement");
//NameText control
userNameET = (EditText) findViewById(R.id.editText1);
passWordET = (EditText) findViewById(R.id.editText2);
//Display Text control
statusTV = (TextView) findViewById(R.id.tv_result);
//Button to trigger web service invocation
b = (Button) findViewById(R.id.button1);
//Display progress bar until web service invocation completes
//Button Click Listener
sharedpreferences = getSharedPreferences(USERPREFERENCE, Context.MODE_PRIVATE);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//Check if text controls are not empty
if (userNameET.getText().length() != 0 && userNameET.getText().toString() != "") {
if (passWordET.getText().length() != 0 && passWordET.getText().toString() != "") {
editTextUsername = userNameET.getText().toString();
editTextPassword = passWordET.getText().toString();
// statusTV.setText("");
//Create instance for AsyncCallWS
AsyncCallWS task = new AsyncCallWS();
//Call execute
task.execute(editTextUsername, editTextPassword);
}
//If Password text control is empty
else {
statusTV.setText("Please enter Password");
}
//If Username text control is empty
} else {
statusTV.setText("Please enter Username");
}
}
});
}
and my async task
private class AsyncCallWS extends AsyncTask<String, String, Void> {
//Make Progress Bar visible
protected void onPreExecute() {
dialog.show();
}
#Override
protected Void doInBackground(String... params) {
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(API_URL)
.build();
geolocateApi post = restAdapter.create(geolocateApi.class);
post.login(editTextUsername, editTextPassword, new Callback<UserModel>() {
#Override
public void success(UserModel userModelRecv, Response response) {
if (userModelRecv != null) {
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("username", userModelRecv.getUsername());
editor.putString("id", userModelRecv.getUser_id());
editor.putString("firstName", userModelRecv.getFirstName());
editor.putString("lastName", userModelRecv.getLastName());
editor.putString("Role", userModelRecv.getRole());
userModel=userModelRecv;
editor.commit();
loginStatus=true;
}else loginStatus=false;
}
#Override
public void failure(RetrofitError error) {
}
});
return null;
}
#Override
//Once WebService returns response
protected void onPostExecute(Void result) {
//Make Progress Bar invisible
Intent intSucces = new Intent(CheckLoginActivity.this, HomeActivity.class);
try {
Thread.sleep(200);
} catch (Exception e) {
e.printStackTrace();
}
dialog.hide();
//Error status is false
if (loginStatus) {
//Based on Boolean value returned from WebService
//Navigate to Home Screen
startActivity(intSucces);
} else {
//Set Error message
statusTV.setText("Login Failed, try again");
}
}
}
my interface Retrofit
public interface geolocateApi {
#FormUrlEncoded
#POST("/login")
public boolean login(#Field("username") String username,#Field("password") String password, Callback<UserModel> response);
}
Thanks for your help
You are using Retrofit for your login with a callback which basically sends request asynchronously. So by the time your onPostExecute is executed retrofit request might still be processing leaving your loginStatus to default false value. You don't need AsyncTask here as login already is running in background. It should be something like this
public class CheckLoginActivity extends Activity {
static AlertDialog dialog;
Button b;
UserModel userModel;
TextView statusTV;
EditText userNameET, passWordET;
String editTextUsername;
boolean loginStatus;
String editTextPassword;
String API_URL = "http://192.168.42.60/task_manager/v1/index.php";
SharedPreferences sharedpreferences;
public static final String USERPREFERENCE = "userPreference";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_check_login);
final TextInputLayout usernameWrapper = (TextInputLayout) findViewById(R.id.usernameWrapper);
final TextInputLayout passwordWrapper = (TextInputLayout) findViewById(R.id.passwordWrapper);
usernameWrapper.setHint("Username");
passwordWrapper.setHint("Password");
dialog = new SpotsDialog(this, "Chargement");
//NameText control
userNameET = (EditText) findViewById(R.id.editText1);
passWordET = (EditText) findViewById(R.id.editText2);
//Display Text control
statusTV = (TextView) findViewById(R.id.tv_result);
//Button to trigger web service invocation
b = (Button) findViewById(R.id.button1);
//Display progress bar until web service invocation completes
//Button Click Listener
sharedpreferences = getSharedPreferences(USERPREFERENCE, Context.MODE_PRIVATE);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//Check if text controls are not empty
if (userNameET.getText().length() != 0 && userNameET.getText().toString() != "") {
if (passWordET.getText().length() != 0 && passWordET.getText().toString() != "") {
editTextUsername = userNameET.getText().toString();
editTextPassword = passWordET.getText().toString();
// statusTV.setText("");
//Create instance for AsyncCallWS
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(API_URL)
.build();
geolocateApi post = restAdapter.create(geolocateApi.class);
post.login(editTextUsername, editTextPassword, new Callback<UserModel>() {
#Override
public void success(UserModel userModelRecv, Response response) {
dialog.hide();
if (userModelRecv != null) {
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("username", userModelRecv.getUsername());
editor.putString("id", userModelRecv.getUser_id());
editor.putString("firstName", userModelRecv.getFirstName());
editor.putString("lastName", userModelRecv.getLastName());
editor.putString("Role", userModelRecv.getRole());
userModel = userModelRecv;
editor.commit();
loginStatus = true;
Intent intSucces = new Intent(CheckLoginActivity.this, HomeActivity.class);
startActivity(intSucces);
} else {
loginStatus = false;
statusTV.setText("Login Failed, try again");
}
}
#Override
public void failure(RetrofitError error) {
}
});
}
//If Password text control is empty
else {
statusTV.setText("Please enter Password");
}
//If Username text control is empty
} else {
statusTV.setText("Please enter Username");
}
}
});
}
}