ANDroid不显示自定义适配器

时间:2017-06-18 14:37:02

标签: android listview android-fragments android-adapter

我正在研究一个vtc应用程序,我需要在主屏幕上显示客户端的命令。 我选择了使用适配器自定义列表视图的方式,但是当我启动应用程序时,除了页面标题之外,屏幕上没有任何内容。 我划分了适配器代码和片段代码(是的,我在一个片段中工作),我想对你的代码有你的意见。 片段:

    package com.cmn.cmnvtc;

        import android.Manifest;
    import android.app.Dialog;
    import android.app.Fragment;
    import android.content.Context;
    import android.content.Intent;
    import android.content.pm.PackageManager;
    import android.location.Location;
    import android.net.Uri;
    import android.os.Build;
    import android.os.Bundle;
    import android.provider.Settings;
    import android.support.annotation.NonNull;
    import android.support.annotation.Nullable;
    import android.support.design.widget.Snackbar;
    import android.support.v4.app.ActivityCompat;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.AdapterView;
    import android.widget.ArrayAdapter;
    import android.widget.Button;
    import android.widget.LinearLayout;
    import android.widget.ListView;
    import android.widget.RelativeLayout;
    import android.widget.TextView;
    import android.widget.Toast;

    import com.android.volley.RequestQueue;
    import com.android.volley.Response;
    import com.android.volley.toolbox.Volley;
    import com.google.android.gms.common.ConnectionResult;
    import com.google.android.gms.common.GoogleApiAvailability;
    import com.google.android.gms.common.api.GoogleApiClient;
    import com.google.android.gms.location.LocationListener;
    import com.google.android.gms.location.LocationRequest;
    import com.google.android.gms.location.LocationServices;
    import com.google.android.gms.maps.CameraUpdate;
    import com.google.android.gms.maps.CameraUpdateFactory;
    import com.google.android.gms.maps.GoogleMap;
    import com.google.android.gms.maps.MapFragment;
    import com.google.android.gms.maps.OnMapReadyCallback;
    import com.google.android.gms.maps.model.LatLng;
    import com.google.android.gms.maps.model.Marker;
    import com.google.android.gms.maps.model.MarkerOptions;

    import org.json.JSONException;
    import org.json.JSONObject;

    import java.util.ArrayList;
    import java.util.List;


    public class MainPageFragment1 extends Fragment implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener{

        private LinearLayout containerView;
        private TextView NoCommand;
        private UserLocalStore userLocalStore;
        private List<Courses> coursesList;
        private ListView lvCourses;
        private CoursesAdapter coursesAdapter;
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            View v = inflater.inflate(R.layout.fragment_main1, container, false);
            userLocalStore = new UserLocalStore(getActivity());
            NoCommand = (TextView) v.findViewById(R.id.NoCommand);
            lvCourses = (ListView) v.findViewById(R.id.lvCourses);
            coursesList = new ArrayList<>();
            final Response.Listener<String> responseListener = new Response.Listener<String>(){


                @Override
                public void onResponse(String response) {
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        boolean success = jsonObject.getBoolean("success");
                        if(success){
                            int count = jsonObject.getInt("count");

                            for(int i=0; i<count; i++) {

                                JSONObject obj = jsonObject.getJSONObject(String.valueOf(i));
                                String origin = obj.getString("origin");
                                String destination = obj.getString("destination");
                                String date_depart = obj.getString("date_depart");
                                String heure_depart = obj.getString("heure_depart");
                                int nb_passagers = Integer.parseInt(obj.getString("nb_passagers"));
                                float prix = Float.parseFloat(obj.getString("prix"));
                                String mode_paiement = obj.getString("paiement");
                                String etat_paiement = obj.getString("course_payee");


                                Courses course = new Courses(origin, destination, date_depart, heure_depart, nb_passagers, prix
                                , mode_paiement, etat_paiement);
                                coursesList.add(course);
                            }

                        }else{
                            NoCommand.setEnabled(true);
                            NoCommand.setText("Oups... Vous n'avez commandé aucune course pour le moment.");
                        }

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

                }
            };
            User currentUser = userLocalStore.getLoggedInUser();
            final GetAllCourseRequest getAllCourse = new GetAllCourseRequest(currentUser.user_id,responseListener);
            RequestQueue queue = Volley.newRequestQueue(getActivity());
            queue.add(getAllCourse);

            coursesAdapter = new CoursesAdapter(getActivity(), coursesList);
            lvCourses.setAdapter(coursesAdapter);
            lvCourses.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Toast.makeText(getActivity(), "CLicked", Toast.LENGTH_SHORT).show();
                }
            });


            if (googleServicesAvailable()) {
                containerView = (LinearLayout) v.findViewById(R.id.containerView);
                askForPermission();
            }

            return v;
        }

        public boolean googleServicesAvailable() {
            GoogleApiAvailability api = GoogleApiAvailability.getInstance();
            int isAvaibable = api.isGooglePlayServicesAvailable(getActivity());
            if (isAvaibable == ConnectionResult.SUCCESS) {
                return true;
            } else if (api.isUserResolvableError(isAvaibable)) {
                Dialog dialog = api.getErrorDialog(getActivity(), isAvaibable, 0);
                dialog.show();
            } else {
                Toast.makeText(getActivity(), "Can't connect to play services", Toast.LENGTH_SHORT).show();
            }
            return false;
        }

        private void explain() {
            Snackbar.make(containerView, "Cette permission est nécessaire pour vous géolocalisez", Snackbar.LENGTH_LONG).setAction("Activer", new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    askForPermission();
                }
            }).show();
        }
        private void askForPermission() {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                requestPermissions(new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.ACCESS_COARSE_LOCATION}, 2);
            }
        }
        @Override
        public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
            if (requestCode == 2) {
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (shouldShowRequestPermissionRationale(permissions[0]) == false) {
                        displayOptions();
                    } else {
                        explain();
                    }
                }
                if (grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (shouldShowRequestPermissionRationale(permissions[1]) == false) {
                        displayOptions();
                    } else {
                        explain();
                    }
                }
            }
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
        private void displayOptions() {
            Snackbar.make(containerView, "Vous avez désactivé la permission", Snackbar.LENGTH_LONG).setAction("Paramètres", new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    final Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                    final Uri uri = Uri.fromParts("package", getActivity().getPackageName(), null);
                    intent.setData(uri);
                    startActivity(intent);
                }
            }).show();
        }

        @Override
        public void onConnected(@Nullable Bundle bundle) {

        }

        @Override
        public void onConnectionSuspended(int i) {

        }

        @Override
        public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

        }
    }

我的自定义适配器:

package com.cmn.cmnvtc;

import android.content.Context;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.TextView;

import org.w3c.dom.Text;

import java.util.List;

/**
 * Created by Wild Shadow on 18/06/2017.
 */
public class CoursesAdapter extends BaseAdapter {

    private List<Courses> coursesList;
    private Context ctx;


    public CoursesAdapter(Context context, List<Courses> coursesList) {
        this.ctx = context;
        this.coursesList = coursesList;
    }

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

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

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View v = View.inflate(ctx, R.layout.row_courses, null);
        TextView adrOrigin = (TextView) v.findViewById(R.id.adrOriginList);
        TextView adrDestinaiton = (TextView) 
v.findViewById(R.id.adrDestList);
        TextView dateDepart = (TextView) v.findViewById(R.id.dateDepList);
        TextView heureDepart = (TextView) 
v.findViewById(R.id.heureDepList);

        ImageButton viewDetails = (ImageButton) 
      v.findViewById(R.id.viewDetailsCourse);

        adrOrigin.setText(coursesList.get(position).getOrigin());
        adrDestinaiton.setText(coursesList.get(position).getDestination());
        dateDepart.setText(coursesList.get(position).getDate_depart());
        heureDepart.setText(coursesList.get(position).getHeure_depart());

        return v;
    }
}

模型布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="6dp">

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <LinearLayout
            android:orientation="horizontal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="5dp">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/ic_depart_courselist"/>

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/adrOriginList"
                android:textSize="17dp"
                android:textColor="#000"
                android:paddingTop="3dp"
                android:text=" :  Adresse de départ"/>

        </LinearLayout>

        <LinearLayout
            android:orientation="horizontal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/ic_destination_courselist"/>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/adrDestList"
                android:paddingTop="3dp"
                android:textColor="#000"
                android:textSize="17dp"
                android:text=" :  Adresse d'arrivée"
                android:layout_marginBottom="5dp"/>

        </LinearLayout>

        <LinearLayout
            android:orientation="horizontal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/ic_date_depart_courselist"/>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/dateDepList"
                android:paddingTop="3dp"
                android:textColor="#000"
                android:textSize="17dp"
                android:text=" :  date de départ"
                android:layout_marginBottom="3dp"
                android:layout_marginRight="20dp"/>

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/ic_heure_dep_courselist"/>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/heureDepList"
                android:paddingTop="3dp"
                android:textColor="#000"
                android:textSize="17dp"
                android:text=" :  Heure"
                android:layout_marginBottom="3dp"/>

            <ImageButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/ic_details_courselist"
                android:layout_marginLeft="65dp"
                android:id="@+id/viewDetailsCourse"
                android:paddingTop="5dp"
                android:background="?android:selectableItemBackground"/>

        </LinearLayout>



    </LinearLayout>
</LinearLayout>

和listview:

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingTop="10dp"
    android:theme="@style/AppTheme"
    tools:context="com.cmn.cmnvtc.MainPageFragment1">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center_horizontal">
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textAlignment="center"
            android:id="@+id/TitleListCommand"
            android:textSize="25dp"
            android:layout_marginBottom="15dp"
            android:textColor="#727574"
            android:text="Liste de mes courses "/>

        <ListView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/TitleListCommand"
            android:layout_alignParentStart="true"
            android:id="@+id/lvCourses"></ListView>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="200dp"
            android:textColor="#969696"
            android:layout_marginLeft="20dp"
            android:layout_marginRight="20dp"
            android:textSize="15dp"
            android:textAlignment="center"
            android:id="@+id/NoCommand"
            android:text=""
            android:enabled="false"/>


    </RelativeLayout>


</ScrollView>

我希望你能帮助我找到错误,如果你想要更多,请尝试解释我如何优化我的代码。 TY

1 个答案:

答案 0 :(得分:0)

填写列表后,您应该在ResponseListener中调用notifyDataSetChanged()。

            @Override
            public void onResponse(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    boolean success = jsonObject.getBoolean("success");
                    if(success){
                        int count = jsonObject.getInt("count");

                        for(int i=0; i<count; i++) {
                            ...
                            coursesList.add(course);
                        }
                        //notify adapter about change in data
                        coursesAdapter.notifyDataSetChanged();
                    }else{
                        NoCommand.setEnabled(true);
                        NoCommand.setText("Oups... Vous n'avez commandé aucune course pour le moment.");
                    }

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

            }
        };