0

I am working on my final year project and I have the presentation after sometime but I am getting an issue that volley always responding as error here is my volley code and below is full code of activity

StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.d("---------------->>>", ""+response);
                        OrderConfirmationResponse orderConfirmationResponse = new Gson().fromJson(response, OrderConfirmationResponse.class);

                        if(orderConfirmationResponse.getSuccess()){
                            Toast.makeText(ConfirmOrderActivity.this, "Your order has been placed successfully!",Toast.LENGTH_LONG).show();
                            BasketPref.setBasket(null, ConfirmOrderActivity.this);
                            OrderPref.setOrder(orderConfirmationResponse.getOrder(), ConfirmOrderActivity.this);

                            startActivity(new Intent(ConfirmOrderActivity.this, MenuActivity.class));
                            finish();

                        }else{
                            Toast.makeText(ConfirmOrderActivity.this, "Unable to place your order, please try again later.",Toast.LENGTH_LONG).show();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                   public void onErrorResponse(VolleyError error) {
                        Toast.makeText(ConfirmOrderActivity.this,error.toString(),Toast.LENGTH_LONG).show();
                    }

Error is displaying in the below screenshot toast area

enter image description here

Here is the complete code of activity please let me know if i can provide you more info

 package com.jazib.otrack;

import android.content.Context;
import android.content.Intent;
import android.location.Location;
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.TextView;
import android.widget.Toast;

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.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.jazib.otrack.model.OrderConfirmationResponse;
import com.jazib.otrack.model.OrderHistory;
import com.jazib.otrack.model.OrderHistoryResponse;
import com.jazib.otrack.model.User;
import com.jazib.otrack.network.HistoryRequest;
import com.jazib.otrack.pref.BasketPref;
import com.jazib.otrack.pref.LocationPref;
import com.jazib.otrack.pref.OrderPref;
import com.jazib.otrack.pref.UserPref;
import com.jazib.otrack.utility.Config;
import com.jazib.otrack.utility.Utility;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.nlopez.smartlocation.OnLocationUpdatedListener;
import io.nlopez.smartlocation.SmartLocation;

public class ConfirmOrderActivity extends AppCompatActivity {
    String deal_id,deal_name,quantity,price,customer_id;


    //private SharedPreferences sp;
    private static final String REGISTER_URL = Config.BASE_URL+"order_enter.php";


    public static final String KEY_DEALID = "deal_id";
    public static final String KEY_DEAL_NAME = "deal_name";
    public static final String KEY_DEALI_QUANTITY= "quantity";
    public static final String KEY_DEAL_TOTAL = "price";
    public static final String KEY_CUSTOMER_ID = "customer_id";


    public static final String KEY_CUSTOMER_LAT = "lat";
    public static final String KEY_CUSTOMER_LNG = "lng";

    private User user;
    private Utility utility;
    private Context ctx;
    private Location mLocation;

    private TextView tvMessage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_confirm_order);

        utility = new Utility();
        ctx = ConfirmOrderActivity.this;

        Intent intent = getIntent();
        price = intent.getStringExtra("dtotalprice");
       // Toast.makeText(ConfirmOrderActivity.this,price,Toast.LENGTH_LONG).show();

        final Button btnaddress = (Button) findViewById(R.id.btnaddress);
        final Button btnorder = (Button) findViewById(R.id.btnorder);
        tvMessage = (TextView) findViewById(R.id.textViewMessage);


        btnaddress.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {

                Intent i = new Intent(ConfirmOrderActivity.this, ChangeAddressActivity.class);
                ConfirmOrderActivity.this.startActivity(i);


            }
        });

        btnorder.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if (Utility.isNetworkAvailable(ConfirmOrderActivity.this)) {
                    confirmOrder();
                }else{
                    Utility.showToast("No Internet Connection.", ConfirmOrderActivity.this);
                }
            }
        });

        getHistory(UserPref.getUser(ctx).getId());

        initLocation();
    }

    @Override
    public void onResume(){
        super.onResume();


        //Show default address
        setDefaultAddress();
    }


    private void setDefaultAddress(){
        User user = UserPref.getUser(ConfirmOrderActivity.this);
        ((TextView) findViewById(R.id.addressConfirmation_addressTextView)).setText(user.getAddress());
        ((TextView) findViewById(R.id.addressConfirmation_cityTextView)).setText(user.getCity());
        ((TextView) findViewById(R.id.addressConfirmation_phoneTextView)).setText(user.getPhone());
    }


    private void confirmOrder(){
        user = UserPref.getUser(ConfirmOrderActivity.this);

        Intent intent = getIntent();
        deal_id = intent.getStringExtra("did");
        deal_name = intent.getStringExtra("dname");
        quantity= intent.getStringExtra("dquantity");
        price = intent.getStringExtra("dtotalprice");

        customer_id = user.getId();


        StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.d("---------------->>>", ""+response);
                        OrderConfirmationResponse orderConfirmationResponse = new Gson().fromJson(response, OrderConfirmationResponse.class);

                        if(orderConfirmationResponse.getSuccess()){
                            Toast.makeText(ConfirmOrderActivity.this, "Your order has been placed successfully!",Toast.LENGTH_LONG).show();
                            BasketPref.setBasket(null, ConfirmOrderActivity.this);
                            OrderPref.setOrder(orderConfirmationResponse.getOrder(), ConfirmOrderActivity.this);

                            startActivity(new Intent(ConfirmOrderActivity.this, MenuActivity.class));
                            finish();

                        }else{
                            Toast.makeText(ConfirmOrderActivity.this, "Unable to place your order, please try again later.",Toast.LENGTH_LONG).show();
                        }
                    }
                },
                new Response.ErrorListener() {
//                    @Override
//                    public void onErrorResponse(VolleyError error) {
//                        Toast.makeText(ConfirmOrderActivity.this,error.toString(),Toast.LENGTH_LONG).show();
//                    }
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Toast.makeText(ConfirmOrderActivity.this,"Slow Internet issue,try again later",Toast.LENGTH_LONG).show();
                        }
                }){
            @Override
            protected Map<String,String> getParams(){
                Map<String,String> params = new HashMap<String, String>();
                params.put(KEY_DEALID,deal_id);
                params.put(KEY_DEAL_NAME,deal_name);
                params.put(KEY_DEALI_QUANTITY, quantity);
                params.put(KEY_DEAL_TOTAL, price);
                params.put(KEY_CUSTOMER_ID, customer_id);
                params.put(KEY_CUSTOMER_LAT, ""+mLocation.getLatitude());
                params.put(KEY_CUSTOMER_LNG, ""+mLocation.getLongitude());



                return params;
            }
        };

        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);
    }

    /************
     ************/
    private void getHistory(String id) {
        utility.showProgressDialog(ctx);
        Response.Listener<String> responseListener = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                utility.hideProgressDialog(ctx);
                try {
                    Log.d("== updateOrderStatus >>", "" + response);
                    OrderHistoryResponse orderResponse = new Gson().fromJson(response, OrderHistoryResponse.class);
                    if (orderResponse.getSuccess()) {
                        if(isOrderPending(orderResponse.getHistory())){
                            //Utility.showToast("You have a under process order, please complete that first.", ctx);
                            findViewById(R.id.btnorder).setVisibility(View.INVISIBLE);
                            tvMessage.setVisibility(View.VISIBLE);
                            tvMessage.setText("You have a under process order, please complete that first.");
                        }else{
                            findViewById(R.id.btnorder).setVisibility(View.VISIBLE);
                            tvMessage.setVisibility(View.GONE);
                        }
                    } else {
                        Utility.showToast("Something went wrong, please try again.", ctx);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };

        Response.ErrorListener errorListener = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                utility.hideProgressDialog(ctx);
                Toast.makeText(ctx, error.getLocalizedMessage(), Toast.LENGTH_LONG).show();
            }
        };

        HistoryRequest orderRequest = new HistoryRequest(id, responseListener, errorListener);
        RequestQueue queue = Volley.newRequestQueue(ctx);
        orderRequest.setRetryPolicy(new DefaultRetryPolicy(10000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue.add(orderRequest);
    }

    private boolean isOrderPending(List<OrderHistory> ordersList){
        for(OrderHistory orderHistory : ordersList){
            if(orderHistory.getStatusCode() == 0 || orderHistory.getStatusCode() == 1){
                return true;
            }
        }

        return false;
    }


    /********
     Location
     ********/
    private void initLocation() {
        SmartLocation.with(ctx).location().start(new OnLocationUpdatedListener() {
            @Override
            public void onLocationUpdated(Location location) {
                Log.d("***LOCATION***", "" + location.getLatitude() + " <---> " + location.getLongitude());
                mLocation = location;
                LocationPref.setLocation(location, ctx);



            }
        });
    }

}
Umar Majeed
  • 313
  • 3
  • 15
  • 1
    Are you sure this is all the code? Do you have a stacktrace? `getLatitude` method is called on null object. Check that object and see if it is initialized correctly. – MXC Oct 04 '18 at 02:58
  • i have added the complete code – Umar Majeed Oct 04 '18 at 03:03
  • Do you get `location` value in your `onLocationUpdated()` method? Paste the stacktrace as well. As per your code, looks like `mLocation` or `location` is null. – MXC Oct 04 '18 at 03:12
  • on some mobiles its working and on some mobiles its giving error – Umar Majeed Oct 04 '18 at 03:19
  • So you mean on some mobiles you see onLocationUpdated method getting called and on some it does not. Are these devices or emulators? Are they in same testing condition. Do they have sim card? Do they differ in network configuration like connected to wifi or data? – MXC Oct 04 '18 at 03:24
  • Have a look at this comment https://stackoverflow.com/a/42995451/5140533 Some of the reason why it is working for some devices and not for others. – MXC Oct 04 '18 at 03:28

1 Answers1

0

I am not sure what your "import io.nlopez.smartlocation.SmartLocation;" does, but it is possible to get a null location from the device. If you have a working device trying disabling the location services while your app is running and see if you can reproduce it.

Check out: https://developer.android.com/training/location/retrieve-current

The location object may be null in the following situations:

  • Location is turned off in the device settings.
  • The result could be null even if the last location was previously retrieved because disabling location also clears the cache.
  • The device never recorded its location, which could be the case of a new device or a device that has been restored to factory settings.
  • Google Play services on the device has restarted, and there is no active Fused Location Provider client that has requested location after the services restarted. To avoid this situation you can create a new client and request location updates yourself. For more information, see Receiving Location Updates.
Ves
  • 387
  • 2
  • 10