How to show image fetched from mysqldatabase to imageview - android

Here this is the layout in which I have to set the image of the user who successfully logged in
and I have saved the url of the image in the table where all the details of the users are there....
So what I was trying is I am fetching the url of the image from the database and then tried to set it into imageview.. I have checked that the url is comming to the variable...
so as you can see in the above image it is not setting the image in imageview but when I assign the url first to the imgurl variable at the time of defining the variable then it works fine...
I don't know why this is happening... am I doing anything wrong or is there any other way to achieve this?
This is the code of the file...
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
public class Dashboard extends AppCompatActivity {
TextView usrname;
ImageView profileimg;
public static String imgurl = "";//here
/**
* Shared Preferences
**/
SharedPreferences sharedPreferences;
public static final String mypreference = "mypref";
public static final String Name = "nameKey";
public static final String Email = "emailKey";
/**
* Shared Preferences
**/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
profileimg = findViewById(R.id.iv_display_image);
usrname = findViewById(R.id.tv_username);
/**Shared Preferences**/
sharedPreferences = getSharedPreferences(mypreference,
Context.MODE_PRIVATE);
/**Shared Preferences**/
//fetching session data
String name = sharedPreferences.getString(Name, "0");
usrname.setText(name);
fetchimg(name);
LoadImage loadImage = new LoadImage(profileimg);
Log.d("Oncreate img url", imgurl);
loadImage.execute(imgurl);
}
private void fetchimg(String name) {
StringRequest request = new StringRequest(Request.Method.POST, "https://**url**//fetchimg.php", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response.startsWith("Here")) {
String urlstr = getUrl(response, "Here ");
seturl(urlstr);
Log.d("urlstr value:", urlstr);
} else {
Toast.makeText(getApplicationContext(), response, Toast.LENGTH_SHORT).show();
Log.d("vOLLEY ERROR", response.toString());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
Log.d("vOLLEY ERROR", error.getMessage().toString());
}
}
) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("login_name", "xxxxx");
params.put("login_pass", "xxxxx");
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(Dashboard.this);
requestQueue.add(request);
}
private void seturl(String urlstr) {
this.imgurl = urlstr;
Log.d("Image url set inside seturl", imgurl);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.dashboardmenu, menu);
return true;
}
public void openeditprofile(View view) {
startActivity(new Intent(this, EditProfileActivity.class));
}
private class LoadImage extends AsyncTask<String, Void, Bitmap> {
ImageView imageView;
public LoadImage(ImageView profileimg) {
this.imageView = profileimg;
}
#Override
protected Bitmap doInBackground(String... strings) {
String urlLink = strings[0];
Bitmap bitmap = null;
try {
InputStream inputStream = new java.net.URL(urlLink).openStream();
bitmap = BitmapFactory.decodeStream(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
#Override
protected void onPostExecute(Bitmap bitmap) {
profileimg.setImageBitmap(bitmap);
}
}
public static String getUrl(String string, String word) {
// Check if the word is present in string
// If found, remove it using removeAll()
if (string.contains(word)) {
// To cover the case
// if the word is at the
// beginning of the string
// or anywhere in the middle
String tempWord = word + " ";
string = string.replaceAll(tempWord, "");
// To cover the edge case
// if the word is at the
// end of the string
tempWord = " " + word;
string = string.replaceAll(tempWord, "");
}
// Return the resultant string
return string;
}
}

You are fetching image asynchronously, your Asynctask execute will be called with empty imgUrl as it not already fetched, move AsyncTask execution code in onResponse of fetching
private void fetchimg(String name) {
StringRequest request = new StringRequest(Request.Method.POST, "https://**url**//fetchimg.php", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response.startsWith("Here")) {
String urlstr = getUrl(response, "Here ");
seturl(urlstr);
//here the url is ready to consume
Log.d("urlstr value:", urlstr);
//load the image now
LoadImage loadImage = new LoadImage(profileimg);
Log.d("Oncreate img url", imgurl);
loadImage.execute(imgurl);
} else {
Toast.makeText(getApplicationContext(), response, Toast.LENGTH_SHORT).show();
Log.d("vOLLEY ERROR", response.toString());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
Log.d("vOLLEY ERROR", error.getMessage().toString());
}
}
) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("login_name", "xxxxx");
params.put("login_pass", "xxxxx");
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(Dashboard.this);
requestQueue.add(request);
}

use **Glide** to display Image from Url into image view.
You have to add glide lib in app-level build.gradle file.
implementation 'com.github.bumptech.glide:glide:4.12.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.12.0'
Glide.with(this).load(url)
.transform(CenterCrop(), RoundedCorners(radius))
.placeholder(R.drawable.drawable_image_placeholder)
.error(R.drawable.drawable_image_placeholder)
.into(ivProfile)
drawable_image_placeholder is the default imageview that displays
when getting the error to load the image. ivProfile is imageview .

Related

Android volley token changes every request

I want to get the results about imei adresses after my inquiry on the inquiry site. The site has token input during the query and I can get this token as follows. But when i run the second volley queue i soppose the token changes and the result doesn't come. How can I solve this problem. The site that i questioned the imei adress and my codes are below.
package com.myapp.query;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import android.os.Bundle;
import android.widget.Toast;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import androidx.appcompat.app.AppCompatActivity;
public class imeiSorgulama extends AppCompatActivity {
StringRequest stringRequest;
RequestQueue queue;
String token, tag, value, tag2, value2, result;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_imei_sorgulama);
queue = Volley.newRequestQueue(this);
final String url = "https://www.turkiye.gov.tr/imei-sorgulama";
stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
tag = "<input type=\"hidden\" name=\"token\" value=\"";
value = response.substring(response.indexOf(tag) + tag.length());
token = value.substring(0, value.indexOf("\""));
try {
token = URLEncoder.encode(token,"UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
imeiQuery();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(imeiSorgulama.this, error+"", Toast.LENGTH_SHORT).show();
}
}
);
queue.add(stringRequest);
}
private void imeiQuery() {
final String url = "https://www.turkiye.gov.tr/imei-sorgulama?submit";
stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
tag2 = "<dl class=\"compact\">";
value2 = response.substring(response.indexOf(tag2) + tag2.length());
result = value2.substring(0, value2.indexOf("</dl>"));
Toast.makeText(imeiSorgulama.this, result+"", Toast.LENGTH_SHORT).show();
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(imeiSorgulama.this, error+"", Toast.LENGTH_SHORT).show();
}
}
) {
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("txtImei", "545454545454545");
params.put("token=", token);
return params;
}
};
queue.add(stringRequest);
}
}

Run a piece of code only once in background whenever user login

Ia trying to get user locations whenever its login the application.I made a class and its working perfect seperately but when I embed it in my main project it didnt submit the location values in database.I want that whenever user login that class run for only once and submits its coordinates in database.
Here Is the code of my location class :
I want that when user login this class class run for once only all I want is to get user location when its loged in.
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import java.util.HashMap;
import java.util.Map;
public class getposition extends AppCompatActivity {
String URL_LOGIN = "api"
Button btn;
TextView tv1,tv2;
LocationManager locationManager;
static final int REQUEST_LOCATION = 1;
String lg, lt , chk;
String lat_long;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_getposition);
btn = findViewById(R.id.send);
tv1 = findViewById(R.id.lang);
tv2 = findViewById(R.id.lat);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
chk = getLocation();
loadlocation();
if(chk != "false"){
String foo = chk;
String[] split = foo.split("_");
lt = split[0];
lg = split[1];
Toast.makeText(getApplicationContext(),chk,Toast.LENGTH_LONG).show();
}
}
private void loadlocation() {
final RequestQueue requestQueue = Volley.newRequestQueue(getposition.this);
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_LOGIN, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
tv1.setText(response);
tv2.setText(response);
requestQueue.stop();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
tv1.setText("Something went wrong///");
error.printStackTrace();
requestQueue.stop();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("user_id","12" );
params.put("user_lat", lt);
params.put("user_lng", lg);
return params;
}
};
VolleySingleton.getInstance(getposition.this).addToRequestQueue(stringRequest);
}
public String getLocation() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED)
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION);
else {
Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
double latt = location.getLatitude();
double lng = location.getLongitude();
lat_long = latt + "_" + lng;
tv1.setText("Latitude: " + latt);
tv2.setText("Longitude: " + lng);
} else {
lat_long = "false";
tv1.setText("Unable to find correct location.");
tv2.setText("Unable to find correct location. ");
}
}
return lat_long;
}
}
This is my login class:
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
import com.vshine.neuron.riseshine.VolleySingleton;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.vshine.neuron.riseshine.MainActivity;
import com.vshine.neuron.riseshine.R;
import com.vshine.neuron.riseshine.getregistered;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class login extends AppCompatActivity {
Button login_button;
ImageButton GetRegistered;
EditText userName_edt, password_edt;
String user_name, password;
Context mctx;
String json_response;
String URL_LOGIN = "api"
public static final String PREFS_NAME = "MyPreferenceFiles";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mctx = this;
initBasic();
initLogin();
}
private void initBasic() {
login_button = (Button) findViewById(R.id.login_button);
GetRegistered = (ImageButton) findViewById(R.id.register);
userName_edt = (EditText) findViewById(R.id.user_name);
password_edt = (EditText) findViewById(R.id.password);
}
private void initLogin() {
GetRegistered.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent= new Intent(login.this,getregistered.class);
startActivity(intent);
}
});
login_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
user_name = userName_edt.getText().toString();
password = password_edt.getText().toString();
if (user_name.trim().equals("") || password.trim().equals("")) {
ShowToastMessage("Please enter the credentials properly");
}
else {
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_LOGIN,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//converting response to json object
JSONObject obj = new JSONObject(response);
//if no error in response
// json_response = j_obj.getString("message");
if (response!= null) {
// Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();
json_response = obj.getString("message");
// ShowToastMessage(json_response);
//getting the user from the response
JSONObject userJson = obj.getJSONObject("response");
//creating a new user object
String u_id = String.valueOf(userJson.getInt("id"));
// ShowToastMessage(u_id);
//storing the user in shared preferences
SharedPreferences.Editor editor = getSharedPreferences(PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("User_id", u_id);
editor.commit();
finish();
startActivity(new Intent(getApplicationContext(), MainActivity.class));
} else {
Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("user_name", user_name);
params.put("password", password);
return params;
}
};
VolleySingleton.getInstance(login.this).addToRequestQueue(stringRequest);
}
}
});
}
private void ShowToastMessage(String message) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
}

How to login with outlook/microsoft using webview?

There are libraries available for login with outlook using a browser (especially chrome browser i.e. MSAL android library ) OR ADAL, but I don't want to log-in with chrome because in my device chrome is not available (Its custom OS flashed in an android device).
I have tried on my end also but its not working as this code is giving access token but not useful to call graph API
here is my code
package learn2crack.weboauth2;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.util.Log;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends Activity implements View.OnClickListener {
private static final String TAG = "MainActivity";
//Change the Scope as you need
WebView web;
Button auth;
SharedPreferences pref;
TextView Access;
String authCode = "";
private Dialog auth_dialog;
private Button authEbay;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pref = getSharedPreferences("AppPref", MODE_PRIVATE);
Access =(TextView)findViewById(R.id.Access);
auth = (Button)findViewById(R.id.auth);
auth.setOnClickListener(this);
authEbay = (Button)findViewById(R.id.auth_ebay);
auth.setOnClickListener(this);
authEbay.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.auth:
auth(Constants.OUTLOOK.USER_AGENT,
Constants.OUTLOOK.OAUTH_URL,
Constants.OUTLOOK.REDIRECT_URI,
Constants.OUTLOOK.CLIENT_ID,
Constants.OUTLOOK.OAUTH_SCOPE);
break;
case R.id.auth_ebay:
auth(Constants.EBAY.USER_AGENT,
Constants.EBAY.OAUTH_URL,
Constants.EBAY.REDIRECT_URI,
Constants.EBAY.CLIENT_ID,
Constants.EBAY.OAUTH_SCOPE);
break;
}
}
private void auth(String userAgent, String oauthUrl, String redirectUri, String clientId,
String oauthScope) {
final Dialog auth_dialog;
// TODO Auto-generated method stub
auth_dialog = new Dialog(MainActivity.this);
auth_dialog.setContentView(R.layout.auth_dialog);
web = (WebView)auth_dialog.findViewById(R.id.webv);
web.getSettings().setJavaScriptEnabled(true);
WebSettings webSettings = web.getSettings();
web.getSettings().setUserAgentString(userAgent);
webSettings.setSupportMultipleWindows(true);
web.loadUrl(oauthUrl+"?redirect_uri="+
redirectUri+"&response_type=code&client_id="+
clientId+"&scope="+ oauthScope);
web.setWebViewClient(new WebViewClient() {
boolean authComplete = false;
Intent resultIntent = new Intent();
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon){
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if (url.contains("?code=") && authComplete != true) {
Uri uri = Uri.parse(url);
authCode = uri.getQueryParameter("code");
callGraphAPI(authCode);
Log.i("", "CODE : " + authCode);
authComplete = true;
resultIntent.putExtra("code", authCode);
auth_dialog.dismiss();
Toast.makeText(getApplicationContext(),"Authorization Code is: "
+authCode, Toast.LENGTH_SHORT).show();
}else if(url.contains("error=access_denied")){
Log.i("", "ACCESS_DENIED_HERE");
Toast.makeText(getApplicationContext(), "Error Occured",
Toast.LENGTH_SHORT).show();
auth_dialog.dismiss();
}
}
});
auth_dialog.show();
auth_dialog.setTitle("Authorize Learn2Crack");
auth_dialog.setCancelable(true);
}
private void callGraphAPI(final String code)
{
Log.d(TAG, "Starting volley request to graph");
/* Make sure we have a token to send to graph */
RequestQueue queue = Volley.newRequestQueue(this);
JSONObject parameters = new JSONObject();
try {
parameters.put("key", "value");
} catch (Exception e) {
Log.d(TAG, "Failed to put parameters: " + e.toString());
}
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, Constants.OUTLOOK.MSGRAPH_URL,
parameters,new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
/* Successfully called graph, process data and send to UI */
Log.d(TAG, "Response: " + response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "Error: " + error.toString());
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap();
headers.put("Authorization", "Bearer " + authCode);
return headers;
}
};
Log.d(TAG, "Adding HTTP GET to Queue, Request: " + request.toString());
request.setRetryPolicy(new DefaultRetryPolicy(
3000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(request);
}
}
anybody please suggeest how to get proper access token after login with microsoft/outlook using webview.
Thanks in advance.

Pass params Using GET method using volley library

How can we pass params from editText to url using request.GET method.
Actually I am trying to pass an email address as parameter to a api which should b attached to api-url .
I came to know from here that getParams() is not called on the GET method, so it seems you'll have to add it to the URL before you send the request.
suggest me any solution to achieve the task ..
when i pass REG_URL="http://ec2-54-147-238-136.compute-1.amazonaws.com/hmc/api/registeruser?email=ameer#novatoresols.com";
it return success=true response as expected because is registered user
but if i set REG_URL="http://ec2-54-147-238-136.compute-1.amazonaws.com/hmc/api/registeruser and pass the params (get value from edittext and use params.put in getparams() method ).response is always success=false i.e params is not attached to url
here is my code.
package com.example.mts3.hammadnewsapp;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.provider.SyncStateContract;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
public class RegisterActivity extends AppCompatActivity {
Button btn_verf;
EditText et_Email;
String u_emails,stat;
AlertDialog.Builder alertDialog;
private static final String TAG = "LoginActivity";
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
Context context;
// public static String firstname, lastname, useremail, userphone, userpass;
// String REG_URL="http://ec2-54-147-238-136.compute-1.amazonaws.com/hmc/api/registeruser?email=ameer#novatoresols.com";
String REG_URL="http://ec2-54-147-238-136.compute-1.amazonaws.com/hmc/api/registeruser";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
btn_verf=findViewById(R.id.btn_reg_send_vf_code);
et_Email=findViewById(R.id.et_reg_email);
alertDialog =new AlertDialog.Builder(RegisterActivity.this);
// u_emails=et_Email.getText().toString().trim();
btn_verf.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
callApi();
}
});
}
private void callApi() {
// Log.e(TAG, "onClick: ");
/*if (!utility.isInternetConnected()) {
Toast.makeText(LoginActivity.this, "Please check your internet connection.", Toast.LENGTH_SHORT).show();
return;
}*/
// dialog = utility.showProgressDialog(LoginActivity.this, "Please wait");
final String email = et_Email.getText().toString().trim();
// Log.e(TAG, "onClick: email = " + email );
// JSONObject params = new JSONObject();
/*
HashMap<String,String> params=new HashMap<>();
params.put("email",email);*/
/*try {
// params.getString("email");
params.put("email",email);
Log.e(TAG, "getParams: param = " + "try of put prams");
} catch (JSONException e){
Log.e(TAG, "getParams: param = " + "catch of put prams");
e.printStackTrace();
}*/
RequestQueue queue = Volley.newRequestQueue(RegisterActivity.this);
StringRequest stringRequest = new StringRequest(Request.Method.GET, REG_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(RegisterActivity.this, "REsponse: " + response, Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String,String> params=new HashMap<>();
// params.put("email",email);
params.put("email",email);
return params;
}
}; queue.add(stringRequest);
}
}
As suggested by #Puneet worked for me which is as :
getParams is only called for POST requests. GET requests don't have a body and hence, getParams is never called. For a simple request like yours just add the parameters to your URL and use that constructed URL to make that request to your server (REG_URL + "?email=" + email).
To pass the parameters, you need to create a class for the key-value pairs.
1) Create a class KeyValuePair with two fields key and value with appropriate constructor and getter-setter methods.
2) Now, for each parameter, you need to create an object of this class, i.e., for a key username with value user#gmail.com, the object would be new KeyValuePair("username", "user#gmail.com").
3) Now, you need to create a List to store these parameters and pass this list to the below method with your base url,
public static String generateUrl(String baseUrl, List<KeyValuePair> params) {
if (params.size() > 0) {
for (KeyValuePair parameter: params) {
if (parameter.getKey().trim().length() > 0)
baseUrl += "&" + parameter.getKey() + "=" + parameter.getValue();
}
}
return baseUrl;
}
4) Pass this baseUrl to your Request.

API calling when phone local language is Arabic in android

I am working on an android project, in which i have to call APIs in english when mobile local language is Arabic. i am not getting API URl String in English.
My API calling file(PackageapiCall.class) is as follows:
package com.example.app.roamer.utils;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Looper;
import android.util.Log;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.example.app.roamer.Constant;
import com.example.app.roamer.R;
import com.example.app.roamer.activities.SplashScreen;
import com.example.app.roamer.app.AppController;
import com.example.app.roamer.fragments.AlltripsFragment;
import com.example.app.roamer.helper.DateFormatsHelper;
import com.example.app.roamer.fragments.TaTripsFragment;
import com.example.app.roamer.models.AllTrips;
import com.example.app.roamer.tasks.GenerateTokenOperation;
import com.example.app.roamer.tasks.ParsingOperation;
import java.text.DateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import static com.example.app.roamer.activities.HomeActivity.TAG;
/**
* Created by manish on 22-12-2016.
*/
public class PackageApicalls {
private Request.Priority priority = Request.Priority.HIGH;
Context ctx;
private List<AllTrips.TripsBean> allTripsByMobileUserIDNewData, allTripsByMobileUserIDNewData1;
AlltripsFragment alltripsFragment;
TaTripsFragment taTripsFragment;
Boolean splashScreenApiCall=false;
SharedPreferences sharedPreferences;
private int mobileUserId;
public PackageApicalls(Context ctx, AlltripsFragment alltripsFragment) {
this.ctx=ctx;
this.alltripsFragment=alltripsFragment;
}
public PackageApicalls(Context ctx, TaTripsFragment taTripsFragment) {
this.ctx=ctx;
this.taTripsFragment=taTripsFragment;
}
public PackageApicalls(Context ctx) {
this.ctx=ctx;
}
public void getalltripdetails() {
// String gettodaysdate="02-02-2016";
DateFormatsHelper dateFormatsHelper = new DateFormatsHelper();
String gettodaysdate = dateFormatsHelper.gettodaysdate();
sharedPreferences = ctx.getSharedPreferences(Constant.MyPREFERENCES, Context.MODE_PRIVATE);
mobileUserId = sharedPreferences.getInt("mobileUserId", 0);
//mobileUserId=1;
String url = ctx.getResources().getString(R.string.alltrips_api_url,mobileUserId,gettodaysdate);
Log.d(TAG, "manish-url-packageapicalls"+url);
StringRequest postRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (Looper.myLooper() == Looper.getMainLooper()) {
Log.d(TAG, "main thread-true");
} else {
Log.d(TAG, "main thread-false");
}
// response
Log.d("Response", response);
allTripsByMobileUserIDNewData = parsejson(response);
// setupui(allTripsByMobileUserIDNewData);
Log.d("manishbutola", "onResponse: New Data arrived");
// pDialog.hide();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
Log.d("manishbutola", "getalltripdetailserror => " + error.toString());
new GenerateTokenOperation(ctx).execute();
if(new GenerateTokenOperation(ctx).getStatus()== AsyncTask.Status.FINISHED){
getalltripdetails();
}
/*if(GenerateTokenOperation(ctx).Status == AsyncTask.Status.FINISHED){
// START NEW TASK HERE
}*/
}
}
) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
sharedPreferences = ctx.getSharedPreferences(Constant.MyPREFERENCES, Context.MODE_PRIVATE);
String token_value = sharedPreferences.getString("token", null);
String authorizedtoken = "bearer" + " " +token_value;
//params.put("User-Agent", "Nintendo Gameboy");
Log.d("packageApiCalls", "authorizedtoken: "+ authorizedtoken);
params.put("Authorization", authorizedtoken);
return params;
}
#Override
public Priority getPriority() {
return priority;
}
};
AppController.getInstance().addToRequestQueue(postRequest);
//return parsejson;
// List<AllTrips.TripsBean> allTrips=db.getAllTripsByMobileUserID(1);
}
private List<AllTrips.TripsBean> parsejson(String response) {
try {
if(Constant.splashScreenApiCall){
new ParsingOperation(ctx).execute(response);
}
else{
new ParsingOperation(ctx,alltripsFragment).execute(response);
}
} catch (Exception e) {
e.printStackTrace();
}
return allTripsByMobileUserIDNewData1;
}
}
My `gettodaydate` method as follows:
public String gettodaysdate(){
DateFormat formatter;
formatter = new SimpleDateFormat("MM-dd-yyyy",Locale.ENGLISH);
String result = formatter.format(new Date());
/*DateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy");
Date date = new Date();*/
// return dateFormat.format(date);
return result;
}
and finally my string.xml :
<string name="alltrips_api_ta_url" translatable="false">http://roamer.techmaster.in/Rest/api/GetAgentTrips?agentId="%1$d"&isPreviousTrip=false&date="%2$s"</string>
I ma getting log cat as:
Unexpected response code 400 for http://roamer.techmaster.in/Rest/api/GetTrips?mobileUserId=١&isPreviousTrip=false&date=02-14-2017
as i am seeing that mobileUserId is 1 and it is going to convert in url in Arabic when url going to hit to server. app going to crash.Please help me out.Thanks.
After struggle i got an idea and it worked, it is:
i change int to string like:
String userId = String.valueOf(mobileUserId); and then i do
<string name="alltrips_api_ta_url" translatable="false">http://base_url/trips?agentId="%1$d"&isPreviousTrip=false&date="%2$s"</string>
to
<string name="alltrips_api_ta_url" translatable="false">http://base_url/GetAgentTrips?agentId="%1$s"&isPreviousTrip=false&date="%2$s"</string>
and then i put
String url = ctx.getResources().getString(R.string.alltrips_api_url,userId ,gettodaysdate);
in your getHeaders() add the Content-Type
#Override
public Map<String,String> getHeaders() throws AuthFailureError {
HashMap<String,String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
Also override getBodyContentType() and return "application/x-www-form-urlencoded; charset=UTF-8";
#Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded; charset=UTF-8";
}

Categories

Resources