Error with the E/libEGL cant make a get request - java

im a begginer Android Developer, trying to make an APP, but
My app is giving an error:
E/libEGL: call to OpenGL ES API with no current context (logged once per thread)
when i try to make a get REQUEST, so it sometimes can make that get go trought, but many times, just get stuck there and cant do anything.
my GET request is here:
StringRequest request = new StringRequest(Request.Method.GET, url_assets, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("AssetPlant", response);
List<Feature> featuresListSN = new ArrayList<>();
fc = FeatureCollection.fromJson(response);
Log.e("AssetPlantFC", fc.toString());
List<Feature> featuresListAll = null;
List<Feature> featuresListWITHSN = null;
for (int i = 0; i < fc.features().size(); i++){
String moduleID = fc.features().get(i).getStringProperty("id");
String moduleName = fc.features().get(i).getStringProperty("name");
String modulePVM = fc.features().get(i).getStringProperty("pvm");
String moduleFinalName = moduleName + "_" + modulePVM;
String moduleSN = fc.features().get(i).getStringProperty("sn");
}
featuresListAll = fc.features();
featuresListWITHSN = fc.features();
if(featuresListAll != null){
fSize = featuresListAll.size();
for(int i = 0; i < fSize; i++){
if(!Objects.equals(featuresListAll.get(i).getStringProperty("sn"), "")){
featuresListSN.add(featuresListAll.get(i));
String barcode_string = featuresListAll.get(i).getStringProperty("sn");
serial_number_list.add(barcode_string);
}
if (i+1 == fSize){
Log.e("FOR LOOP", "ENDED");
FeatureCollection fc_SN = FeatureCollection.fromFeatures(featuresListSN);
fc = FeatureCollection.fromFeatures(featuresListAll);
all_barcodes_list = serial_number_list;
arrayAsString_SN = new Gson().toJson(fc_SN);
arrayAsString = new Gson().toJson(fc);
goNext(feature);
}
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if(error.networkResponse.statusCode == 403 || error.networkResponse.statusCode == 401){
Toast.makeText(LoadingMapActivity.this, "Session ended", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(LoadingMapActivity.this, "Failed to gather info" + error.networkResponse.statusCode, Toast.LENGTH_SHORT).show();
}
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("Authorization", "Bearer " + token);
return headers;
}
};
Log.e("ADDED GET PLANT", "TO THE QUEUE:");
request.setRetryPolicy(new DefaultRetryPolicy(
6000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES*2,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
VolleySingleton.getInstance(LoadingMapActivity.this).addToRequestQueue(request);
I've already tryed many things, like making it run in another thread and give a call back when it get the response, but it get stuck anyway, and i cant figure out why this is happening.

Related

Android Volley POST to Java EE not working

I'm trying to call a POST-Method on my Android Device to my Java EE Webapplication. Java Version 8, Android Application is on API Level 22 and i'm using a virtual device on my computer.
I can add the request to the Volley-queue but then it doesn't resolve my POST request.
This is the CustomerService on the Java EE Application:
#EJB
CustomerBean customerBean;
#POST
#Produces(MediaType.APPLICATION_JSON)
#Path("/registration")
public Long registration(#FormParam("email") String email, #FormParam("password") String pw) {
Customer c = customerBean.registration(email, pw);
if(c == null) {
return (long) 0;
}
return c.getId();
}
And this is the called method on CustomerBean:
#PersistenceContext
private EntityManager em;
public Customer registration(String email, String password) {
Customer c = (Customer) em.createQuery("FROM " + Customer.class.getSimpleName() + " c WHERE c.email = :email")
.setParameter("email", email).getSingleResult();
if(c == null) {
c = new Customer();
c.setEmail(email);
c.setPassword(password);
em.persist(c);
em.flush();
return c;
}
else {
return null;
}
}
And this is my Android-Client, who's sending the POST Request (MainActivity):
private Long api_regist(final String email, final String password) throws IOException {
RequestQueue queue = Volley.newRequestQueue(this);
String url = "http://10.0.2.2:8080/onlineshop-web/api/customer/registration";
final String[] result = new String[1];
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
// response
Log.d("Response", response);
result[0] = response;
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
// error
Log.d("Error.Response", error.toString());
}
}
) {
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("email", email);
params.put("password", password);
return params;
}
};
queue.add(postRequest);
while (result[0] == null){
Log.d("Result:", " Empty");
} //TODO return value afterwards
So the result[0] is allways null.

org.json.JSONException: No value for status

org.json.JSONException: No value for status
Here is my java code method for json parse
java
public void performSearch() {
String url= "http://192.168.0.136/fyp/stitle1.php";
RequestQueue requestQueue = Volley.newRequestQueue(Stitle.this);
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST,url,null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("Response", response.toString());
try {
//converting the string to json array object
JSONObject array = new JSONObject();
//Log.i("test", " value : " + array.getString("status"));
Log.i("test", " value : " + response.getString("status"));
if (array.getString("status").equals("true")) {
JSONArray jsonArray = array.getJSONArray("search");
Log.i("test", " value : " + array);
for (int i = 0; i < jsonArray.length(); i++) {
//getting product object from json array
JSONObject product = jsonArray.getJSONObject(i);
//adding the product to product list
boolean add = productList.add(new list(
product.getLong("isbn"),
product.getString("title"),
product.getString("authors"),
product.getInt("accession"),
product.getString("publisher"),
product.getInt("pubyear"),
product.getInt("pages"),
product.getInt("rak"),
product.getInt("hr"),
product.getInt("vr"),
product.getLong("barcode")
));
}
} else {
Log.i("test", "else error");
}
} catch (JSONException e) {
e.printStackTrace();
Log.i("test", e.toString());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "error:" + error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("Title", searchtitle.getText().toString());
return params;
}
};
requestQueue = Volley.newRequestQueue(Stitle.this);
requestQueue.add(jsObjRequest);
}
Php file to pass parameter to android jsonobject
stitle1.php
php
<?php
// array for JSON response
$response = array();
//set values just in case any thing goes wrong
$response["status"] = 0;
$response["message"] = "Error before start";
// check for post data with isset
if (isset($_POST["Title"])) {
$title = $_POST["Title"];
// You were not using PDO so I dumped your connection and require you to provide...
//...a configuration file for ...
require_once 'connection.php';
// ...these variables
$host = 'localhost';
$db = 'fyp';
$user = 'root';
$pass = '';
$charset = 'utf8';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
try{
// connecting to db with PDO
$pdo = new PDO($dsn, $user, $pass, $opt);
$sql = 'SELECT isbn, title, authors, accession, publisher, pubyear, pages, rak, hr, vr, barcode
FROM books
WHERE title LIKE :titleParam';
$titleParam = "%".$title."%";
$stmt = $pdo->prepare($sql);
// Bind the parameter
$stmt->bindParam(':titleParam', $titleParam, PDO::PARAM_STR);
$res = $stmt->execute();
if ($res) {
// success
$response["status"] = 1;
// connection node
$response["books"] = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$data = array();
$data["isbn"] = $row["isbn"];
$data["title"] = $row["title"];
$data["authors"] = $row["authors"];
$data["accession"] = $row["accession"];
$data["publisher"] = $row["publisher"];
$data["pubyear"] = $row["pubyear"];
$data["pages"] = $row["pages"];
$data["rak"] = $row["rak"];
$data["hr"] = $row["hr"];
$data["vr"] = $row["vr"];
$data["barcode"] = $row["barcode"];
array_push($response["books"], $data);
}
}
else {
// required field is missing
$response["status"] = 2;
$response["message"] = "No data returned";
}
}
catch (Exception $e){
$response["status"] = 3;
$response["message"] = "Error occurred." . $e->getMessage();
}
}
else {
$response["status"] = 4;
$response["message"] = "Post parameters are not correct";
}
// echoing JSON response
echo json_encode($response);
?>
When I run my application these lines appear on logcat panel
I/test: value : 4
I/test: org.json.JSONException: No value for status
These are two lines appear on logcat which indicate error about that the parameter was not sent properly
We will take this step for step. Lets start with response.
Your PHP code is returning a status value =4 which indicates that you are not getting the parameters sent to the PHP code properly. It is possible that getParams() is not even being called.
Change the getParams() method to look like this:
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
try{
String s = searchtitle.getText().toString();
Log.e("Volley request", "getParams called : " + s);
params.put("Title", s);
}
catch(Exception ex){
Log.e("Volley request ERROR", ex.getMessage());
}
return params;
}
For the second part, lets try to deal with the parsing code. Change the code to look like this:
Now regardless of how your php code responds, you will be getting a well formed JSONObject as a response which you can parse and react to it appropriately.
Change the onResponse() part of the code to look like this:
#Override
public void onResponse(JSONObject response) {
// Log.d("Response", response.toString());
try {
//converting the string to json array object
if(response != null){
if(!response.has("status"){
Log.e(TAG, "Something went wrong -- no status key!");
return;
}
else{
int status = response.optInt("status", -1);
if(status == 1){
//There could be quite a few books in this response...
//...you might want to parse in an AsyncTask instead
parseJsonObject(response);
}
else{
String message = response.optString("message", "uups");
Log.e(TAG, "error message = " + message);
return;
}
}
}
}
catch(Exception ex){
Log.e(TAG, ex.getMessage());
}
}
And now to parse the JSONObject:
Map<String, String> booksMap = new HashMap<>();
private void parseJsonObject(JSONObject jsonObject){
try{
if(jsonObject == null) return;
//Not Available!
String na = "NA"
Log.i("test", " value : " + jsonObject.toString());
if(jsonObject.has("books")){
JSONArray array = jsonObject.getJSONArray("books");
for(int i = 0; array.length(); i++){
JSONObject book = array.getJSONObject(i);
Iterator<String> it = book.keys();
while(it.hasNext()){
String key = it.next();
String value = book.optString(key, na);
booksMap.put(key, value);
}
}
}
}
catch(Exception ex){
Log.e(TAG, ex.getMessage());
}
}

How to retrieve all tagged facebook photos from the facebook sdk

After many attempts I have been unable to retrieve all of my tagged photos from the facebook sdk. I would like something similar to what tinder has, but my query only returns 110 photos, of which some repeat, compared to tinder retrieving all 296 tagged photos.
Here is the code for my request:
Bundle paramaters = new Bundle();
paramaters.putString("fields", "source");
paramaters.putInt("limit", 1000);
new GraphRequest(
AccessToken.getCurrentAccessToken(),
"/" + userId + "/photos",
paramaters,
HttpMethod.GET,
graphCallback
).executeAsync();
GraphRequest.Callback graphCallback = new GraphRequest.Callback() {
#Override
public void onCompleted(GraphResponse response) {
try {
if (response.getError() == null) {
JSONObject joMain = response.getJSONObject();
if (joMain.has("data")) {
final JSONArray jaData = joMain.optJSONArray("data");
for (int i = 0; i < jaData.length(); i++) {
JSONObject joImages = jaData.getJSONObject(i);
String url = (String) joImages.get("source");
if (i == 0) {
facebookAlbum.setDisplayUrl(url);
}
facebookAlbum.addImage(url);
albumnListAdapter.notifyDataSetChanged();
}
}
}
GraphRequest nextRequest = response.getRequestForPagedResults(GraphResponse.PagingDirection.NEXT);
if(nextRequest != null) {
nextRequest.setCallback(this);
nextRequest.executeAsync();
}
}
catch (Exception e) {
e.printStackTrace();
}
}
};

android volley: global variables does not change depending on the response on first time execution of method.

I have method in which i am making a volley request and depending on the response I need to change a global boolean variable but for some reason the variable only gets changed after the method is executed completely giving me wrong data for the variable. I need to somehow changed the variable only after the response is recieved.. please help me with it
I need to change the value of variable 'chk' on response but it does not change.
public boolean checkSourceCode() {
pDialog.setMessage("Please Wait ...");
pDialog.show();
final String entered_source_code = source_code.getText().toString();
if(entered_source_code!=null || !entered_source_code.isEmpty()) {
testString = entered_source_code;
final StringRequest sr = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String web_response) {
try {
response = new JSONObject(web_response);
Log.e("Resp SUCCESS", "" + response);
} catch (JSONException e) {
e.printStackTrace();
}
try {
hasBeenValidated = true;
if (response.getBoolean("success")) {
Log.e("Resp SUCCESS", "" + response);
validateCode = true;
chk=true; // THIS VALUE DOES NOT CHANGE ON FIRST CALL OF THE METHOD HOWEVER ON SECOND TIME CALLING THE METHOD IT CHANGED
// Utils.reference_id = source_code.getText().toString().trim();
pDialog.hide();
input_layout_source_code.setError(null);
input_layout_source_code.setErrorEnabled(false);
Utils.reference_id = source_code.getText().toString().trim();
source_code.setBackground(source_code.getBackground().getConstantState().newDrawable());
} else {
validateCode = false;
chk=false;// THIS VALUE DOES NOT CHANGE ON FIRST CALL OF THE METHOD HOWEVER ON SECOND TIME CALLING THE METHOD IT CHANGED
pDialog.hide();
input_layout_source_code.setErrorEnabled(true);
input_layout_source_code.setError("Invalid reference Id.");
Utils.reference_id = null;
Toast.makeText(getContext(), "Invalid reference Id", Toast.LENGTH_SHORT).show();
}
// chk = validateSourceCode();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
String json = null;
if (error instanceof NoConnectionError) {
String strerror = "No internet Access, Check your internet connection.";
displayMessage(strerror);
}
NetworkResponse response = error.networkResponse;
if (null != response && response.statusCode != 200) {
Log.e("Resp code", "" + response.statusCode);
displayMessage("Please contact administrator for error code " + response.statusCode);
}
if (response != null && response.data != null) {
switch (response.statusCode) {
case 400:
json = new String(response.data);
json = trimMessage(json, "message");
if (json != null) displayMessage(json);
break;
default:
json = new String(response.data);
json = trimMessage(json, "message");
if (json != null) displayMessage(json);
}
}
}
}
) {
#Override
public Request.Priority getPriority() {
return Priority.IMMEDIATE;
}
#Override
protected Map<String, String> getParams() {
Map<String, String> requestParams = new HashMap<String, String>();
requestParams.put("referral_code", entered_source_code);
// params.put("email", "abc#androidhive.info");
// params.put("password", "password123");
return requestParams;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Auth-Token", auth_token);
return params;
}
};
sr.setRetryPolicy(new DefaultRetryPolicy(
60000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
// Adding request to request queue
MaintainRequestQueue.getInstance(mContext).addToRequestQueue(sr, "tag");
}
else{
pDialog.hide();
chk=true;// THIS VALUE DOES NOT CHANGE ON FIRST CALL OF THE METHOD HOWEVER ON SECOND TIME CALLING THE METHOD IT CHANGED
}
Toast.makeText(mContext, String.valueOf(chk), Toast.LENGTH_LONG).show();
return chk;
}
chk variable can not reinitialize again inside a thread
try this
setchk(boolean chk)
{
this.chk=chk;
}
and call it from request method;
Your variable inside the volley request is not initialized by the time you reach: Toast.makeText(mContext, String.valueOf(chk), Toast.LENGTH_LONG).show(); Use a get method to obtain the chk value within volley and call that getter where you need it.

android-market retrieve empty results

I wanted to harvest some data on specific apps in
Google play marketplace.
I have used this unofficial API:
https://code.google.com/p/android-market-api/
Here is my code, that basically gets list of apps' names
and try to fetch other data on each app:
public void printAllAppsData(ArrayList<AppHarvestedData> dataWithAppsNamesOnly)
{
MarketSession session = new MarketSession();
session.login("[myGamil]","[myPassword]");
session.getContext().setAndroidId("dead00beef");
final ArrayList<AppHarvestedData> finalResults = new ArrayList<AppHarvestedData>();
for (AppHarvestedData r : dataWithAppsNamesOnly)
{
String query = r.name;
AppsRequest appsRequest = AppsRequest.newBuilder()
.setQuery(query)
.setStartIndex(0).setEntriesCount(10)
//.setCategoryId("SOCIAL")
.setWithExtendedInfo(true)
.build();
session.append(appsRequest, new Callback<AppsResponse>() {
#Override
public void onResult(ResponseContext context, AppsResponse response) {
List<App> apps = response.getAppList();
for (App app : apps) {
AppHarvestedData r = new AppHarvestedData();
r.title = app.getTitle();
r.description = app.getExtendedInfo().getDescription();
String tmp = app.getExtendedInfo().getDownloadsCountText();
tmp = tmp.replace('<',' ').replace('>',' ');
int indexOf = tmp.indexOf("-");
tmp = (indexOf == -1) ? tmp : tmp.substring(0, indexOf);
r.downloads = tmp.trim();
r.rating = app.getRating();
r.version = app.getVersion();
r.userRatingCount = String.valueOf(app.getRatingsCount());
finalResults.add(r);
}
}
});
session.flush();
}
for(AppHarvestedData res : finalResults)
{
System.out.println(res.toString());
}
}
}
Should I realyy call session.flush(); at this point?
all my quesries return empty collection as a result,
even though I see there are some names as input.
It works fine when I send only one hard coded app name as a query.
session.flush() close you session
you should open session for each query. pay attention the user can be locked for few minutes so you should have many users to to those queries.
if you have the AppId you should use that query:
String query = r.name;
AppsRequest appsRequest = AppsRequest.newBuilder()
.setAppId("com.example.android")
.setWithExtendedInfo(true)
.build();
session.append(appsRequest, new Callback<AppsResponse>() {
#Override
public void onResult(ResponseContext context, AppsResponse response) {
List<App> apps = response.getAppList();
for (App app : apps) {
AppHarvestedData r = new AppHarvestedData();
r.title = app.getTitle();
r.description = app.getExtendedInfo().getDescription();
String tmp = app.getExtendedInfo().getDownloadsCountText();
tmp = tmp.replace('<',' ').replace('>',' ');
int indexOf = tmp.indexOf("-");
tmp = (indexOf == -1) ? tmp : tmp.substring(0, indexOf);
r.downloads = tmp.trim();
r.rating = app.getRating();
r.version = app.getVersion();
r.userRatingCount = String.valueOf(app.getRatingsCount());
finalResults.add(r);
}
}
});
session.flush();
}
if you want to download also screenshoot or images you should call this query:
GetImageRequest? imgReq; imgReq = GetImageRequest?.newBuilder().setAppId(appId).setImageUsage(AppImageUsage?.SCREENSHOT).setImageId("0").build();
session.append(imgReq, new Callback<GetImageResponse>() {
#Override public void onResult(ResponseContext? context, GetImageResponse? response) {
Log.d(tag, "------------------> Images response <----------------"); if(response != null) {
try {
//imageDownloader.download(image, holder.image, holder.imageLoader);
Log.d(tag, "Finished downloading screenshot 1...");
} catch(Exception ex) {
ex.printStackTrace();
}
} else {
Log.e(tag, "Response was null");
} Log.d(tag, "------------> End of Images response <------------");
}
});

Categories