Virtual method 'getApplicationContext()' Failure to display context in application - android

When displaying a context, a failure occurs. What could be the problem?
No results were found for your request
If results are found, displays if there is no context menu, that no results were found, but it gives an error and application failure
public void run(final View view) throws IOException{
Log.d(TAG, "run: up and running...");
if (frag_id==0 || frag_id==1) { //if home fragment & search fragment
Log.d(TAG, "getIntentData: frag id not 2");
if (search_term == null) {
urlImage = "https://api.pexels.com/v1/curated";
} else {
int randPage;
do {
randPage = new Random().nextInt(15);
}while(randPage==0);
urlImage = "https://api.pexels.com/v1/search?query=" + search_term.toLowerCase() + "&per_page=15&page=" + randPage;
}
}
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.header("Authorization", StaticUtils.API_KEY)
.url(urlImage)
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(#NonNull Call call, #NonNull IOException e) {
call.cancel();
}
#Override
public void onResponse(#NonNull Call call, #NonNull Response response) throws IOException {
final String myResponse = response.body() != null ? response.body().string() : null;
runOnUiThread(new Runnable() {
#Override
public void run() {
Log.d(TAG, "run: integrated successfully: ");
if (!StaticUtils.imagesListTemp.isEmpty()){
StaticUtils.imagesListTemp.clear();
}
try {
JSONObject json = new JSONObject(myResponse);
JSONArray jsonArray = json.getJSONArray("photos");
if (jsonArray.length()>0){
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
int imageId = jsonObject.getInt("id");
String srcName = jsonObject.getString("photographer");
String srcUrl = jsonObject.getString("photographer_url");
String dimen = jsonObject.getString("width")+"x"+jsonObject.getString("height");
JSONObject srcObject = jsonObject.getJSONObject("src"); //getting the image sources of different dimens
String imgSrcOrg = srcObject.getString("original");
String imgSrcLarg = srcObject.getString("large");
String imgSrcMid = srcObject.getString("medium");
String imgSrcSml = srcObject.getString("small");
String imgSrcPort = srcObject.getString("portrait");
String imgSrcLand = srcObject.getString("landscape");
String imgSrcTiny = srcObject.getString("tiny");
ImageDifferentSize imageArray = new ImageDifferentSize(imgSrcOrg,imgSrcLarg,imgSrcMid,imgSrcSml,imgSrcPort,imgSrcLand,imgSrcTiny);
StaticUtils.imagesListTemp.add(new ImagesItem(imageId, srcName, dimen, srcUrl,imageArray));
ImagesFragment.adapter.notifyDataSetChanged();
}
}else{
//replace with snackBar
Toast.makeText(getApplicationContext(), "This is my Toast message!",
Toast.LENGTH_SHORT).show();
}
Log.d(TAG, "run: List size: "+StaticUtils.imagesListTemp.size());
boolean isAddSucceed = StaticUtils.imagesList.addAll(StaticUtils.imagesListTemp);
Log.d(TAG, "onCreate: Copy operation succeed:"+isAddSucceed+", Final arrayList size: "+StaticUtils.imagesList.size());
} catch (JSONException e) {
Log.d(TAG, "onResponse: Json Parsing data error.");
e.printStackTrace();
}
}
When displaying a context, a failure occurs. What could be the problem?
No results were found for your request
If results are found, displays if there is no context menu, that no results were found, but it gives an error and application failure

Related

How to instantiate a new JSONObject Arraylist which takes the value of the Arraylist returned by a function?

My defined function returns a JSONObejct Arraylist, however, when I instantiate a new Arraylist to the output of the function, it shows an empty Arraylist. How can I fix this issue and why is it showing an empty array list when it is indeed returning an Arraylist in the function?
Here is the code :
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activty_departures);
departure_flights = doGetRequest();
}
//my function
private ArrayList<JSONObject> doGetRequest() {
OkHttpClient client = new OkHttpClient();
ArrayList<JSONObject> departureObject = new ArrayList<>();
String url = "http_url";
Request request = new Request.Builder().url(url).build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
if(response.isSuccessful()) {
try {
String jsonData = response.body().string();
JSONObject Jobject = new JSONObject(jsonData);
JSONArray jarray = Jobject.getJSONArray("Flights");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
String adft = object.getString("Adft");
if (adft.equals("D")) {
departureObject.add(object);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
return departureObject;
Hitting Api in android not getting immediately return data it depends upon your response.
you are to return the list immediately so you received an empty list if you can work inside the onResponse method then your problem is solved.
Don't use .equals() method on String, but use .contentEquals(). The reason for this is because contentEquals() checks the content of a String and compares it to StringBuffer, StringBuilder and CharSequence aswell and all derived classes of these.
This is why in your case adft.equals("D") could return false even though adft is in the background this:
String adft = "D";
The reason for that is because equals() will only compare String objects, so all other objects are considered not equal and it will return false.
More on that here: https://www.programmersought.com/article/2993983603/
Also, sometimes returned values can store a space we dont need, so insted "D" we have "D " or " D". To solve this just use method .trim()
if(adft.trim().contentEquals("D"))
You're returning the list immediately after enqueue your API. Your ArrayList fill after API request succeeds so you have to create your ArrayList global and fill that after onSuccess. After that create another method to render your data on UI. like mentioned below:
ArrayList<JSONObject> departureObject = new ArrayList<>();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activty_departures);
doGetRequest();
}
private void doGetRequest() {
OkHttpClient client = new OkHttpClient();
String url = "http_url";
Request request = new Request.Builder().url(url).build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
if(response.isSuccessful()) {
try {
String jsonData = response.body().string();
JSONObject Jobject = new JSONObject(jsonData);
JSONArray jarray = Jobject.getJSONArray("Flights");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
String adft = object.getString("Adft");
if (adft.equals("D")) {
departureObject.add(object);
}
}
reloadData();
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
}
private void reloadData() {
// here your data is ready
}

How to get Retrofit 2 error from array body

My current response is
{"response":"validation error","status":"failure","code":400,"errors":["You can not add multiple items with different categories"]}
My current code is :
String errorBody = response.errorBody().string();
JSONObject jsonObject = new JSONObject(errorBody.trim());
jsonObject = jsonObject.getJSONObject("errors");
Iterator<String> keys = jsonObject.keys();
String errors = "";
while (keys.hasNext()) {
String key = keys.next();
JSONArray arr = jsonObject.getJSONArray(key);
for (int i = 0; i < arr.length(); i++) {
errors += key + " : " + arr.getString(i) + "\n";
}
}
I am trying to get the error code to see if it matches specific keywords to handle the response
i think your current code its not to good,better way for u is:
create modelClass for your json output and in retrofit calls write:
if (model.status=='failure' || model.code==400){
print(response.message) // or something like this
}
You can look through the following code snippet
call.enqueue(new Callback<PagedResponse<NotificationModel>>() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onResponse(Call<PagedResponse<NotificationModel>> call, Response<PagedResponse<NotificationModel>> response) {
if (response.isSuccessful()) {
if (response.code() == 200) {
try {
PagedResponse<NotificationModel> notifications = (PagedResponse<NotificationModel>) response.body();
tvRecordsCount.setText("Total "+response.body().getTotal()+" Notifications ");
showNotification(notifications);
} catch (Exception e){
e.printStackTrace();
}
} else {
showToast(getApplicationContext(), "Server Error");
}
}
}
#Override
public void onFailure(Call<PagedResponse<NotificationModel>> call, Throwable t) {
showToast(getApplicationContext(), t.getMessage());
}
});
I managed to get it working with this code:
String errors = "";
String errorBody = response.errorBody().string();
JsonParser parser = new JsonParser();
JsonObject rootObj = parser.parse(errorBody.trim()).getAsJsonObject();
JsonArray errorArray = rootObj.getAsJsonArray("errors");
for (JsonElement pa : errorArray) {
errors = pa.getAsString();
}

Handle response of multiple request from Volley Library

I am sending multiple request through for loop.
On response I get success or failure message, and I need to show this message in a AlertDialog.
My Problem is: when I am sending 10 request then I am getting 10 response hence 10 times dialogue is showing with response.
I want to show only one dialogue when all response will have come,and that dialogue should contain response according to their each and every request.
How can I do it.
code which I tried:
if (globalInstance.isNetworkAvailable(AddBookingList.this)) {
int si = checkedItems.size();
if (checkedItems.size() > 0) {
for (int i = 0; i < si; i++) {
int appid = checkedItems.get(i).getAppid();
int bookingId = checkedItems.get(i).getBookingid();
List<Contacts> con = db.getadvertisment(bookingId);
List<AddImages> img = db.getImagesbybookingId(bookingId);
String postXml = createxmlForPost(con, img);
sendDataToServer(postXml,appid, bookingId, si);
}
}
}
private void sendDataToServer(final String postXml, final int appid, final int bookingId, final int si) {
final ProgressDialog progressDialog = new ProgressDialog(this, R.style.AppCompatAlertDialogStyle);
progressDialog.setMessage("Please wait...");
progressDialog.setCancelable(false);
progressDialog.show();
try {
final RequestQueue queue = Volley.newRequestQueue(this);
JSONObject obj = new JSONObject();
obj.put("xmlData", postXml);
int socketTimeout = 30000;//30 seconds
final StringRequest postRequest = new StringRequest(Request.Method.POST, Constants.Rootpath + "PostBooking",
new Response.Listener<String>() {
#Override
public void onResponse(String st) {
if (progressDialog != null || progressDialog.isShowing()) {
progressDialog.dismiss();
}
try {
JSONArray response = new JSONArray(st);
for (int i = 0; i < response.length(); i++) {
JSONObject jsonObject = response.getJSONObject(i);
int status = jsonObject.getInt("Status");
String msg = jsonObject.getString("Msg");
String serverbooking_id = jsonObject.getString("BookingId");
if (status == 1) {
checkedItems.clear();
if (response.length() > 1) {
String newserverbooking_id = response.getJSONObject(0).getString("BookingId") + "\n" + response.getJSONObject(1).getString("BookingId");
db.updateBookingDetailsbyAppId(newserverbooking_id, appid, status);
} else {
db.updateBookingDetailsbyAppId(serverbooking_id, appid, status);
}
showDatainList();
globalInstance.showSuceessMessage(true, "Success!!! Your BookingID is: " + serverbooking_id, AddBookingList.this);
try {
List<Contacts> contacts = db.getAllBookingDetails();
for (int h = 0; h < contacts.size(); h++) {
locallySaveImagesinPhone(bookingId, contacts.get(h).get_serverbookingId());
}
} catch (IOException e) {
e.printStackTrace();
}
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
} else {
globalInstance.showFailureMessage(false, "Booking Failed." + msg, AddBookingList.this);
checkedItems.clear();
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (progressDialog != null || progressDialog.isShowing()) {
progressDialog.dismiss();
}
String msg = error.getMessage();
globalInstance.showFailureMessage(false, "Booking Failed.Please Try Again!!!", AddBookingList.this);
}
}
) {
#Override
protected Map<String, String> getParams() {
HashMap<String, String> params = new HashMap<>();
params.put("xmldata", postXml);
return params;
}
};
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
postRequest.setRetryPolicy(policy);
queue.add(postRequest);
} catch (JSONException e1) {
e1.printStackTrace();
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}
As i understand your problem is calling globalInstance.showSuceessMessage() or globalInstance.showFailureMessage every time you get the response.
what i think might work is:
Instead of these two methods, define an Arraylist<String> and based on the
success or failure of the response add messages to it like "Success!!! Your BookingID is: " + serverbooking_id and "Booking Failed." + msg.
Define a method like showMessages() which has a dialogue containing the messages u added to arraylist before. then call it after where you called thesendDataToServer method which is in the if (checkedItems.size() > 0) block.

How to show other Json objects in RecylerView on Android

I want develop android application for one website. I read website posts from json and show its in RecyclerView every 10 posts.
I can show title, description and thumbnail. but i want show medium from thumbnail_images instance of thumbnail. I don't know how to read images from medium ?!
My Json Link : Link
AsyncTaskCodes:
public class MainDataInfo {
private Context mContext;
private String ServerAddress = ServerIP.getIP();
public void getMainDataInfo(Context context) {
mContext = context;
new getInfo().execute(ServerAddress + "page=1");
}
private class getInfo extends AsyncTask<String, Void, String> {
EventBus bus = EventBus.getDefault();
private String ou_response;
private List<MainDataModel> infoModels;
#Override
protected void onPreExecute() {
CustomProcessDialog.createAndShow(mContext);
infoModels = new ArrayList<>();
}
#Override
protected String doInBackground(String... params) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(ServerAddress + "page=1")
.build();
Response response;
try {
response = client.newCall(request).execute();
ou_response = response.body().string();
response.body().close();
if (ou_response != null) {
try {
JSONObject postObj = new JSONObject(ou_response);
JSONArray postsArray = postObj.getJSONArray("posts");
infoModels = new ArrayList<>();
for (int i = 0; i <= infoModels.size(); i++) {
JSONObject postObject = (JSONObject) postsArray.get(i);
int id = postObject.getInt("id");
String title = postObject.getString("title");
//get other data
JSONObject imageObj = postObject.getJSONObject("thumbnail_images");
JSONObject mediumObj = imageObj.optJSONObject("medium");
String mediumImage = mediumObj.getString("url");
Log.d("Data", "Post id: " + id);
Log.d("Data", "Post title: " + title);
//Use the title and id as per your requirement
infoModels.add(new MainDataModel(
postObject.getInt("id"),
postObject.getString("title"),
postObject.getString("content"),
postObject.getString(mediumImage)));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
return ou_response;
}
#Override
protected void onPostExecute(String result) {
CustomProcessDialog.dissmis();
if (result != null) {
bus.post(infoModels);
}
}
}
}
for fetch medium image i use this code :
//get other data
JSONObject imageObj = postObject.getJSONObject("thumbnail_images");
JSONObject mediumObj = imageObj.optJSONObject("medium");
String mediumImage = mediumObj.getString("url");
but when set mediumImage for infoModels.add(new MainDataModel() not show me any posts!
How can set images from medium ? thanks all <3
private void setImageWithPicaso(String imageUrl) {
if (!(imageUrl == null)) {
Picasso.with(getActivity()).load(imageUrl).placeholder(R.drawable.placeholder_background).into(imageView, new Callback() {
#Override
public void onSuccess() {
//On Success
}
#Override
public void onError() {
spinner.setVisibility(View.GONE);
//On Error
}
});
} else {
spinner.setVisibility(View.GONE);
//On Error
}
}

Android query can't store class variable from JSON object callback

I can't write class variable from AJAX-JSON callback. It show right info inside callback but when a Query callback finishes, it is set to null. Why?
This is code:
public void asyncJson() {
String url = "myurl";
aq.ajax(url, JSONObject.class, new AjaxCallback<JSONObject>() {
#Override
public void callback(String url, JSONObject json, AjaxStatus status
{
if (json != null) {
jsonToString(json);
} else {
Toast.makeText(aq.getContext(), "Error:" + status.getCode(), Toast.LENGTH_LONG).show();
}
}
});
private void jsonToString(JSONObject data) {
JSONArray array = null;
try {
array = data.getJSONArray("listResp");
for (int i = 0; i < array.length(); i++) {
JSONObject json_data = array.getJSONObject(i);
c.setDate_creation(json_data.getString("date_creation"));
c.setName_user(json_data.getString("name_user"));
list.add(c);//linkedlist
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}
The variable listContest when callback finishes is null.

Categories

Resources