Volley中的JsonArrayRequest不会将任何值传递给ListView

时间:2019-03-17 17:55:40

标签: java php android json android-volley

我正在尝试将Volley用于我的项目,并且我使用JsonArrayRequest()从PHP获得了JSON数组编码,并在ListView上进行了修改。我遵循了此页面上的教程: https://www.androidhive.info/2014/07/android-custom-listview-with-image-and-text-using-volley/

我的应用崩溃了,下面是错误。

2019-03-18 15:34:51.706 14999-14999/com.example.smartparkingapp E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.smartparkingapp, PID: 14999
    java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.app.Activity.getSystemService(java.lang.String)' on a null object reference
        at com.example.smartparkingapp.adapter.CarListAdapter.getView(CarListAdapter.java:48)
        at android.widget.AbsListView.obtainView(AbsListView.java:3180)
        at android.widget.ListView.makeAndAddView(ListView.java:2197)
        at android.widget.ListView.fillDown(ListView.java:824)
        at android.widget.ListView.fillFromTop(ListView.java:885)
        at android.widget.ListView.layoutChildren(ListView.java:1924)
        at android.widget.AbsListView.onLayout(AbsListView.java:2952)
        at android.view.View.layout(View.java:21054)
        at android.view.ViewGroup.layout(ViewGroup.java:6440)
        at android.support.constraint.ConstraintLayout.onLayout(ConstraintLayout.java:1915)
        at android.view.View.layout(View.java:21054)
        at android.view.ViewGroup.layout(ViewGroup.java:6440)
        at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1791)
        at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1635)
        at android.widget.LinearLayout.onLayout(LinearLayout.java:1544)
        at android.view.View.layout(View.java:21054)
        at android.view.ViewGroup.layout(ViewGroup.java:6440)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
        at android.view.View.layout(View.java:21054)
        at android.view.ViewGroup.layout(ViewGroup.java:6440)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
        at android.view.View.layout(View.java:21054)
        at android.view.ViewGroup.layout(ViewGroup.java:6440)
        at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1083)
        at android.view.View.layout(View.java:21054)
        at android.view.ViewGroup.layout(ViewGroup.java:6440)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
        at android.view.View.layout(View.java:21054)
        at android.view.ViewGroup.layout(ViewGroup.java:6440)
        at android.support.v7.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:444)
        at android.view.View.layout(View.java:21054)
        at android.view.ViewGroup.layout(ViewGroup.java:6440)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
        at android.view.View.layout(View.java:21054)
        at android.view.ViewGroup.layout(ViewGroup.java:6440)
        at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1791)
        at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1635)
        at android.widget.LinearLayout.onLayout(LinearLayout.java:1544)
        at android.view.View.layout(View.java:21054)
        at android.view.ViewGroup.layout(ViewGroup.java:6440)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
        at com.android.internal.policy.DecorView.onLayout(DecorView.java:966)
        at android.view.View.layout(View.java:21054)
        at android.view.ViewGroup.layout(ViewGroup.java:6440)
        at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:3043)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2730)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1859)
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:8087)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:911)
        at android.view.Choreographer.doCallbacks(Choreographer.java:723)
        at android.view.Choreographer.doFrame(Choreographer.java:658)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:897)
        at android.os.Handler.handleCallback(Handler.java:790)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:7000)
2019-03-18 15:34:51.707 14999-14999/com.example.smartparkingapp E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:441)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)

这是我的PHP代码,其中 car_list.php 要求来自 smart_parking_connect.php smart_parking_connect.php 的连接包含数据库变量。

>

smart_parking_config.php

<?php

define("DB_HOST", "localhost");
define("DB_USER", "root");
define("DB_PASSWORD", "garuda96");
define("DB_DATABASE", "mydb");

?>

smart_parking_connect.php

<?php

class Connect {
    public $conn;

    //connecting to database
    function Connect() {
        require_once('smart_parking_config.php');

        //connecting to mysql database
        $this->conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);

        //return database object
        return $this->conn; 
    }  
}?>

car_list.php

<?php

    require_once('smart_parking_connect.php');

    $connect = new Connect();

    $conn = $connect->conn;

    if($conn){

            $carResult = mysqli_query($conn, "SELECT carLicense, idCustomer FROM Car");

            while($obj=mysqli_fetch_object($carResult)){
                $car[] = array('idCustomer' => $obj->idCustomer, 'carLicense' => $obj->carLicense);
            }

            echo json_encode($car);

    } else {
        $response['success'] = 0;
        $response['message'] = "Connection failure";
        echo json_encode($response);

    }

?>

在Android方面,我为MainActivity.java创建了3个片段,并在'HomeFragment.java'中使用了JsonArrayRequest()。另一个片段运行正常。

HomeFragment.java (为简化起见,我删除了所有导入)

package com.example.smartparkingapp;    

public class HomeFragment extends Fragment {

    private static final String TAG = HomeFragment.class.getSimpleName();

    private static final String carListURL = Variable.connstr + "car_list.php";
    private ProgressDialog progressDialog;
    private List<Car> carList = new ArrayList<Car>();
    private CarListAdapter carListAdapter;
    private RequestQueue queue;

    private  FloatingActionButton assignCarButton;
    private TextView nameTextView;
    private TextView testTextView;
    private Button logoutButton;
    private ListView carListView;
    private SharedPreferencesConfig preferencesConfig;

    public HomeFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        String name, idCustomer;

        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        preferencesConfig = new SharedPreferencesConfig(getContext());

        assignCarButton = (FloatingActionButton) view.findViewById(R.id.assignCarButton);
        logoutButton = (Button) view.findViewById(R.id.logoutButton);
        nameTextView = (TextView) view.findViewById(R.id.nameTextView);
        testTextView = (TextView) view.findViewById(R.id.testTextView);

        name = preferencesConfig.readUsername();
        nameTextView.setText(name);

        idCustomer = Integer.toString(preferencesConfig.readId());

        carListView = (ListView) view.findViewById(R.id.carList);
        carListAdapter = new CarListAdapter(this, carList);
        carListView.setAdapter(carListAdapter);

        progressDialog = new ProgressDialog(getContext());
        progressDialog.setMessage("Loading...");
        progressDialog.show();    

        //Creating volley request obj
       JsonArrayRequest carReq = new JsonArrayRequest(carListURL,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        Log.d(TAG, response.toString());
                        hidePDialog();

                        //parsing JSON
                        for (int i = 0; i < response.length(); i++) {
                            try {

                                JSONObject obj = response.getJSONObject(i);
                                Car car = new Car();
                                car.setId(obj.getString("idCustomer"));
                                car.setCarPlate(obj.getString("carLicense"));

                                carList.add(car);
                                carListAdapter.notifyDataSetChanged();

                            } catch (JSONException e){
                                e.printStackTrace();
                            }

                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
                hidePDialog();
            }
        });

        AppController.getInstance().addToRequestQueue(carReq);

                assignCarButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        openDialog();
                    }
                });

            logoutButton.setOnClickListener(new View.OnClickListener(){
                @Override
                public void onClick(View v) {
                    Logout(getActivity());
                }
            });


        return view;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        hidePDialog();
    }

    public void openDialog() {
        NumberPlateDialog numberPlateDialog = new NumberPlateDialog();
        numberPlateDialog.show(getFragmentManager(), "Number Plate Dialog");
    }

    private void hidePDialog() {
        if (progressDialog!= null) {
            progressDialog.dismiss();
            progressDialog = null;
        }
    }

    public void Logout(Activity activity){

        preferencesConfig.writeLoginStatus(false);
        preferencesConfig.writeUsername("Name");
        startActivity(new Intent(getContext(), LoginActivity.class));
        activity.finish();
    }

}

Car.java

package com.example.smartparkingapp.Model;

public class Car {
    private String id;
    private String carPlate;

    public Car(){

    }

    public Car(String id, String carPlate) {
        this.id = id;
        this.carPlate = carPlate;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getCarPlate() {
        return carPlate;
    }

    public void setCarPlate(String carPlate) {
        this.carPlate = carPlate;
    }
}

AppController.java (我的单例)

package com.example.smartparkingapp.app;

public class AppController extends Application {

    public static final String TAG = AppController.class
            .getSimpleName();

    private RequestQueue mRequestQueue;

    private static AppController mInstance;

    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;
    }

    public static synchronized AppController getInstance() {
        return mInstance;
    }

    public RequestQueue getRequestQueue() {
        if (mRequestQueue == null) {
            mRequestQueue = Volley.newRequestQueue(getApplicationContext());
        }

        return mRequestQueue;
    }

    public <T> void addToRequestQueue(Request<T> req) {
        req.setTag(TAG);
        getRequestQueue().add(req);
    }

    public void cancelPendingRequests(Object tag) {
        if (mRequestQueue != null) {
            mRequestQueue.cancelAll(tag);
        }
    }
}

CarListAdapter.java

package com.example.smartparkingapp.adapter;
public class CarListAdapter extends BaseAdapter {
    private Activity activity;
    private Fragment fragment;
    private LayoutInflater layoutInflater;
    private List<Car> carItems;

    public CarListAdapter(Fragment fragment, List<Car> carItems) {
        this.fragment = fragment;
        this.carItems = carItems;
    }

    @Override
    public int getCount() {
        return carItems.size();
    }

    @Override
    public Object getItem(int position) {
        return carItems.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (layoutInflater == null)
            layoutInflater= (LayoutInflater) activity
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        if (convertView == null)
            convertView = layoutInflater.inflate(R.layout.car_layout_row, null);

        TextView idTextView = (TextView) convertView.findViewById(R.id.IdTextView);
        TextView numberPlatetextView = (TextView) convertView.findViewById(R.id.plateNumberTextView);

        Car c = carItems.get(position);

        idTextView.setText(String.valueOf(c.getId()));
        numberPlatetextView.setText(c.getCarPlate());

        return convertView;
    }
}

很抱歉,这么长的帖子。

1 个答案:

答案 0 :(得分:0)

您正在尝试在适配器中使用空activity。将活动对象从您的调用活动传递到CarListAdapter构造函数中

类似: 在您的HomeFragment中

carListAdapter = new CarListAdapter(this, carList, getActivity());

并在您的CarListAdapter中:

public class CarListAdapter extends BaseAdapter {
    private Activity activity;
    private Fragment fragment;
    private LayoutInflater layoutInflater;
    private List<Car> carItems;

    public CarListAdapter(Fragment fragment, List<Car> carItems, Activity activity) {
        this.fragment = fragment;
        this.carItems = carItems;
        this.activity = activity;
    }
.....

这是根据您显示的错误