Как я могу отобразить массив моего списка в фрагменте? - PullRequest
0 голосов
/ 12 июня 2019

Я работаю в системе бронирования

Мне нужно отобразить массив в списке Я пробовал некоторые коды, однако они не работают

Помогите мне, пожалуйста

Заранее спасибо;

Это часть OnCreateView

public class Res extends Fragment {
    ListView lv;
    ArrayAdapter adapter;
    ProgressDialog loading;

    @Override
    public View onCreateView(LayoutInflater inflater,
                             ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_res, container, false);
        lv=view.findViewById(R.id.lview);

        getReservations();
        return view;
    }

и эта часть предназначена для получения данных с листа google, для которых есть резервирования, и для отображения резервирований в моем списке просмотра с помощью адаптера.

private void getReservations() {

        loading =  ProgressDialog.show(getActivity(),"Rezervasyonlar yukleniyor","Lutfen Bekleyiniz",false,true);

        StringRequest stringRequest = new StringRequest(Request.Method.GET, "HERE I HAVE THE URL ..WORKS ON GOOGLE APP SCRIPT BUT PROBLEM IS ABOUT MY CODE ",
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        parseItems(response);
                    }
                },

                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                }
        );
        int socketTimeOut = 50000;
        RetryPolicy policy = new DefaultRetryPolicy(socketTimeOut, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);

        stringRequest.setRetryPolicy(policy);

        RequestQueue queue = Volley.newRequestQueue(getActivity());
        queue.add(stringRequest);
    }

    private void parseItems(String jsonResponse) {
        ArrayList<HashMap<String, String>> list = new ArrayList<>();

        try {
            JSONObject jobj = new JSONObject(jsonResponse);
            JSONArray jarray = jobj.getJSONArray("items");


            for (int i = 0; i < jarray.length(); i++) {

                JSONObject jo = jarray.getJSONObject(i);

                final String name = jo.getString("name");
                final String phone = jo.getString("phone");
                final String email = jo.getString("email");
                final String arriving = jo.getString("arriving");
                final String departure = jo.getString("departure");
                final String pax = jo.getString("pax");
                final String roomtype = jo.getString("roomtype");
                final String rate = jo.getString("rate");
                final String address = jo.getString("addres");
                final String company = jo.getString("company");
                final String agency = jo.getString("agency");
                final String ratecode= jo.getString("ratecode");

                HashMap<String, String> item  = new HashMap<>();
                item.put("name",name);
                item.put("email",email);
                item.put("phone",phone);
                item.put("arriving",arriving);
                item.put("departure",departure);
                item.put("company",company);
                item.put("pax",pax);
                item.put("roomtype",roomtype);
                item.put("rate",rate);
                item.put("address",address);
                item.put("agency",agency);
                item.put("ratecode",ratecode);

                list.add(item);


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


        //adapter = new SimpleAdapter(getActivity(),list,R.layout.getres,
                //new String[]{"name","phone","email","arriving","departure","pax","roomtype","rate","address","company","agency"},new int[]{R.id.namev,R.id.phonev,R.id.emailv,R.id.checkv,R.id.depv,R.id.personv,R.id.roomtypev,R.id.ratev,R.id.adresv,R.id.companyv,R.id.agencyv});

        //ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,list);
        adapter = new ArrayAdapter(getActivity().getApplicationContext(), android.R.layout.simple_list_item_1, list);


        lv.setAdapter(adapter);
        lv.setCacheColorHint(getResources().getColor(android.R.color.white   ));
        loading.dismiss();

    }

Здесь у меня есть XML-файлы с текстовыми представлениями и списками

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:background="@android:color/holo_red_light"
    tools:context=".Res">


    <ListView
        android:id="@+id/lview"
        style="@android:style/Widget.Holo.ListView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:cacheColorHint="@android:color/background_light" />
</RelativeLayout>

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TableLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/design_default_color_primary">

        <TableRow
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@android:color/holo_blue_light">

            <TextView
                android:id="@+id/namev"
                android:layout_width="157dp"
                android:layout_height="match_parent"
                android:ems="10"
                android:hint="Name"
                android:inputType="textPersonName" />

            <TextView
                android:id="@+id/emailv"
                android:layout_width="121dp"
                android:layout_height="match_parent"
                android:layout_marginStart="5dp"
                android:ems="10"
                android:hint="E-mail"
                android:inputType="textPersonName" />

            <TextView
                android:id="@+id/phonev"
                android:layout_width="70dp"
                android:layout_height="wrap_content"
                android:ems="10"
                android:hint="Phone"
                android:inputType="number" />
        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@android:color/holo_orange_light">

            <TextView
                android:id="@+id/companyv"
                android:layout_width="111dp"
                android:layout_height="wrap_content"
                android:ems="10"
                android:hint="Company"
                android:inputType="textPersonName" />

            <TextView
                android:id="@+id/adresv"
                android:layout_width="132dp"
                android:layout_height="wrap_content"
                android:layout_marginStart="5dp"
                android:ems="10"
                android:hint="Address"
                android:inputType="textPersonName" />

            <TextView
                android:id="@+id/agencyv"
                android:layout_width="91dp"
                android:layout_height="match_parent"
                android:ems="10"
                android:hint="Agency"
                android:inputType="textPersonName" />

        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@android:color/holo_blue_light">


            <TextView
                android:id="@+id/nationv"
                android:layout_width="105dp"
                android:layout_height="wrap_content"
                android:ems="10"
                android:hint="Natinality"
                android:inputType="textPersonName" />

            <TextView
                android:id="@+id/idnov"
                android:layout_width="143dp"
                android:layout_height="wrap_content"
                android:ems="10"
                android:hint="ID number"
                android:inputType="textPersonName" />

        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@android:color/holo_orange_light">

            <TextView
                android:id="@+id/checkv"
                android:layout_width="111dp"
                android:layout_height="wrap_content"
                android:ems="10"
                android:hint="Arriving"
                android:inputType="date" />

            <TextView
                android:id="@+id/depv"
                android:layout_width="160dp"
                android:layout_height="wrap_content"
                android:ems="10"
                android:hint="Departure"
                android:inputType="date" />
        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@android:color/holo_blue_light">

            <TextView
                android:id="@+id/roomprv"
                android:layout_width="137dp"
                android:layout_height="wrap_content"
                android:ems="10"
                android:hint="Room Preference"
                android:inputType="textPersonName" />

            <TextView
                android:id="@+id/roomtypev"
                android:layout_width="155dp"
                android:layout_height="wrap_content"
                android:ems="10"
                android:hint="Room Tye"
                android:inputType="textPersonName" />
        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@android:color/holo_orange_light">

            <TextView
                android:id="@+id/textView4"
                android:layout_width="113dp"
                android:layout_height="match_parent"
                android:layout_marginTop="0dp"
                android:gravity="center_vertical"
                android:text="Pérson" />

            <TextView
                android:id="@+id/personv"
                android:layout_width="134dp"
                android:layout_height="wrap_content"
                android:autofillHints=""
                android:ems="10"
                android:gravity="center|center_vertical"
                android:inputType="number"
                android:text="0" />


        </TableRow>
        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@android:color/holo_blue_light">

            <TextView
                android:id="@+id/ratecodev"
                android:layout_width="114dp"
                android:layout_height="wrap_content"
                android:ems="10"
                android:hint="Rate Code"
                android:inputType="textPersonName" />

            <TextView
                android:id="@+id/ratev"
                android:layout_width="151dp"
                android:layout_height="wrap_content"
                android:ems="10"
                android:hint="Rate"
                android:inputType="textPersonName" />



        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@android:color/holo_orange_light"
            android:gravity="center">

        </TableRow>
    </TableLayout>

</FrameLayout>

1 Ответ

2 голосов
/ 12 июня 2019

Не знаю точно, в чем именно проблема на вашей стороне. Но я бы предложил сделать эти вещи, чтобы подтвердить, где проблема.

Убедитесь, что вы что-то получаете по сетевому вызову

Эта функция включена в ваш запрос залпа.

            public void onResponse(String response) {
                parseItems(response);
            }

Вы удостоверились, что ответ содержит допустимую строку JSON, содержащую ваши элементы ?. Поэтому сначала попробуйте распечатать этот ответ в журнале и посмотреть, получаете ли вы что-то из запроса или нет.

Если вы что-то получаете в своем ответе, и все же это не работает. Затем прокомментируйте скриншот или строку ответа здесь. Также, если вы можете указать свой URL-адрес, куда вы отправляете запрос на получение данных, тогда мне будет легко проверить, почему он не работает в вашем случае.

Дополнительно вы должны сделать это. Это не является причиной вашей проблемы, но вы должны использовать ее следующим образом. Эта строка вашего кода

 lv=view.findViewById(R.id.lview); 
 getReservations();

Переопределите функцию onViewCreated () и поместите эти две строки внутри этой функции. Но проблема не в этом

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...