Why Retrofit can't resolve No connection - Check internet connection on Android? - java

Hello guys I have one specific problem. I'm using retrofit library for all of my network calls. And I have one method to send points to another user and if any error occurs, the server will return me code 400 and string alongside it that I will have to show to user. This thing is working I created it like this ( NetworkSDK is sending a body with params and expect to recieve an error status string if it occurs) so logically I am processing my errors in onResponse method (if Networksdk recieve an object with error string) and if onFailure occurs there is no error. But now I have a bigger problem. If there is no connection at all, if user turns off internet in that fragment it will again go to onFailure and show message that points are sent. Ordinary I would do that via status code if status code is 200 than it's okey but for some reasons I can't get any status code via response.code() command. Here is the code :
#Override
public void onClick(View v) {
try {
final String cardNo;
String amountstring = bodovi.getText().toString();
final Integer amount = Integer.valueOf(amountstring);
cardNo = brojkartice.getText().toString();
Log.d("Broj bodova:", amount.toString());
Log.d("Broj kartice:", cardNo);
final SendPoints Posiljka = new SendPoints();
Posiljka.setAmount(amount);
Posiljka.setCardNumber(cardNo);
NetworkSDK.getInstance().SendPoints(Posiljka, new Callback<SendPointsResponse>() {
#Override
public void onResponse(Call<SendPointsResponse> call, Response<SendPointsResponse> response) {
Log.d("Response code:", "" + response.code());
Log.d("Kartica", Posiljka.getCardNumber());
Log.d("Broj bodova", Posiljka.getAmount().toString());
try {
SendPointsResponse error = (new Gson()).fromJson(response.errorBody().string(), SendPointsResponse.class);
if (error.getCode().equals("-1"))
Toast.makeText(getActivity(), "Neuspješno slanje bodoava. Neispravni ulazni podaci.", Toast.LENGTH_SHORT).show();
if (error.getCode().equals("-2"))
Toast.makeText(getActivity(), "Neuspješno slanje bodova. Korisnički podaci nisu popunjeni.", Toast.LENGTH_SHORT).show();
if (error.getCode().equals("-3"))
Toast.makeText(getActivity(), "Neuspješno slanje bodova. Korisnik ima rezervisanu nagradu.", Toast.LENGTH_SHORT).show();
if (error.getCode().equals("-4"))
Toast.makeText(getActivity(), "Neuspješno slanje bodova. U toku jednog mjeseca bodove je moguće poslati maksimalno dva puta.", Toast.LENGTH_SHORT).show();
if (error.getCode().equals("-5"))
Toast.makeText(getActivity(), "Neuspješno slanje bodova. Bodove nije moguće poslati samom sebi.", Toast.LENGTH_SHORT).show();
if (error.getCode().equals("-6"))
Toast.makeText(getActivity(), "Neuspješno slanje bodova. Korisnik ne može primiti bodove.", Toast.LENGTH_SHORT).show();
if (error.getCode().equals("-100"))
Toast.makeText(getActivity(), "Neuspješno slanje bodova. Greška nepoznata.", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call<SendPointsResponse> call, Throwable t) {
Toast.makeText(getActivity(), "Uspješno slanje bodova.", Toast.LENGTH_SHORT).show();
}
});
}catch (Exception e) {
Toast.makeText(getActivity(), "Podaci nisu ispravni, provjerite podatke !", Toast.LENGTH_SHORT).show();
} }
});
}
I basicly need some idea in OnFailure method to detect if user is turned off internet and to display proper message.

You can check this link where is explained in detail if internet connection status is available usgin the ConnectivityManager through the Connectivity Service.
Notice that your app will need permissions for obtaining the network status:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Related

Intent not working with if operator Android

I try when it displays a message when I press a button to redirect me to a page, but it doesn't work. When successful, the message is displayed but does not forward me.
private void registerUser() {
try {
Account account = new Account();
account.setpAddress(edt_adress.getText().toString());
account.setpBloodGroup(edt_blood.getSelectedItem().toString());
account.setpFirstName(edt_first.getText().toString());
account.setpMidName(edt_mid.getText().toString());
account.setpFamilyName(edt_fam.getText().toString());
account.setpGender(edt_gender.getSelectedItem().toString());
account.setpPhone(edt_phone.getText().toString());
account.setpEgn(edt_egn.getText().toString());
account.setuPassword(edt_password.getText().toString());
account.setuUsername(edt_username.getText().toString());
INodeJS accountservice = RetrofitClient.getInstance().create(INodeJS.class);
Call call = accountservice.create(account);
call.enqueue(new Callback() {
#Override
public void onResponse(Call call, Response response) {
Account result = (Account) response.body();
Toast.makeText(getApplicationContext(), result.getNotes(), Toast.LENGTH_LONG).show();
if (result.getNotes().equals("Success")) {
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
}
// startActivity(intent);
}
#Override
public void onFailure(Call call, Throwable t) {
Toast.makeText(getApplicationContext(), getString(R.string.createfield), Toast.LENGTH_SHORT).show();
}
});
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
looks like result.getNotes().equals("Success") isnt true, are you shure it should be? equals is case-sensitive so "success" doesn't equal "Success" and also " Success " - note whitespaces
maybe you can try with this statement:
result.getNotes().toLowerCase(Locale.getDefault()).trim().equals("success")
toLowerCase will make all your letters small caps and trim will remove all whitespaces at beggining and end of String
also there is equalsIgnoreCase method so it may also looks like below:
result.getNotes().trim().equalsIgnoreCase("success")

Firebase not firing a success or unsuccess

I've followed the instructions exactly, in fact, I even used the code from the Firebase helper in android studio. My issue is as such, nor login or failure to login is occurring with my code! What am I missing?
public void toSubscribe(View v) {
Log.d("OK", "this part first");
String strUsername, strPassword;
strUsername = ((EditText) findViewById(R.id.username)).getText().toString();
strPassword = ((EditText) findViewById(R.id.password)).getText().toString();
if (strUsername.matches("")) {
Toast.makeText(MainActivity.this, "You did not enter a username.", Toast.LENGTH_SHORT).show();
return;
}
if (strPassword.matches("")) {
Toast.makeText(MainActivity.this, "You did not enter a password.", Toast.LENGTH_SHORT).show();
return;
}
mAuth.signInWithEmailAndPassword(strUsername, strPassword)
.addOnCompleteListener(MainActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d("TAG", "signInWithEmail:onComplete:" + task.isSuccessful());
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful()) {
Log.w("TAG", "signInWithEmail", task.getException());
Toast.makeText(MainActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
}
}
});
}
Not much else to say... I tried using a new JSON file and it still doesn't work. I've Googled tons of stuff but nothing really worked.
please check the following:
1-you install and add Gson file correctly from firebase console
2- you enable firebase authentication from firebase console
3- you mAuth initialized correctly

Paytm Integration in my application

I create sandbox account in paytm.I am using github code and pass merchant id and all parameter to paytm.please check my below code
public void onStartTransaction(View view) {
PaytmPGService Service = PaytmPGService.getStagingService();
Map<String, String> paramMap = new HashMap<String, String>();
// these are mandatory parameters
paramMap.put("ORDER_ID", ((EditText) findViewById(R.id.order_id)).getText().toString());
paramMap.put("MID", ((EditText) findViewById(R.id.merchant_id)).getText().toString());
paramMap.put("CUST_ID", ((EditText) findViewById(R.id.customer_id)).getText().toString());
paramMap.put("CHANNEL_ID", ((EditText) findViewById(R.id.channel_id)).getText().toString());
paramMap.put("INDUSTRY_TYPE_ID", ((EditText) findViewById(R.id.industry_type_id)).getText().toString());
paramMap.put("WEBSITE", ((EditText) findViewById(R.id.website)).getText().toString());
paramMap.put("TXN_AMOUNT", ((EditText) findViewById(R.id.transaction_amount)).getText().toString());
paramMap.put("THEME", ((EditText) findViewById(R.id.theme)).getText().toString());
paramMap.put("EMAIL", ((EditText) findViewById(R.id.cust_email_id)).getText().toString());
paramMap.put("MOBILE_NO", ((EditText) findViewById(R.id.cust_mobile_no)).getText().toString());
PaytmOrder Order = new PaytmOrder(paramMap);
PaytmMerchant Merchant = new PaytmMerchant(
"https://pguat.paytm.com/paytmchecksum/paytmCheckSumGenerator.jsp",
"https://pguat.paytm.com/paytmchecksum/paytmCheckSumVerify.jsp");
Service.initialize(Order, Merchant, null);
Service.startPaymentTransaction(this, true, true,
new PaytmPaymentTransactionCallback() {
#Override
public void someUIErrorOccurred(String inErrorMessage) {
Toast.makeText(getApplicationContext(), "Ui/Webview error occured.", Toast.LENGTH_LONG).show();
}
#Override
public void onTransactionSuccess(Bundle inResponse) {
Log.d("LOG", "Payment Transaction is successful " + inResponse);
Toast.makeText(getApplicationContext(), "Payment Transaction is successful ", Toast.LENGTH_LONG).show();
}
#Override
public void onTransactionFailure(String inErrorMessage,
Bundle inResponse) {
Log.d("LOG", "Payment Transaction Failed " + inErrorMessage);
Toast.makeText(getBaseContext(), "Payment Transaction Failed ", Toast.LENGTH_LONG).show();
recreate();
}
#Override
public void networkNotAvailable() {
Toast.makeText(getBaseContext(), "No Internet connection.", Toast.LENGTH_LONG).show();
}
#Override
public void clientAuthenticationFailed(String inErrorMessage) {
Toast.makeText(getBaseContext(), "Client Authentication Failed.", Toast.LENGTH_LONG).show();
}
#Override
public void onErrorLoadingWebPage(int iniErrorCode,
String inErrorMessage, String inFailingUrl) {
}
#Override
public void onBackPressedCancelTransaction() {
// TODO Auto-generated method stub
}
});
}
below attachment I pass parameter to PaytmPGService.please check attachment
after click on confirm order I got this screen please check attachment
so please check and help me...
there is also some server side implementation, make sure your chechksum is generated from server.
Several things to take care:
Confirm you supply all required arguments for checksum generation to your server.
Make sure when paytm hits your server url, it generates same checksum as it was returned back to your app.
Your credentials are configured in their staging server while testing on staging, and same on their production server.
Make sure from their side if they have enabled all required options like cc/dc etc.

Sending notifications with action buttons from one device to all users using OneSignal

I am trying to send notifications with action buttons from one device to all subscribers of my android app
here is my code
OneSignal.startInit(this)
.inFocusDisplaying(OneSignal.OSInFocusDisplayOption.Notification)
.unsubscribeWhenNotificationsAreDisabled(true)
.init();
Button onSendNotification2 = (Button)(findViewById(R.id.send_notification_button2));
onSendNotification2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
OSPermissionSubscriptionState status = OneSignal.getPermissionSubscriptionState();
try {
OneSignal.postNotification(new JSONObject("{'contents': {'en':'Tag substitution value for key1 = {{key1}}'}, " +
"'app_id':{ '61b94305-7527-4681-a257-c3851af3ab82'},"+
"'included_segments':{ ['All']},"+
"'headings': {'en': 'Tag sub Title HI {{user_name}}'}, " +
"'data': {'openURL': 'https://imgur.com'}," +
"'buttons':[{'id': 'id1', 'text': 'Go to GreenActivity'}, {'id':'id2', 'text': 'Go to MainActivity'}]}"),
new OneSignal.PostNotificationResponseHandler() {
#Override
public void onSuccess(JSONObject response) {
Toast.makeText(getApplicationContext() , " Success : "+ response.toString(), Toast.LENGTH_LONG).show();
}
#Override
public void onFailure(JSONObject response) {
Toast.makeText(getApplicationContext() , " failure : "+ response.toString(), Toast.LENGTH_LONG).show();
}
});
} catch (Exception e) {
Toast.makeText(getApplicationContext() , " exception : "+e , Toast.LENGTH_LONG).show();
}
}
});
I get Exception when I run this code , and the problem in JSONObject code , I don't know how to write it correctly .
Any help would be much appreciated .
I got the solution of my problem from OneSignal Example in Github here https://github.com/OneSignal/OneSignal-Android-SDK

Error in execution of Try/catch statement in Android

This code is used to find if a book is available or not.
Now IF the bookname for eg is Analog Electronics
and if i Enter input just as Analog or electronics it will display the full bookname Analog electronics which means that the 1st n 2nd try/catch block were executed properly.
But when i Enter input as Analog electronics with a space in between the two words it delivers an error and says "Check your internet connection " even when my internet connection is proper. It catches the error in the 1st try/catch block which should'nt have happened. I am getting an error all because of the "space".
try {
response = CustomHttpClient.executeHttpPost(
"http://duh.com/lol.php?name="+input,
postParameters);
String result = response.toString();
try{
returnString = "";
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag","ID: "+json_data.getInt("ID")+
", Bookname: "+json_data.getString("Bookname")+
);
returnString += "\n" + "Book+ json_data.getString("Bookname");
}
}
catch(JSONException e){
Toast toast = Toast.makeText(getBaseContext(), "Book is not availabe" ,Toast.LENGTH_LONG);
toast.show();
toast.getView().postDelayed(new Runnable() {
#Override
public void run() {
startActivity(new Intent(getBaseContext(), MainActivity.class));
finish();
}
}, 3500);
}
try{
tv.setText(returnString);
}
catch(Exception e){
Toast.makeText(getBaseContext(), "Error in Display" ,Toast.LENGTH_LONG).show();;
}
}
catch (Exception e) {
Toast toast = Toast.makeText(getBaseContext(), "Check your Internet connection" ,Toast.LENGTH_LONG);
toast.show();
toast.getView().postDelayed(new Runnable() {
#Override
public void run() {
startActivity(new Intent(getBaseContext(), MainActivity.class));
finish();
}
}, 3500);
};
}
LOG cat error :
04-22 20:51:52.589: E/log_tag(1322): Check your internet connection!!java.lang.IllegalArgumentException: Illegal character in query at index 52: http://duh.com/lol.php?name=analog electonics
04-22 20:51:52.759: W/EGL_emulation(1322): eglSurfaceAttrib not implemented
as per your logcat error:
04-22 20:51:52.589: E/log_tag(1322): Check your internet connection!!java.lang.IllegalArgumentException: Illegal character in query at index 52: http://duh.com/lol.php?name=analog electonics
you have an illegal character in your query.
URLs aren't allowed to have a space character in them without it being encoded (see this page for more details), so you will need to encode your query string before requesting the page.
see this SO answer for the correct way to encode a URL on Android

Categories