TypeToken без класса? - PullRequest
       20

TypeToken без класса?

0 голосов
/ 12 апреля 2020

Я пытаюсь сохранить свои данные с помощью Gson. Я следовал учебнику и застрял.

Type type = new TypeToken<ArrayList<**HERE SHOULD BE A CLASS**>>() {}.getType();

Проблема в том, что у меня нет класса для Предметов в Arraylist. Есть ли способ обойти эту проблему (я также использую фрагменты)?

Это мой адаптер

package com.example.barryblack;

import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;
import java.util.zip.Inflater;


public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private ArrayList<String> cards;

public MyAdapter(ArrayList<String> countries) {
    this.cards = countries;
}

@Override
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
    View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.example_item, viewGroup, 
false);
    return new ViewHolder(view);
}

@Override
public void onBindViewHolder(MyAdapter.ViewHolder viewHolder, int i) {

    viewHolder.taskText.setText(cards.get(i));


}

@Override
public int getItemCount() {
    return cards.size();
}

public class ViewHolder extends RecyclerView.ViewHolder{

    private TextView taskText;
    private EditText tv_editText;
    private Button insertButton;
    private Button tv_button;
    private int amountofclicks = 1;


    public ViewHolder(View view) {
        super(view);

        taskText = view.findViewById(R.id.tv_country);
        tv_button = view.findViewById(R.id.tv_button);
        tv_editText = view.findViewById(R.id.editTask);
        insertButton = view.findViewById(R.id.button_insert);

        tv_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                amountofclicks++;
                        if (amountofclicks % 2 == 0) {
                            tv_button.setBackgroundResource(R.drawable.button_green);
                        }else
                            tv_button.setBackgroundResource(R.drawable.button_red);
            }
        });
    }
}
}

А это мой фрагмент

public class FragmentPage extends Fragment {

private MyAdapter mAdapter;
private EditText editTask;
private ArrayList items;
private Button insertbtn;
private TextView taskText;
private ProgressBar progressBar;
private int progressStatus = 0;
private String task;


@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable 
 Bundle savedInstanceState) {
    loadData();
    CreateExampleList();

    View view = inflater.inflate(R.layout.page_fragment, container, false);

    RecyclerView recyclerView = view.findViewById(R.id.listRecyclerView);
    taskText = view.findViewById(R.id.tv_country);
    insertbtn = view.findViewById(R.id.button_insert);
    editTask = view.findViewById(R.id.editTask);

    insertbtn.setEnabled(false);

    editTask.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            String taskInput = editTask.getText().toString().trim();
            insertbtn.setEnabled(!taskInput.isEmpty());
        }

        @Override
        public void afterTextChanged(Editable s) {
            task = editTask.getText().toString().trim();
        }
    });

    insertbtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            InsertItem();
            SaveData();
            editTask.setText(null);
        }
    });

    recyclerView.setHasFixedSize(true);

    RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
    new ItemTouchHelper(itemTouchHelperCallback).attachToRecyclerView(recyclerView);
    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setItemViewCacheSize(500);
    mAdapter = new MyAdapter(items);
    recyclerView.setAdapter(mAdapter);

    return view;
}

private void SaveData(){
    SharedPreferences sharedPreferences = this.getActivity().getSharedPreferences("shared 
  prefernces", MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    Gson gson = new Gson();
    String json = gson.toJson(items);
    editor.putString("task list", json);
    editor.apply();
}

private void loadData() {
    SharedPreferences sharedPreferences = this.getActivity().getSharedPreferences("shared 
 prefernces", MODE_PRIVATE);
    Gson gson = new Gson();
    String json = sharedPreferences.getString("task list", null);
    Type type = new TypeToken<ArrayList<>>() {}.getType();
    items = gson.fromJson(json, type);

    if (items == null) {
        items = new ArrayList<>();
    }
}

public void InsertItem() {
    // task = editTask.getText().toString().trim();

    items.add(task);
    mAdapter.notifyDataSetChanged();

}

private void CreateExampleList() {
    items = new ArrayList<>();
}

ItemTouchHelper.SimpleCallback itemTouchHelperCallback = new ItemTouchHelper.SimpleCallback(0, 
ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
    @Override
    public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder 
viewHolder, @NonNull RecyclerView.ViewHolder target) {
        return false;
    }

    @Override
    public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
        items.remove(viewHolder.getAdapterPosition());
        mAdapter.notifyItemRemoved(viewHolder.getAdapterPosition());
    }
 };
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...