Как создать столбцы в listview, используя данные JSON в Android Studio? - PullRequest
0 голосов
/ 19 декабря 2018

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

я прикрепил вывод, который я получил, а также выводя хочу отобразить.

Colleagues_Schedule.java

            package com.example.myapplication;

            import android.content.Context;
            import android.content.SharedPreferences;
            import android.graphics.Typeface;
            import android.os.AsyncTask;
            import android.os.Bundle;
            import android.support.v7.app.AppCompatActivity;
            import android.util.Log;
            import android.view.View;
            import android.widget.Button;
            import android.widget.GridLayout;
            import android.widget.LinearLayout;
            import android.widget.ListAdapter;
            import android.widget.ListView;
            import android.widget.SimpleAdapter;
            import android.widget.TableLayout;
            import android.widget.TableRow;
            import android.widget.TextView;
            import android.widget.Toast;

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

            import java.io.IOException;
            import java.io.InputStream;
            import java.io.OutputStream;
            import java.net.HttpURLConnection;
            import java.net.MalformedURLException;
            import java.net.URL;
            import java.text.DateFormat;
            import java.text.SimpleDateFormat;
            import java.util.ArrayList;
            import java.util.Calendar;
            import java.util.Date;
            import java.util.HashMap;

            public class Colleagues_Schedule extends AppCompatActivity {
            int i;
            String result1;
            int size=20;
            Context context;
            int Count=0;
            LinearLayout linearLayout;
            int datecount=1;
            Integer Nmaxclicks = 3;
            Integer Ncurrentnumber = 0;
            Integer Pmaxclicks = 4;
            Integer Pcurrentnumber = 0;
            TextView t1v,t2v,t3v,t4v;
            Button Next,Previous;
            JSONArray jsonArray_New = null;
            String[] ScheduleDates, StartTimes, Endtimes,Names;
            String ScheduleDate,StartTime,Endtime,Today,Tomarrow,Name,Password,Date1;
            TextView dat;
            private ArrayList<String> ScheduleDateArray = new ArrayList<>();
            private ArrayList<String> StartTimeArray = new ArrayList<>();
            private ArrayList<String> EndtimeArray = new ArrayList<>();
            private ArrayList<String> NameArray = new ArrayList<>();
            TableRow tbrow0,tbrow;
            DateFormat TW;
            TableLayout stk;
            Typeface boldTypeface = Typeface.defaultFromStyle(Typeface.BOLD);
            GridLayout mainGrid2;

            private String TAG = Colleagues_Schedule.class.getSimpleName();
            private ListView lv;
            ArrayList<HashMap<String, String>> contactList;

            @Override
            protected void onCreate(Bundle savedInstanceState)

            {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_colleagues__schedule);

            contactList = new ArrayList<>();
            lv = (ListView) findViewById(R.id.list);

            Next = (Button) findViewById(R.id.next);
            Previous = (Button) findViewById(R.id.back);
            linearLayout=(LinearLayout) findViewById(R.id.schedule);

            DateFormat TO = new SimpleDateFormat("yyyy-MM-dd");
            Today = TO.format(Calendar.getInstance().getTime());
            TW = new SimpleDateFormat("yyyy-MM-dd");


            call();


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

            Previous.setOnClickListener(new View.OnClickListener()
            {
                @Override
                public void onClick(View v)
                {

                } });


            }

            private Date Tomarrow(int datecount)
            {
            final Calendar cal = Calendar.getInstance();
            cal.add(Calendar.DATE, +datecount);
            return cal.getTime();
            }




            private void call()
            {
            context = getApplicationContext();
            SharedPreferences mPrefs = context.getSharedPreferences("identifier", Context.MODE_PRIVATE);
            Name = mPrefs.getString("Name", null);
            Password = mPrefs.getString("Password", null);
            Emp_Hour b = new Emp_Hour();
            Date1=Today;

            //Toast.makeText(context , "result" + Name + Password+ Today, Toast.LENGTH_LONG).show();
            b.execute(Name, Password, Date1);

            }

            class Emp_Hour extends AsyncTask<String, String, String>
            {

            @Override
            protected String doInBackground(String... params)
            {
                String name = params[0];
                String password = params[1];
                String today = params[2];
                String data="";
                int tmp;
                try
                {
                    URL url = new URL(Config_URLS.TAG_COLLEAGUES_SCHEDULE);
                    String urlParams =  "&Name="+name+"&Password="+password +"&Today="+today;
                    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                    httpURLConnection.setDoOutput(true);
                    OutputStream os = httpURLConnection.getOutputStream();
                    os.write(urlParams.getBytes());
                    os.flush();
                    os.close();
                    InputStream is = httpURLConnection.getInputStream();
                    while((tmp=is.read())!=-1)
                    {
                        data+= (char)tmp;
                    }
                    is.close();
                    httpURLConnection.disconnect();
                    return data;
                } catch (MalformedURLException e)
                {
                    e.printStackTrace();
                    return "Exception: "+e.getMessage();
                } catch (IOException e)
                {
                    e.printStackTrace();
                    return "Exception: "+e.getMessage();
                }




            }

            @Override
            protected void onPostExecute(String result)
            {
                if(result!=null)
                {

                    Hourslist(result);
                }else
                {
                    Toast.makeText(context , "result null", Toast.LENGTH_LONG).show();
                }
            }
            }


            private void Hourslist(String result)
            {

            String hourdetails;
            hourdetails=result;
            try
            {
                JSONObject jsonObj = new JSONObject(hourdetails);
                // Getting JSON Array node
                JSONArray contacts = jsonObj.getJSONArray("Colleagues_Schedule");
                // looping through All Contacts
                for (int i = 0; i < contacts.length(); i++)
                {
                    JSONObject c = contacts.getJSONObject(i);
                    //  String id = c.getString("id");
                    String name = c.getString("Name");
                    String scheduleDate = c.getString("ScheduleDate");
                    String startTime = c.getString("StartTime");
                    String endtime = c.getString("Endtime");

                    // tmp hash map for single contact
                    HashMap<String, String> contact = new HashMap<>();

                    // adding each child node to HashMap key => value
                    // contact.put("id", id);
                    contact.put("name", name);
                    contact.put("scheduleDate", scheduleDate);
                    contact.put("startTime", startTime);
                    contact.put("endtime", endtime);

                    // adding contact to contact list
                    contactList.add(contact);
                }
            } catch (final JSONException e)
            {
                Log.e(TAG, "Json parsing error: " + e.getMessage());
                runOnUiThread(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        Toast.makeText(getApplicationContext(),"Json parsing error: " + e.getMessage(),
                                Toast.LENGTH_LONG).show();
                    }
                });
            }

            ListAdapter adapter = new SimpleAdapter(
                    Colleagues_Schedule.this, contactList,
                    R.layout.list_item, new String[]{"name", "scheduleDate", "startTime", "endtime"},
                    new int[]{R.id.name, R.id.scheduleDate, R.id.startTime, R.id.endtime});

            lv.setAdapter(adapter);
            }



            }//end of main

activity_colleagues__schedule.xml

            <?xml version="1.0" encoding="utf-8"?>
            <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:app="http://schemas.android.com/apk/res-auto"
            xmlns:tools="http://schemas.android.com/tools"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="#3d455b"
            tools:context=".Colleagues_Schedule">
            <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:weightSum="1"
            tools:layout_editor_absoluteX="16dp"
            tools:layout_editor_absoluteY="58dp"
            tools:ignore="MissingConstraints">
            <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:orientation="vertical">
            <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="271dp"
            android:layout_weight="1"
            android:orientation="vertical"
            android:paddingTop="40dp">
            <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:layout_gravity="center"
            android:text="SCHEDULE OF COLLEAGUES"
            android:textColor="@android:color/white"
            android:textSize="30sp" />
            <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/dat"
            android:layout_centerInParent="true"
            android:layout_gravity="center"
            android:textColor="@android:color/white"
            android:textSize="30sp" />
            </LinearLayout>


            <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/schedule"
            android:layout_weight="1"
            android:orientation="vertical">

            <ListView
            android:id="@+id/list"
            android:text="Employees hour list"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" />
            </LinearLayout>


            </LinearLayout>

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

            <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center_horizontal"
            android:orientation="horizontal">
            <Button
            android:id="@+id/back"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="PREVIOUS" />


            <Button
            android:id="@+id/next"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="NEXT" />
            </LinearLayout>
            </LinearLayout>
            </LinearLayout>
            </android.support.constraint.ConstraintLayout>

list_item.xml

            <?xml version="1.0" encoding="utf-8"?>

            <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            >

            <TextView
            android:id="@+id/name"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:paddingBottom="2dip"
            android:paddingTop="6dip"
            android:background="#4EB1BA"
            android:textColor="@android:color/holo_red_dark"
            android:textSize="16sp"
            android:textStyle="bold" />

            <TextView
            android:id="@+id/scheduleDate"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:paddingBottom="2dip"
            android:background="#4EB1BA"
            android:textColor="@android:color/white"/>

            <TextView
            android:id="@+id/startTime"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:background="#4EB1BA"
            android:textColor="@android:color/black"
            android:textStyle="bold" />
            <TextView
            android:id="@+id/to"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:background="#4EB1BA"
            android:textColor="@android:color/black"
            android:text="TO"
            android:textStyle="bold" />
            <TextView
            android:id="@+id/endtime"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:background="#4EB1BA"
            android:textColor="@android:color/black"
            android:textStyle="bold" />
            </LinearLayout>

[Оригинальный вывод] 1 [ожидаемый результат] 2

1 Ответ

0 голосов
/ 19 декабря 2018

Чтобы создать такой макет, вам нужно создать два макета.Один для строки заголовка и один для строки списка.

Вы можете использовать LinearLayout, и если вы используете layout_weight на вашем TextViews, вы можете заставить их занимать даже место в макете.

Например, вот TextView.Если вы установите layout_width в 0dp, а layout_weight в 1, это заполнит как можно больше места.Если они все настроены так, они все займут даже место.Примечание: вы должны переместить это в styles.xml, чтобы вы могли легко применить это ко всем вашим Views.

<TextView
    android:id="@+id/name"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:gravity="center"
    tools:text="John Smith" />

Это будет ваш заголовок с вашими ярлыками.Поместите это над вашим ListView.

<!-- Layout for Header -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <TextView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="center"
        android:text="Name" />

    <TextView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="center"
        android:text="Date" />

    <TextView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="center"
        android:text="Start Time" />

    <TextView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="center"
        android:text="End Time" />
</LinearLayout>

И для вашего макета элемента.

<!-- Layout for ListView -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <TextView
        android:id="@+id/name"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="center"
        tools:text="John Smith" />

    <TextView
        android:id="@+id/scheduleDate"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="center"
        tools:text="2018-12-18" />

    <TextView
        android:id="@+id/startTime"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="center"
        tools:text="9:00 pm" />

    <TextView
        android:id="@+id/endtime"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="center"
        tools:text="10:00 pm" />
</LinearLayout>

И все выстроится правильно.

Example of what it should look like.

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