Пользовательский ListView не работает - PullRequest
0 голосов
/ 02 мая 2018

Я пытаюсь создать собственный ListView, и я думаю, что я сделал свой адаптер правильно. Я совершенно новичок в Android и не совсем понимаю все концепции с представлениями, адаптерами и т. Д.

Мой код сделан фрагментом, а не основной деятельностью. Я не знаю, повлияет ли это на то, как вы передаете материал в список и из него.

Я пытаюсь отобразить информацию, полученную из строки в формате JSON. Когда я запускаю свое приложение, список никогда не появляется, я не знаю, так ли это, потому что я передаю неправильное представление или что-то в этом роде. Он не падает.

personal_profile_fragment:

public class Personal_Profile_Fragment extends Fragment {

private charAdapter adapter;

ListView list;
ArrayList<charactors> charactorList;

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


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View v = inflater.inflate(R.layout.fragment_personal__profile_, container, false);

    Bundle bundle = getArguments();
    String JSON = bundle.getString("JSON");

    parseJson(JSON);

    list = (ListView)v.findViewById(R.id.list);
    charactorList = new ArrayList<charactors>();
    adapter = new charAdapter(getContext(), charactorList);
    list.setAdapter(adapter);

    return v;
}

private void parseJson(String json) {
    try {
        JSONObject chars = new JSONObject(json);
        JSONArray charArray = chars.getJSONArray("heroes");

        for (int i = 0; i<charArray.length(); i++) {
            JSONObject realCharacter = charArray.getJSONObject(i);

            charactors charactor = new charactors();
            charactor.setName(realCharacter.getString("name"));
            charactor.setClassType(realCharacter.getString("class"));
            charactor.setLevel(realCharacter.getString("level"));
            charactor.setParagonLevel(realCharacter.getString("paragonLevel"));
            charactor.setHardcore(realCharacter.getString("hardcore"));
            charactor.setSeasonal(realCharacter.getString("seasonal"));

            charactorList.add(charactor);
        }

    } catch(Exception e) {

    }
}

}

personal_profile.xml

<FrameLayout 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:id="@+id/personalProfileFragment"
tools:context="com.hfad.diablo3assistant.Personal_Profile_Fragment">

<!-- TODO: Update blank fragment layout -->

<android.support.constraint.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ListView
        android:id="@+id/list"
        android:layout_width="368dp"
        android:layout_height="551dp"
        tools:layout_editor_absoluteX="8dp"
        tools:layout_editor_absoluteY="8dp" />
</android.support.constraint.ConstraintLayout>
</FrameLayout>

row.xml:

<?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">

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginStart="17dp"
        android:layout_marginTop="34dp"
        android:text="TextView" />

    <TextView
        android:id="@+id/classType"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignStart="@+id/name"
        android:layout_below="@+id/name"
        android:layout_marginTop="12dp"
        android:text="TextView" />

    <TextView
        android:id="@+id/level"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignStart="@+id/classType"
        android:layout_below="@+id/classType"
        android:layout_marginTop="15dp"
        android:text="TextView" />

    <TextView
        android:id="@+id/paragonLevel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignStart="@+id/level"
        android:layout_below="@+id/level"
        android:layout_marginTop="15dp"
        android:text="TextView" />

    <TextView
        android:id="@+id/hardcore"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignEnd="@+id/paragonLevel"
        android:layout_below="@+id/paragonLevel"
        android:layout_marginTop="13dp"
        android:text="TextView" />

    <TextView
        android:id="@+id/seasonal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignStart="@+id/hardcore"
        android:layout_below="@+id/hardcore"
        android:layout_marginTop="20dp"
        android:text="TextView" />

</RelativeLayout>
</LinearLayout>

класс персонажей:

public class charactors {
private String name;
private String classType;
private String level;
private String paragonLevel;
private String hardcore;
private String seasonal;

public charactors() {

}



public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getClassType() {
    return classType;
}

public void setClassType(String classType) {
    this.classType = classType;
}

public String getLevel() {
    return level;
}

public void setLevel(String level) {
    this.level = level;
}

public String getParagonLevel() {
    return paragonLevel;
}

public void setParagonLevel(String paragonLevel) {
    this.paragonLevel = paragonLevel;
}

public String getHardcore() {
    return hardcore;
}

public void setHardcore(String hardcore) {
    this.hardcore = hardcore;
}

public String getSeasonal() {
    return seasonal;
}

public void setSeasonal(String seasonal) {
    this.seasonal = seasonal;
}

}

Адаптер Charactor:

public class charAdapter extends ArrayAdapter<charactors> {
private final Context context;
private final ArrayList<charactors> charactorsArrayList;

public charAdapter(Context context, ArrayList<charactors> charactorsArrayList) {

    super(context, R.layout.row, charactorsArrayList);

    this.context = context;
    this.charactorsArrayList = charactorsArrayList;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    // 1. Create inflater
    LayoutInflater inflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    // 2. Get rowView from inflater
    View rowView = inflater.inflate(R.layout.row, parent, false);

    // 3. Get the two text view from the rowView
    TextView name = (TextView) rowView.findViewById(R.id.name);
    TextView classType = (TextView) rowView.findViewById(R.id.classType);
    TextView level = (TextView) rowView.findViewById(R.id.level);
    TextView paragonLevel = (TextView) rowView.findViewById(R.id.paragonLevel);
    TextView hardcore = (TextView) rowView.findViewById(R.id.hardcore);
    TextView seasonal = (TextView) rowView.findViewById(R.id.seasonal);

    // 4. Set the text for textView
    name.setText("Name: "+charactorsArrayList.get(position).getName());
    classType.setText("Class: "+charactorsArrayList.get(position).getClassType());
    level.setText("Level: "+charactorsArrayList.get(position).getLevel());
    paragonLevel.setText("Paragon: "+charactorsArrayList.get(position).getParagonLevel());
    hardcore.setText("Hardcore: "+charactorsArrayList.get(position).getHardcore());
    classType.setText("Seasonal: "+charactorsArrayList.get(position).getSeasonal());

    // 5. retrn rowView
    return rowView;
}
}

1 Ответ

0 голосов
/ 02 мая 2018

Реализация getView() вашего адаптера неэффективна , но выглядит функционально правильной . Я думаю, что проблема просто простая ошибка в вашем onCreateView():

parseJson(JSON);
...
charactorList = new ArrayList<charactors>();
adapter = new charAdapter(getContext(), charactorList);

Похоже, вы анализируете строку JSON, а затем сразу же отбрасываете работу синтаксического анализа, присваивая new ArrayList charactorList.

На самом деле, если взглянуть немного глубже, кажется, что charactorList равен нулю, когда parseJson() работает (но блок catch скрывает это от вас). Итак, вы просто хотите немного изменить этот код:

charactorList = new ArrayList<charactors>();
parseJson(JSON);
...
adapter = new charAdapter(getContext(), charactorList);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...