Requirement->
To get list of Objects Using GET Request:
passing Request headers:
X-ACCESS-TOKEN = Token received after successful sign in
X-USER-EMAIL = Email used in login.
I am using this code to login->
private void normalLoginToServer() {
final ProgressDialog progressDialog = GeneralUtil.createProgressDialog(this, "Logging into app..");
progressDialog.show();
Instead of using JSONObject, i need to pass Request Headers.
in a below Astrike code. how to pass Headers.? please help me.
***JSONObject outer_body = new JSONObject();
JSONObject body = new JSONObject();
try {
body.put(Constants.USER_EMAIL, _emailText.getText().toString().trim());
body.put(Constants.USER_PWD, _passwordText.getText().toString().trim());
outer_body.put(Constants.USER, body);***
try {
TypedInput typedInput = new TypedByteArray("text/plain", outer_body.toString().getBytes("UTF-8"));
apiService.loginToServer(typedInput, new Callback<UserInfo>() {
#Override
public void success(UserInfo response, Response response2) {
int status = response2.getStatus();
switch (status) {
case 200:
if (progressDialog.isShowing())
progressDialog.dismiss();
if (response == null)
return;
String status1 = response.getStatus();
if (status1.equalsIgnoreCase("success")) {
Toast.makeText(context, "Successful login", Toast.LENGTH_SHORT).show();
Data data = response.getData();
User user = data.getUser();
String token = user.getAccess_token();
Intent intent = new Intent(context, MainActivity.class);
intent.putExtra(Constants.ACCESS_TOKEN, token);
startActivity(intent);
finish();
} else if (status1.contains("failure")) {
Toast.makeText(context, "Username not found", Toast.LENGTH_SHORT).show();
}
break;
case 500:
Toast.makeText(context, getResources().getString(R.string.server_error), Toast.LENGTH_SHORT).show();
break;
}
}
#Override
public void failure(RetrofitError retrofitError) {
if (progressDialog.isShowing())
progressDialog.dismiss();
if (retrofitError != null) {
if (retrofitError.getKind() != null) {
if (retrofitError.getKind().equals(RetrofitError.Kind.NETWORK)) {
Toast.makeText(context, "Check your network connection and try again later",
Toast.LENGTH_SHORT).show();
}
} else if (retrofitError.getResponse() != null) {
if (retrofitError.getResponse().getStatus() == 500) {
Toast.makeText(context, getResources().getString(R.string.server_error), Toast.LENGTH_SHORT).show();
}
}
}
}
});
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Thanks in Advenced.!!
You can use #Header in your retrofit api interface. For example, something like:
void loginToServer(#Header("your_header") String yourHeaderValue, Callback<UserInfo> callback);
Assuming you want to pass static headers(those who won't change for a individual requests).
for example this code adds cache control header to /tasks request
public interface UserService {
#Headers("Cache-Control: max-age=640000")
#GET("/tasks")
List<Task> getTasks();
}
and if you need to pass dynamic headers (those changing on individual requests)
public interface UserService {
#GET("/tasks")
List<Task> getTasks(#Header("Content-Range") String contentRange);
}
More on Retrofit Add Custom Request Header
Related
i found this api here to do my job but i didint know how to apply it to my application
i know there is description but how can i apply the api to onclick method to run the ussd and get the measage to string value then deside whatever i like based on the measage. can anyone help me with step by step application?
i have tried like this
in appcompatActivity i declared
private HashMap map=new HashMap<>();
private USSDApi ussdApi;
in oncreate method
USSDController.verifyAccesibilityAccess(this);
USSDController.verifyOverLay(this);
map.put("KEY_LOGIN",new HashSet<>(Arrays.asList("koyu","waiting","loading","tinish yitebku")));
map.put("KEY_ERROR",new HashSet<>(Arrays.asList("chigir tefetrwal","problem","error","chigir")));
ussdApi = USSDController.getInstance(this);
then in onclick method
atidabira.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onClick(View v) {
String suffix = Uri.encode("#");
String ussd = "*" + "804"+suffix;
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:" + ussd));
if (checkSelfPermission(Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
String[] PERMISSIONS={Manifest.permission.CALL_PHONE};
ActivityCompat.requestPermissions((Activity) mContext,PERMISSIONS,REQUEST);
}
else {
startActivity(intent);
}
ussdApi.callUSSDInvoke(ussd, map, new USSDController.CallbackInvoke() {
#Override
public void responseInvoke(String message) {
Toast.makeText(mContext, ""+message, Toast.LENGTH_SHORT).show();
}
#Override
public void over(String message) {
}
});
}
});
all you need to do is to create a ussd Response Callback that will listen to response and use it on a Telephony.sendUssdRequest that takes three parameter (code eg *101#, the callback, and a Handler) method like this:
if (ActivityCompat.checkSelfPermission(activity, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
return;
}else{
TelephonyManager telephonyManager= (TelephonyManager)activity.getSystemService(Context.TELEPHONY_SERVICE);
Handler handler = new Handler();
TelephonyManager telephonyManagerBySlot=telephonyManager.createForSubscriptionId(slot);
TelephonyManager.UssdResponseCallback callback = new TelephonyManager.UssdResponseCallback() {
#Override
public void onReceiveUssdResponse(TelephonyManager telephonyManager, String request, CharSequence response) {
super.onReceiveUssdResponse(telephonyManager, request, response);
Log.e("ussd",response.toString());
Toast.makeText(activity, response.toString(), Toast.LENGTH_SHORT).show();
}
#Override
public void onReceiveUssdResponseFailed(TelephonyManager telephonyManager, String request, int failureCode) {
super.onReceiveUssdResponseFailed(telephonyManager, request, failureCode);
Toast.makeText(activity, "Rung USSD code", Toast.LENGTH_SHORT).show();
Log.e("ussd","failed with code " + Integer.toString(failureCode));
}
};
try {
Log.e("ussd","trying to send ussd request");
telephonyManagerBySlot.sendUssdRequest(ussdCode,
callback,
handler);
}catch (Exception e){
String msg= e.getMessage();
Log.e("DEBUG",e.toString());
e.printStackTrace();
}
}
I am using PHP JSON Volley for authenticating my login activity .Currently i am giving the localhost and IP address to test my application (Please find my code below). But when the APK is generated , what is the URL that should be given ? Kindly guide.
public class LoginActivitywithConnection extends Activity {
private static final String TAG = "LoginActivitywithConnection";
private Button btnLogin;
private Button btnLinkToRegister;
private EditText usernameEditText;
private EditText inputPassword;
private ProgressDialog pDialog;
private SessionManager session;
private DbHandler db;
String userType;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Log.i(TAG, "entered");
Intent i = this.getIntent();
Bundle data = i.getExtras();
if (data != null) {
String buttonClicked = data.getString("ButtonClicked");
if (buttonClicked.equals("asha")) {
userType = "asha";
} else if (buttonClicked.equals("anm")) {
userType = "anm";
} else if (buttonClicked.equals("doc")) {
userType = "doc";
} else if (buttonClicked.equals("sdm")) {
userType = "sdm";
}
}
usernameEditText = (EditText) findViewById(R.id.username);
inputPassword = (EditText) findViewById(R.id.password);
btnLogin = (Button) findViewById(R.id.login);
btnLinkToRegister = (Button) findViewById(R.id.register);
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
}
public void loginCLick(View view) throws SocketException {
Log.i(TAG, "entered login");
String username = usernameEditText.getText().toString().trim();
String ashaphno = username;
String password = inputPassword.getText().toString().trim();
// Check for empty data in the form
if (!ashaphno.isEmpty() && !password.isEmpty()) {
chkStatus();
// login user
checkLogin(ashaphno, password);
Log.i(TAG, "username(ashaphone)" + username);
Intent i;
}
}
// Link to Register Screen
public void clickregister(View view) {
Intent i = new Intent(getApplicationContext(),
AshaRegisterActivity.class);
startActivity(i);
finish();
}
/**
* function to verify login details in mysql db
*/
public void checkLogin(final String ashaphno, final String password) {
// Tag used to cancel the request
String tag_string_req = "req_login";
pDialog.setMessage("Logging in ...");
pDialog.show();
StringRequest strReq = new StringRequest(Request.Method.POST,
Constants.URL_LOGIN, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Login Response: " + response.toString());
pDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response.substring(response.indexOf("{"), response.lastIndexOf("}") + 1));
boolean error = jsonObject.getBoolean("error");
// Check for error node in json
if (!error) {
// user successfully logged in
// Create login session
Log.i(TAG, "loginactivity" + userType);
if (userType.equals("asha")) {
JSONObject asha = jsonObject.getJSONObject("asha");
String username = asha.getString("AshaUsername");
String phone = asha.getString("Ashaphno");
if (username.equals(phone)) {
// Launch main activity
Intent intent = new Intent(LoginActivitywithConnection.this,
LoginOpeningPageAsha.class);
Bundle b = new Bundle();
b.putString("username", ashaphno);
intent.putExtras(b);
startActivity(intent);
finish();
}
} else if
(userType.equals("anm")) {
Intent i;
i = new Intent(LoginActivitywithConnection.this, LoginOpeningPageANM.class);
Bundle b = new Bundle();
b.putString("username", ashaphno);
i.putExtras(b);
startActivity(i);
}
} else {
// Error in login. Get the error message
String errorMsg = jsonObject.getString("message");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
Log.i(TAG, "error" +
errorMsg);
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.e(TAG, "Login Error: " + volleyError.getMessage());
String message = null;
if (volleyError instanceof NetworkError) {
message = "Cannot connect to Internet...Please check your connection!";
} else if (volleyError instanceof ServerError) {
message = "The server could not be found. Please try again after some time!!";
} else if (volleyError instanceof AuthFailureError) {
message = "Cannot connect to Internet...Please check your connection!";
} else if (volleyError instanceof ParseError) {
message = "Parsing error! Please try again after some time!!";
} else if (volleyError instanceof NoConnectionError) {
message = "Cannot connect to Internet...Please check your connection!";
} else if (volleyError instanceof TimeoutError) {
message = "Connection TimeOut! Please check your internet connection.";
}
Toast.makeText(getApplicationContext(),
message, Toast.LENGTH_LONG).show();
String erroridentifier = handleServerError(volleyError, getApplicationContext());
Log.e(TAG, "Login Erroridentifier: " + erroridentifier);
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("AshaUsername", ashaphno);
params.put("ASHApwd", password);
return params;
}
};
DefaultRetryPolicy retryPolicy = new DefaultRetryPolicy(0, -1, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
strReq.setRetryPolicy(retryPolicy);
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
Constants Class :
public class Constants {
private static final String ROOT_URL ="http://192.168.43.6/Android/v1/";
// Server user login url
public static String URL_LOGIN = ROOT_URL+"ashaLogin.php";
}
When this apk is downloaded by a user , what will be the server URL(not local) ?
I will be the same URL server, if you what to make work the apk wherever it execute, you should create a public server. Azure, Google, etc, or an server with public IP.
I assume you are using some localhost and serving your PHP code to implement authentication, before releasing your android app into stores like GooglePlay you should first deploy your backend code into some servers like Azure, Digital ocean,... and after deployment and running your backend code on some server you should enter your backend's URL into your app. also I recommend you using Retrofit for your networking stuff it will decrease much of stuff you should deal with.
I need to handle a functionality based on the retrofit response.
The post method has the request as json format and getting the response as Text true
I have tried to get this response as the following code snippet. But always I get false though I get true in postman response.
private void callPostLoginAPI(String webServiceResponse) {
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
Call<ResponseBody> result = apiService.getPostDealer(postLoginAPI(webServiceResponse));
result.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
String postLoginResponse = null;
try {
postLoginResponse = response.body().string();
} catch (IOException e) {
e.printStackTrace();
}
if (postLoginResponse != null || (!postLoginResponse.equals(""))) {
if (postLoginResponse.equals("true")) {
try {
if (PreferenceClass.getInstallationID(Loginpage.this) == null ||
PreferenceClass.getInstallationID(Loginpage.this).equals("")) {
request_appInstallation_API(0);
} else {
checkAppUpdate();
}
} catch (Exception e) {
e.printStackTrace();
}
} else {
Toast.makeText(Loginpage.this, "Please contact CMS Admin", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(Loginpage.this, "Something went wrong... Please try again", Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(Loginpage.this, t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
UPDATE:
As I tried the following,and I havent gotten the respective "Postman response value" .
ApiInterface apiService = ApiClient.getClient1().create(ApiInterface.class);
Call<Boolean> result = apiService.getPostDealer(postLoginAPI(webServiceResponse));
result.enqueue(new Callback<Boolean>() {
#Override
public void onResponse(Call<Boolean> call, Response<Boolean> response) {
Log.i("Response", response.body().toString());
if (response.isSuccessful()) {
if (response.body() != null) {
Log.i("callPostLoginAPI", response.body().toString());
Toast.makeText(Dealer_Loginpage.this, "returned", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(Dealer_Loginpage.this, "Nothing returned", Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onFailure(Call<Boolean> call, Throwable t) {
Toast.makeText(Dealer_Loginpage.this, "Nothing returned", Toast.LENGTH_LONG).show();
}
});
ApiClient.getClient1() :
public static Retrofit getClient1() {
if (retrofit1 == null) {
retrofit1 = new Retrofit.Builder().baseUrl(GlobalClass.sBase_Url).
addConverterFactory(ScalarsConverterFactory.create()).
addConverterFactory(GsonConverterFactory.create()).build();
}
return retrofit1;
}
Solution:
Attach this:
postLoginResponse.replaceAll("[^A-Za-z]+", "");
After the line:
postLoginResponse = response.body().string();
and try.
I am new to firebase. I tried to store user data in firebase database using volley. However, firebase has no response regarding my volley request and the database still is null. This is the tutorial I followed.
This is the volley request I used to connect firebase.
public void executeFirebase(){
StringRequest request = new StringRequest(Request.Method.GET, FIREBASE_REGISTER_URL, new Response.Listener<String>(){
#Override
public void onResponse(String s) {
Firebase reference = new Firebase("https://tradeal-930ad.firebaseio.com/users");
if(s.equals("null")) {
reference.child(name).child("password").setValue(password);
Toast.makeText(activity, "registration successful 1", Toast.LENGTH_LONG).show();
}
else {
try {
JSONObject obj = new JSONObject(s);
if (!obj.has(name)) {
reference.child(name).child("password").setValue(password);
Toast.makeText(activity, "registration successful 2", Toast.LENGTH_LONG).show();
Intent intent = new Intent(activity, MainPageActivity.class);
activity.startActivity(intent);
activity.finish();
loginUserActivity.finish();
} else {
Toast.makeText(activity, "username already exists", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
loading.dismiss();
}
},new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError volleyError) {
System.out.println("" + volleyError );
loading.dismiss();
}
});
RequestQueue rQueue = Volley.newRequestQueue(activity);
rQueue.add(request);
}
change the rules of your database to public
{
"rules" :
{
".read" : true,
".write" : true
}
}
otherwise
{
"error" : "Permission denied"
}
this will be your response
to know more about rules you can visit security rules
Hey developers i am tried send the data through intent
i am sending data A activity to B activity data is send A Activity properly but B Activity is not receive but some data is receive but some data not receive
Code is A Activity
private void requestForSMS(final String mobile) {
StringRequest strReq = new StringRequest(Request.Method.POST,
config.Config.URL_REQUEST_SMS, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, response.toString());
try {
JSONObject responseObj = new JSONObject(response);
final String user = responseObj.getString("uid");
String message = responseObj.getString("msg");
Intent intent1 = new Intent(getApplicationContext(),HttpService.class);
intent1.putExtra("uid", user); // <---Sending data here this data not recive B Activity ------>
Log.d("user id going","====>"+user);
if(!user.equalsIgnoreCase("")){
pref.setIsWaitingForSms(true);
viewPager.setCurrentItem(1);
txtEditMobile.setText(pref.getMobileNumber());
layoutEditMobile.setVisibility(View.VISIBLE);
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(),
"ErrorToast: " + message,
Toast.LENGTH_LONG).show();
}
// hiding the progress bar
progressBar.setVisibility(View.GONE);
} catch (JSONException e) {
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
progressBar.setVisibility(View.GONE);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "ErrorResponce: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("key","xxxxxxxxxxxxx");
params.put("mobile", mobile);
Log.e(TAG, "Posting params: " + params.toString());
return params;
}
};
int socketTimeout = 60000;
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
strReq.setRetryPolicy(policy);
// Adding request to request queue
newapp.getInstance().addToRequestQueue(strReq);
}
private void verifyOtp() {
String otp = inputOtp.getText().toString().trim();
if (!otp.isEmpty()) {
Intent grapprIntent = new Intent(getApplicationContext(), HttpService.class);
// <---- sending data here also B Activity---->
grapprIntent.putExtra("key","xxxxxxxxxxxx");
grapprIntent.putExtra("mobileverify", otp);
startService(grapprIntent);
} else {
Toast.makeText(getApplicationContext(), "Please enter the OTP", Toast.LENGTH_SHORT).show();
}
}
private static boolean isValidPhoneNumber(String mobile) {
String regEx = "^[0-9]{10}$";
return mobile.matches(regEx);
}
B Activity
public class HttpService extends IntentService {
private static String TAG = HttpService.class.getSimpleName();
public HttpService() {
super(HttpService.class.getSimpleName());
}
#Override
protected void onHandleIntent(Intent intent) {
if (intent != null) {
String otp = intent.getStringExtra("mobileverify");
final String user1 = intent.getStringExtra("uid"); //<---- this is not recive value ---->
verifyOtp(otp,user1);
}
}
/**
* Posting the OTP to server and activating the user
*
* #param otp otp received in the SMS
*/
private void verifyOtp(final String otp, final String user1){
StringRequest strReq = new StringRequest(Request.Method.POST,
config.Config.URL_VERIFY_OTP, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, response.toString());
try {
JSONObject responseObj = new JSONObject(response);
// Parsing json object response
// response will be a json object
String message = responseObj.getString("msg");
if (message!="") {
// parsing the user profile information
JSONObject profileObj = responseObj.getJSONObject(response);
String mobile = profileObj.getString("mobile");
PrefManager pref = new PrefManager(getApplicationContext());
pref.createLogin(mobile);
Intent intent = new Intent(HttpService.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
Toast.makeText(getApplicationContext(), "HTTPIF"+message, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "HTTPELSE"+message, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "HTTPError: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
}
}) {
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("key","xxxxxxxxxx");
params.put("mobileverify", otp);
params.put("uid",user1); // here its given error
Log.e(TAG, "Posting params: " + params.toString());
return params;
}
};
MyApplication.getInstance().addToRequestQueue(strReq);
}
Please Help me Thanks
Your grapprIntentdoesn't contain a value for "uid" key because you don't put it. You use some intent1 which is not used anywhere more. Instead you need to put "uid" into grapprIntent:
grapprIntent.putExtra("uid", user);
Maybe grapprIntent should be global variable for the class or find a way to pass it between methods.
Create A Global variable in your Application class and Use set and get Methods
like this
Application.class
private String user;
public String setuser(String usermy) {
this.user = usermy;
return null;
}
public String getuser()
{
return user;
}
where you want to send value set value like as your code
SMSActivity
MyApplication myUser = (MyApplication)getApplicationContext();
#Override
public void onResponse(String response) {
Log.d(TAG, response.toString());
try {
JSONObject responseObj = new JSONObject(response);
String user = responseObj.getString("uid");
String user1 = myUser.setuser(user);
And Get Value in your HttpService.class
Like this
MyApplication uidinfo = (MyApplication)getApplicationContext();
final String user = uidinfo.getuser();
and mention manifest.xml inside Application tag
<application
android:name=".MyApplication"
/>
happy coding