Android: Error connecting Android app with Database using php and json - java

My android app needs to send a string, and based on that, needs to get a response from the database.
I have a php that receives the string from the app, queries the database, and returns the response using echo json_encode($response_array); which works fine on the browser and echoes in a json object format.
However, In the app, I am using Volley. The php array $response_array above sends multiple strings which i need to display in the app textview.
I have set up volley in the gradle dependencies.
However, on running the app from my phone (which is connected on my laptop hotspot), the error i get is "null". This is the sample code from the app.
TextView o,t;
private RequestQueue requestQueue;
private static final String URL = "http://172.25.33.189/fadapp/mirror.php";
private StringRequest request;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
o=(TextView)findViewById(R.id.tryOne);
t=(TextView)findViewById(R.id.tryTwo);
requestQueue = Volley.newRequestQueue(this);
request = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonobject = new JSONObject(response);
if (jsonobject.names().get(0).equals("name")) {
o.setText(jsonobject.getString("name"));
if(jsonobject.getString("stat").equals("1")) {
t.setText(R.string.inText);
t.setTextColor(Color.parseColor("#00FF00"));
} else {
t.setText(R.string.outText);
t.setTextColor(Color.parseColor("#FF0000"));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, ""+error.getMessage(), Toast.LENGTH_SHORT).show();;
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> hashMap = new HashMap<String, String>();
hashMap.put("speid", "database query string here");
return hashMap;
}
};
requestQueue.add(request);

Have you grant the intenet access to the app with ?
If you are hosting from your laptop you may need to open the port 80, to be sure that the problem isn't yor Volley set-up try to query for example google and print the response that should be a 200 http code

Related

Can not store response data public to access outside in android

I can get very strange issue in my project. I can get the response from volley over the internet and after reposne I want to store it in sharedpref, but issue is that when I get the response and showed up within resonse function then it shows correct data, but when I used to save it outside the response function sharedpref it gives 0. I declared the string public and top of the class but got no luck. Am very strange whats the issue.
SharedPreferences savelogin = getSharedPreferences("login",MODE_PRIVATE);
final SharedPreferences.Editor slogin = savelogin.edit();
String url = "https://datafinderdatabase.xyz/dfapi/FetchId.php?username="+fuser;
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
userid = response.toString();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toasty.error(getApplicationContext(), "Network Issue", Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
slogin.putString("username",fuser);
slogin.putString("password",fpass);
slogin.putString("userid",userid);
slogin.commit();
This is because your call to the API is asynchronous. Therefore, the result you get back may be processed after that function finishes. To solve this, you can take a Interface approach, explained here for a similar issue:
wait until firebase retrieves data
OR: you need to save the variable to the shared preferences inside the onResponse function.
These:
slogin.putString("username",fuser);
slogin.putString("password",fpass);
slogin.putString("userid",userid);
slogin.commit();
must be inside this:
#Override
public void onResponse(String response) {
userid = response.toString();
//here
}

API Call in Android Studio using volley (JAVA)

I am not sure what I am doing wrong. I am very new to this and just jumped straight into trying to make API calls. I am trying to retrieve information from rapidAPI for a simple project I am working on to view prices of stocks and so on. I am using the volley package from Android Studio to make my APIcalls to retrieve JSON and trying to put that into a textView. The way I imagine this to work is that I press a button and then once that is clicked, it runs the code to get the information and then shows the response in the textView. however, when the button is clicked, nothing happens. no error or response of any sort.
private TextView mTextViewResult;
private RequestQueue mQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextViewResult= findViewById(R.id.text_view_result);
Button buttonParse= findViewById(R.id.button_parse);
mQueue= Volley.newRequestQueue(this);
buttonParse.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
jsonParse();
}
});
}
private void jsonParse(){
String url="https://apidojo-yahoo-finance-v1.p.rapidapi.com/market/get-quotes?region=CA&lang=en&symbols=VEQT.TO";
JsonObjectRequest request= new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray= response.getJSONArray("result");
JSONObject result=jsonArray.getJSONObject(0);
int marketPrice= result.getInt("regularMarketPrice");
mTextViewResult.setText(String.valueOf(marketPrice));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
mTextViewResult.setText("" +error.toString());
}
}){
#Override
public Map<String,String> getHeaders() throws AuthFailureError{
Map<String,String> params= new HashMap<>();
params.put("x-rapidapi-host", "apidojo-yahoo-finance-v1.p.rapidapi.com");
params.put("x-rapidapi-key", "APIKEY");
return params;
}
};
mQueue.add(request);
}
}
From what you've posted are you sure your x-rapidapi-key is APIKEY. Pretty sure that's the primary reason of your issue. Only after you put a valid API key in your request header, will your API call return a proper expected response.
You can read how to generate the rapidapi key from their official docs here
Currently the response you receive on api call using the wrong apikey is something like this:
{
"message": "Key doesn't exists"
}
Now in your java code you are looking for a JSONArray based on the key "result", while the response currently only has "message" being returned. That's the reason nothing happens, you can try finding the value in response for message and get the error messages if you wish. Generate a valid rapidapi key and try again, Good luck!

How to find specific data from a Volley Api string response

I am new to APIs and finally figured out how to successfully retrieve a request response from a website. The thing is I am completely lost on how I should handle the response. I don't know how to access certain values within the response
here is my API Volley code
RequestQueue requestQueue = Volley.newRequestQueue(this);
String uri = Uri.parse("https://chicken-coop.p.rapidapi.com/games/Fortnite?platform=pc")
.buildUpon()
.build().toString();
StringRequest stringRequest = new StringRequest(
Request.Method.GET, uri, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
displayResults.setText("Response: " + response.substring(0,500));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
displayResults.setText( "" + error.toString());
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("X-RapidAPI-Key", "5cdb2bbe57mshd9242c8d3177cb3p16f2fbjsnd7c5829eb4ad");
params.put("X-RapidAPI-Host", "chicken-coop.p.rapidapi.com");
return params;
}
};
requestQueue.add(stringRequest);
Here is the response query that I received
"result":{10 items
"title":"Fortnite"
"releaseDate":"Jul 25, 2017"
"description":"Epic Games next project has you building forts and stopping a zombie invasion."
"genre":[...
]6 items
"image":"https://static.metacritic.com/images/products/games/5/c7eb46ceb7da9c72c5a95193e8621faf-98.jpg"
"score":81
"developer":"Epic Games"
"publisher":[...
]1 item
"rating":"T"
"alsoAvailableOn":[6 items
0:
"iPhone/iPad"
1:
"PlayStation 3"
2:
"PlayStation 4"
3:
"Switch"
4:
"Xbox 360"
5:
"Xbox One"
How would I go about finding an explicit value from the response query? I have been searching for how to do this online and there are so many different ways to go about and I have no clue what to do. For example, how would I be able to put the Release Date into its own text box? Most of the examples I see online use JsonObjects when I m using a string response
in your onResponse method you need to parse your result so you can extract any data you want
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("result");
// toaccess to your json data
String title = jsonArray.getString("title");
// your code
} catch (JSONException e) {
e.printStackTrace();
}
}

Android Volley unable to get data in response

I am trying to make a web-service call using volley and printing the response in the logcat. But I don't know why I am not getting response. Not even any error message.
Below is my code. I know I am missing something. Please correct me.
private void syncData() {
mProgressDialog.showProgressDialog("Initializing Please Wait...");
RequestQueue requestQueue = Volley.newRequestQueue(SalesDashboard.this);
StringRequest stringRequest = new StringRequest(Request.Method.POST, SYNC_DATA_SALES, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
mProgressDialog.dismissProgressDialog();
Log.e("TAG", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
mProgressDialog.dismissProgressDialog();
Log.e("TAG", error.toString());
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String , String> params = new HashMap<>();
String userrole = mSessionManagement.getLoggedInUser().get(SESSION_USER_ROLE);
params.put("branch", mSessionManagement.getSelectedBranch());
params.put("staff_id", mSessionManagement.getLoggedInUser().get(SESSION_EMP_ID));
params.put("user_role", mSessionManagement.getLoggedInUser().get(SESSION_USER_ROLE));
params.put("user_dept", mSessionManagement.getLoggedInUser().get(SESSION_DEPT_IDS));
params.put("principal", mSessionManagement.getLoggedInUser().get(SESSION_PRINC_IDS));
if (userrole.equals(ADMIN) || userrole.equals(COUNTRY_MANAGER)) {
params.put("user_div", mSessionManagement.getSelectedDivision());
} else {
params.put("user_div", mSessionManagement.getLoggedInUser().get(SESSION_DIV_IDS));
}
return super.getParams();
}
};
requestQueue.add(stringRequest);
}
I am not receiving any error message also or any kind of exception. I have checked the webservice by hitting it on browser the response is displayed correctly on the browser but not able to fetch it in android.
Why you call super.getParams() on return instead params? Maybe it turn wrong on your request. Then try as follow
#Override
protected Map<String, String> getParams() throws AuthFailureError {
...
return params;
}
Bonus: use getMessage instead do toString() your error object
Print the stringRequest and check the url and cross verify with ur url
Before that check have u added Internet permissions in manifest file.

WearOS cannot make Volley request to an endpoint running on my computer's localhost

Problem
I'm attempting to make a simple POST JsonObjectRequest from a Huawei Watch and I keep getting com.android.volley.TimeoutError. I can successfully make other POST JsonObjectRequests from the watch to a different endpoint (not on my computer's localhost) and I can successfully make requests to the desired endpoint from a laptop.
What I've Tried:
Most posts suggest that this error is due to a bad connection or an incorrect endpoint. I tried increasing the timeout period to see if my connection was just slow but this did not fix things. The endpoint is definitely correct as it works when I make the request from a laptop.
I read on several posts that there are issues when connecting to unknown certificates. I followed the quick fix outline here: https://newfivefour.com/android-trust-all-ssl-certificates.html but this made no difference
My Code
mRequestQueue.add(volleyRequest());
...
private JsonObjectRequest volleyRequest(){
JSONObject data = null;
try{
data = new JSONObject("{'some':'data','other':'data'}");
} catch (JSONException e){
e.printStackTrace();
}
JsonObjectRequest request = new JsonObjectRequest(POST, mPath, data,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.i("Volley Response", response.toString());
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("Volley Error", error.toString());
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
headers.put("Authorization", mToken);
return headers;
}
};
return request;
}

Categories

Resources