I'm working on an Android app and currently stuck to link my database to my app for registration using volley but I get the problem:
this is response:
com.android.volley.NoConnectionError:java.io.IOEXCEPTION: Cleartext HTTP traffic to 10.0.2.2 not permitted
Here is my MainActivity code:
public class MainActivity extends AppCompatActivity {
Button loginBtn;
EditText password, username;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
password = findViewById(R.id.pssword);
username = findViewById(R.id.username);
loginBtn = findViewById(R.id.check);
loginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
login();
}
});
}
void login() {
StringRequest request = new StringRequest(Request.Method.POST,
"http://10.0.2.2:80/android/test.php", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(getApplicationContext(), "this is response: " + response,
Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "this is response: " + error,
Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("username", "hicham");
params.put("password", "hello");
return params;
}
};
Volley.newRequestQueue(this).add(request);
}
}
Please add the usesCleartextTraffic="true" tag in your AndroidManifest.xml accordingly to fix this issue.
<application
android:usesCleartextTraffic="true"
</application>
This issue occurs because you are trying to access an http url instead of https and there are new restrictions regarding this lately. Hence, only after adding the tag I mentioned, your HTTP requests will work.
Happy coding! :)
Using Volley, I was able to make a asynchronous HTTP GET call to my API that i wanted to hit. But it is taking 15 to 20 seconds to fetch the data and populate it on the UI, Staggered Grid Layout using Recycler View.
For every search call I make, it roughly takes that much time which is bad. How do I reduce this latency? I also added the RequestQueue but no luck.
I'm initializing the Adapter after the search call is made. Is it a good approach to do it there? Or would you recommend doing it in onCreate method of activity. Could anyone please guide what's the cause for this latency?
Here's the excerpt from the code
public class StaggeredSearchActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private StaggeredGridLayoutManager staggeredGridLayoutManager;
private StaggeredGridAdapter staggeredGridAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_staggered_search);
Intent intent = getIntent();
String searchText = intent.getStringExtra("searchText");
getSearchData(searchText);
recyclerView = findViewById(R.id.staggered_recycler_view);
staggeredGridLayoutManager = new StaggeredGridLayoutManager(2, LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(staggeredGridLayoutManager);
}
private void getSearchData(String searchText) {
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
String url = "https://my-json-server.typicode.com/typicode/demo/comments";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
ArrayList<StaggeredCustomCard> dataset = new ArrayList<>();
#Override
public void onResponse(JSONObject response) {
try {
JSONArray array = response.getJSONArray("tweets");
for (int i = 0; i < array.length(); i++) {
JSONObject jsonObject = array.getJSONObject(i);
String body = jsonObject.getString("body");
String postId = jsonObject.getString("postId");
dataset.add(new StaggeredCustomCard(body, postId);
}
staggeredGridAdapter = new StaggeredGridAdapter(StaggeredSearchActivity.this, dataset);
recyclerView.setAdapter(staggeredGridAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO: Handle error
...
}
});
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(50000, 5, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(jsonObjectRequest);
}
}
I am new to Android and I am using JAVA and Android studio. I have to use the WooCommerce API to get the list of all orders:
wp-json/wc/v2/orders
Is this possible using the volley library and if yes, how can I call this and get the response (I have my client_id and client_secret)?
Here is my activity page:
public class YourOrders extends AppCompatActivity {
private TextView textViewback;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_your_orders);
getSupportActionBar().hide();
textViewback = (TextView) findViewById(R.id.textViewback);
textViewback.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
}}
String url = "https://www.example.com/wp-json/wc/v2/orders?consumer_key=123&consumer_secret=abc";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
textViewback.setText("Response: " + response.toString());
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO: Handle error
}
});
// Access the RequestQueue through your singleton class.
MySingleton.getInstance(this).addToRequestQueue(jsonObjectRequest);
I'm trying to parse the value in this JSON url using Volley, however I'm getting a null returned from the response: http://free.currencyconverterapi.com/api/v3/convert?q=CAD_USD&compact=ultra
{"CAD_USD":0.78246}
All I am trying to do is display the value of the JSON in my textview.
The error I get:
java.lang.NullPointerException: Attempt to invoke virtual method 'double java.lang.Double.doubleValue()' on a null object reference
I'm not sure if I'm fetching the JSON data correctly.
What I have so far:
public class MainActivity extends AppCompatActivity {
RequestQueue rq;
Double conversionDouble;
String url = "http://free.currencyconverterapi.com/api/v3/convert?q=CAD_USD&compact=ultra";
private Spinner toSpinner, fromSpinner;
private Button convertBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addItemsOnToSpinner();
addListenerOnButton();
jsonSendRequest();
Button convertBtn = (Button) findViewById(R.id.convertBtn);
final EditText fromAmountEditText = findViewById(R.id.fromAmountEditText);
convertBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView toAmountTextView = findViewById(R.id.toAmountTextView);
String result = Double.toString(conversionDouble);
toAmountTextView.setText(result);
}
});
Spinner toSpinner = (Spinner) findViewById(R.id.toSpinner);
Spinner fromSpinner = (Spinner) findViewById(R.id.fromSpinner);
String toSpinnerText = toSpinner.getSelectedItem().toString();
String fromSpinnerText = fromSpinner.getSelectedItem().toString();
rq = Volley.newRequestQueue(this);
}
public void jsonSendRequest() {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
conversionDouble = response.getDouble("CAD_USD");
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
}
public void addItemsOnToSpinner(){
Spinner toSpinner = (Spinner) findViewById(R.id.toSpinner);
Spinner fromSpinner = (Spinner) findViewById(R.id.fromSpinner);
List<String> currency = new ArrayList<String>();
currency.add("USD");
currency.add("CAD");
currency.add("CNY");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item, currency
);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
toSpinner.setAdapter(dataAdapter);
fromSpinner.setAdapter(dataAdapter);
}
public void addListenerOnButton() {
Spinner fromSpinner = (Spinner) findViewById(R.id.fromSpinner);
Spinner toSpinner = (Spinner) findViewById(R.id.toSpinner);
Button convertBtn = (Button) findViewById(R.id.convertBtn);
}
}
Any help is appreciated.
//Replace your method with below
public void jsonSendRequest() {
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://free.currencyconverterapi.com/api/v3/convert?q=CAD_USD&compact=ultra";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject jsonobject = new JSONObject(response);
if(jsonobject.has("CAD_USD")){
conversionDouble = jsonobject.getDouble("CAD_USD");
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
}
I have crated login application which is a part of my native application building process.There are few end points which uses login session.I am getting successful result for login endpoint but It was not forwarding its session to next activity.For example: If user is loggedIn successful he can access rest of features in further activities. But while I'm trying to switch activity I am getting "User Needs to login".
MainActivity.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
jsonResponse = new LoginPOJO();
// UserLogin Field
etUserName = (EditText) findViewById(R.id.etUserName);
// UserLogin Password
etPassword = (EditText) findViewById(R.id.etPassword);
// Login Button Image
btnLogin = (ImageView) findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(this);
// User SignUp Button Image
ImageView btnSignUp = (ImageView) findViewById(R.id.btnSignUp);
btnSignUp.setOnClickListener(this);
// Forget Password Textbutton
TextView frgtPassword = (TextView) findViewById(R.id.forgetpassword);
frgtPassword.setOnClickListener(this);
// Skip for now button
final TextView skipfornow = (TextView) findViewById(R.id.skipnow);
skipfornow.setOnClickListener(this);
}
private void logIn(final String username, final String password) {
final ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setMessage("Logging you in...");
progressDialog.setIndeterminate(true);
progressDialog.setCancelable(false);
progressDialog.show();
String UPLOAD_URL = "http://xxxxx-dev.elasticbeanstalk.com/api/v1/login";
final StringRequest stringRequest = new StringRequest(Request.Method.POST, UPLOAD_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
//Dismissing the progress dialog
progressDialog.dismiss();
// Getting the final Json Object
JSONObject parentObject;
try {
parentObject = new JSONObject(s);
LoginPOJO.setCode(parentObject.getString("code"));
// Getting the data from Data Json Object
JSONObject dataObject = parentObject.getJSONObject("data");
// Getting data from Geo object
JSONObject geoObject = dataObject.getJSONObject("geo");
// Getting data from businesses Array
JSONArray businessesArray = dataObject.getJSONArray("businesses");
// Getting data from Meta Object
JSONObject metaObject = parentObject.getJSONObject("meta");
startActivity(new Intent(MainActivity.this, PromotionsFeedActivity.class));
} catch (JSONException e) {
e.printStackTrace();
}
//Showing toast message of the response
Log.i("TAG", "onResponse: " + s);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
//Dismissing the progress dialog
progressDialog.dismiss();
//Showing snackbar
Toast.makeText(MainActivity.this, "Connection Problem", Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
//Converting Bitmap to String
//Creating parameters
Map<String, String> params = new Hashtable<>();
params.put("apikey", Utilities.API_KEY);
params.put("secret", Utilities.SECRET_KEY);
params.put("email", username);
params.put("password",password);
//Adding parameters
//returning parameters
return params;
}
};
//Creating a Request Queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
}
feed.java
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_promotions_feed);
jsonResponse = new LoginPOJO();
communityImage = (TextView) findViewById(R.id.communityImage);
communityImage.setOnClickListener((View.OnClickListener) this);
searchImage = (TextView) findViewById(R.id.searchImage);
searchImage.setOnClickListener((View.OnClickListener) this);
specialsImage = (TextView) findViewById(R.id.searchImage);
specialsImage.setOnClickListener(this);
calenderImage = (TextView) findViewById(R.id.calenderImage);
calenderImage.setOnClickListener(this);
profileImage = (TextView) findViewById(R.id.profileImage);
profileImage.setOnClickListener(this);
TextView response = (TextView) findViewById(R.id.response);
String data = LoginPOJO.getCode();
response.setText(data);
}
private void getPromotionsFeed(final String location) {
final ProgressDialog progressDialog = new ProgressDialog(PromotionsFeedActivity.this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setMessage("Getting promotions feed...");
progressDialog.setIndeterminate(true);
progressDialog.setCancelable(false);
progressDialog.show();
String UPLOAD_URL = "http://xxxx-dev.elasticbeanstalk.com/api/v1/get_promotions_feed";
final StringRequest stringRequest = new StringRequest(Request.Method.POST, UPLOAD_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
//Dismissing the progress dialog
progressDialog.dismiss();
// Getting the final Json Object
JSONObject parentObject;
try {
parentObject = new JSONObject(s);
} catch (JSONException e) {
e.printStackTrace();
}
//Showing toast message of the response
Log.i("TAG", "onResponse: " + s);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
//Dismissing the progress dialog
progressDialog.dismiss();
//Showing snackbar
Toast.makeText(PromotionsFeedActivity.this, "Connection Problem", Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
//Converting Bitmap to String
//Creating parameters
Map<String, String> params = new Hashtable<>();
params.put("apikey", Utilities.API_KEY);
params.put("secret", Utilities.SECRET_KEY);
params.put("location","xxx");
//Adding parameters
//returning parameters
return params;
}
};
//Creating a Request Queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
}
LogCat
04-03 18:47:26.263 10750-10750/com.example.reception.farbinder_test I/TAG: onResponse: {"code":200,"status":"ok","message":"Logged in.","data":{"id":"Pg4yYHXIQK","firstName":"Arun","lastName":"","shortName":"Arun","email":"arun#farbinder.com","role":"owner","showInviteMessage":false,"verified":true,"zipCode":"07666","location":"Teaneck, NJ","geo":{"latitude":40.888461,"longitude":-74.012066,"zipcode":"07666","city":"Teaneck","state":"NJ","type":"geo"},"defaultCommunity":{"id":18313,"name":"Teaneck, NJ Community","city":"Teaneck","state":"NJ","latitude":40.888461,"longitude":-74.012066,"type":"community"},"businesses":[{"id":72,"name":"my bus","type":"business"}],"type":"user"},"meta":{"userVideoUrl":"https://d1e6yi6s3cx2ur.cloudfront.net/videos/0/_20160316_ios-user.m4v","businessVideoUrl":"https://d1e6yi6s3cx2ur.cloudfront.net/videos/0/_20160316_ios-business.m4v","promoVideoUrl":"https://d1e6yi6s3cx2ur.cloudfront.net/videos/0/_20160316_ios-user.m4v","searchVideoUrl":"https://d1e6yi6s3cx2ur.cloudfront.net/videos/0/_20160316_ios-user.m4v","faqUrl":"http://farbinder-dev.elasticbeanstalk.com/api/v1/faq","privacyUrl":"http://farbinder-dev.elasticbeanstalk.com/api/v1/privacy","termsUrl":"http://farbinder-dev.elasticbeanstalk.com/api/v1/terms","contactFormUrl":"http://farbinder-dev.elasticbeanstalk.com/api/v1/contact?u\u003d25fee27e9d18464eadbad0faa632a9b6e82787cc613ca64e","feedbackFormUrl":"http://farbinder-dev.elasticbeanstalk.com/api/v1/feedback?u\u003d25fee27e9d18464eadbad0faa632a9b6e82787cc613ca64e","type":"links"}}
04-03 18:47:26.265 1518-1877/system_process W/InputMethodManagerService: Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy#2ddf4f6b attribute=null, token = android.os.BinderProxy#330c1b98
04-03 18:47:26.326 1518-1660/system_process V/WindowManager: Adding window Window{11f00761 u0 com.example.reception.farbinder_test/com.example.reception.farbinder_test.PromotionsFeedActivity} at 4 of 10 (after Window{27eec5b0 u0 com.example.reception.farbinder_test/com.example.reception.farbinder_test.MainActivity EXITING})
04-03 18:47:26.330 1518-1880/system_process V/WindowManager: Adding window Window{1217747 u0 com.example.reception.farbinder_test/com.example.reception.farbinder_test.PromotionsFeedActivity} at 4 of 11 (before Window{11f00761 u0 com.example.reception.farbinder_test/com.example.reception.farbinder_test.PromotionsFeedActivity})
04-03 18:47:26.441 10750-10750/com.example.reception.farbinder_test E/RecyclerView: No adapter attached; skipping layout
04-03 18:47:26.457 1162-1162/? W/SurfaceFlinger: couldn't log to binary event log: overflow.
04-03 18:47:27.092 10750-10750/com.example.reception.farbinder_test I/TAG: onResponse: {"code":401,"status":"error","message":"User not logged in."}
You do your login in a service, and then have the service broadcast the successful login to any interested classes.