Кнопка фрагмента для открытия списка в другом фрагменте

#java #android #listview #android-fragments #button

#java #Android #просмотр списка #android-фрагменты #кнопка

Вопрос:

У меня возникли проблемы с получением данных во фрагменте, где я записываю данные с помощью кнопки в этом же фрагменте, которые будут отображаться в списке в другом фрагменте, у меня нет проблем с вызовом фрагмента, но список не загружается или не отображается. Данные загружаются, потому что из голосового режима я могу видеть их из этого списка… Кто-нибудь может мне помочь? Я довольно новичок, поэтому простое объяснение или помощь мне бы очень помогли. Если вам нужно увидеть больше кода, дайте мне знать в комментариях.

Выбор фрагмента визуализации

 package it.alfacod.eaglevoice.Fragments;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

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

import it.alfacod.eaglevoice.Activities.InventoryActivity;
import it.alfacod.eaglevoice.Adapters.ListOutputCursorAdapter;
import it.alfacod.eaglevoice.AppContext;
import it.alfacod.eaglevoice.Database.DBContract;
import it.alfacod.eaglevoice.Database.DBIOFields;
import it.alfacod.eaglevoice.Interfaces.NotifyListener;
import it.alfacod.eaglevoice.R;
import vocemaindll.Engine;

import static android.content.ContentValues.TAG;
import static it.alfacod.eaglevoice.AppContext.dBManager;
import static it.alfacod.eaglevoice.AppContext.vibrationTime;

public class FragVisualizationSelection extends Fragment implements View.OnClickListener {


    private String sort_time_asc = DBContract.COLUMN_DATE   " ASC";
    private String sort_time_desc = DBContract.COLUMN_DATE  " DESC";
    private String sort_barcode_asc = DBContract.COLUMN_BARCODE   " ASC";
    private String sort_barcode_desc = DBContract.COLUMN_BARCODE   " DESC";
    private String sort_color_asc = DBContract.COLUMN_COLORE   " ASC";
    private String sort_color_desc = DBContract.COLUMN_COLORE   " DESC";
    private String sort_quantita_asc = DBContract.COLUMN_QUANTITA   " ASC";
    private String sort_quantita_desc = DBContract.COLUMN_QUANTITA   " DESC";
    private String sort_position_asc = DBContract.COLUMN_POSITION   " ASC";
    private String sort_position_desc = DBContract.COLUMN_POSITION   " DESC";

    private String uniArrow_down = "u21E9";
    private String uniArrow_up = "u21E7";

    public String sort_lastchoice;

    public ListOutputCursorAdapter outputAdapter;
    public ListView listView;
    private Cursor resu<
    NotifyListener notifyListener;
    Toolbar toolbar;
    private View view;
    public List<DBIOFields> selectedList;



    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.frag_list_select, container, false);

        Button finish = (Button) view.findViewById(R.id.bt_finish);
        Button back = (Button) view.findViewById(R.id.bt_back);
        sort_lastchoice = sort_time_asc;


        toolbar = view.findViewById(R.id.m_toolbar);
        ((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);

        TextView code = (TextView) view.findViewById(R.id.sticky_code);
        code.setOnClickListener(this);

        TextView date = (TextView) view.findViewById(R.id.sticky_datetime);
        date.setOnClickListener(this);

        TextView position = (TextView) view.findViewById(R.id.sticky_position);
        position.setOnClickListener(this);

        TextView colore = (TextView) view.findViewById(R.id.sticky_color);
        colore.setOnClickListener(this);

        TextView quantita = (TextView) view.findViewById(R.id.sticky_quantita);
        quantita.setOnClickListener(this);

        finish.setOnClickListener(this);
        back.setOnClickListener(this);

        listView = (ListView) view.findViewById(R.id.entryList);

        //un giorno quando lo si rende dinamico bisogna cambiare questa parte
        selectedList = new ArrayList<DBIOFields>();
        selectedList.add(new DBIOFields(getString(R.string.db_barcode)));
        selectedList.add(new DBIOFields(getString(R.string.db_colore)));
        selectedList.add(new DBIOFields(getString(R.string.db_quantita)));
        selectedList.add(new DBIOFields(getString(R.string.db_position)));


        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                AppContext.viber.vibrate(vibrationTime);
                result = (Cursor) listView.getAdapter().getItem(position);
                Log.d(TAG, "Frag VisualizationSelection: setOnItemClickListener: Hai cliccato su "   position);
                if (result.moveToPosition(position)) {
                    getOutputDatafromCursor(position);
                    launchUserDialog();
                }
            }
        });

        return view;
    }

    String selectedId;

    private void getOutputDatafromCursor(int position) {
        if (result.moveToPosition(position)) {
            Log.d(TAG, "Getting data from cursor at position "   position);
            for (int i = 0, count = selectedList.size(); i < count; i  ) {
                Log.d(TAG, "Name: "   selectedList.get(i).Name);
                Log.d(TAG, "Value: "   result.getString(result.getColumnIndex(selectedList.get(i).Name)));
                selectedList.get(i).Value = result.getString(result.getColumnIndex(selectedList.get(i).Name));
            }
            selectedId = result.getString(result.getColumnIndex("_id"));
        }
    }

    FragDetailItem fragDetailItem;

    private void launchUserDialog() {
        if (AppContext.dialStatus == AppContext.UserDialogStatus.OPEN) return;
        else AppContext.dialStatus = AppContext.UserDialogStatus.OPEN;

        FragmentManager fm = getFragmentManager();
        fragDetailItem = FragDetailItem.newInstance("Selection");
        fragDetailItem.setCancelable(false);
        fragDetailItem.setList(selectedList, selectedId);
        fragDetailItem.show(fm, "Selection");
    }



    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.sticky_code:
                onCodeLabelClick(v);
                break;
            case R.id.sticky_datetime:
                onDateLabelClick(v);
                break;
            case R.id.sticky_position:
                onPositionLabelClick(v);
                break;
            case R.id.sticky_color:
                onColorLabelClick(v);
                break;
            case R.id.sticky_quantita:
                onQuantitaLabelClick(v);
                break;
            case R.id.bt_finish:
                dBManager.SaveOutput(getActivity());
                InventoryActivity MyActivity;
                MyActivity = (InventoryActivity) getActivity();
                MyActivity.setViewPager(2);
                break;
            case R.id.bt_back:
                InventoryActivity My_Activity;
                My_Activity = (InventoryActivity) getActivity();
                My_Activity.setViewPager(2);
               break;
        }
    }

    private int date_label_click = 0;

    public void onDateLabelClick(View view) {
        TextView txt1 = (TextView) getView().findViewById(R.id.sticky_datetime);
        TextView txt2 = (TextView) getView().findViewById(R.id.sticky_code);
        TextView txt3= (TextView) getView().findViewById(R.id.sticky_color);
        TextView txt4 = (TextView) getView().findViewById(R.id.sticky_quantita);
        TextView txt5 = (TextView) getView().findViewById(R.id.sticky_position);

        txt2.setText(R.string.code_string);
        txt3.setText(R.string.color_string);
        txt4.setText(R.string.numero_string);
        txt5.setText(R.string.position_string);

        Log.d(TAG, "Clicked on DateLabel");
        AppContext.viber.vibrate(vibrationTime);

        if (date_label_click == 0) {
            date_label_click  ;
            updateEntryList(sort_time_desc);
            String arrow = getString(R.string.datetime_string)   uniArrow_up;
            txt1.setText(arrow);
        } else {
            date_label_click--;
            updateEntryList(sort_time_asc);
            String arrow = getString(R.string.datetime_string)   uniArrow_down;
            txt1.setText(arrow);
        }
    }

    private int code_label_click = 0;

    public void onCodeLabelClick(View view) {
        TextView txt1 = (TextView) getView().findViewById(R.id.sticky_datetime);
        TextView txt2 = (TextView) getView().findViewById(R.id.sticky_code);
        TextView txt3= (TextView) getView().findViewById(R.id.sticky_color);
        TextView txt4 = (TextView) getView().findViewById(R.id.sticky_quantita);
        TextView txt5 = (TextView) getView().findViewById(R.id.sticky_position);

        txt1.setText(R.string.datetime_string);
        txt3.setText(R.string.color_string);
        txt4.setText(R.string.numero_string);
        txt5.setText(R.string.position_string);

        Log.d(TAG, "Clicked on CodeLabel");
        AppContext.viber.vibrate(vibrationTime);

        if (code_label_click == 0) {
            code_label_click  ;
            updateEntryList(sort_barcode_desc);
            String arrow = getString(R.string.code_string)   uniArrow_up;
            txt2.setText(arrow);
        } else {
            code_label_click--;
            updateEntryList(sort_barcode_asc);
            String arrow = getString(R.string.code_string)   uniArrow_down;
            txt2.setText(arrow);
        }
    }


    private int color_label_click = 0;

    public void onColorLabelClick(View view) {
        TextView txt1 = (TextView) getView().findViewById(R.id.sticky_datetime);
        TextView txt2 = (TextView) getView().findViewById(R.id.sticky_code);
        TextView txt3= (TextView) getView().findViewById(R.id.sticky_color);
        TextView txt4 = (TextView) getView().findViewById(R.id.sticky_quantita);
        TextView txt5 = (TextView) getView().findViewById(R.id.sticky_position);

        txt1.setText(R.string.datetime_string);
        txt2.setText(R.string.code_string);
        txt4.setText(R.string.numero_string);
        txt5.setText(R.string.position_string);

        Log.d(TAG, "Clicked on ColorLabel");
        AppContext.viber.vibrate(vibrationTime);

        if (color_label_click == 0) {
            color_label_click  ;
            updateEntryList(sort_color_desc);
            String arrow = getString(R.string.color_string)   uniArrow_up;
            txt3.setText(arrow);
        } else {
            color_label_click--;
            updateEntryList(sort_color_asc);
            String arrow = getString(R.string.color_string)   uniArrow_down;
            txt3.setText(arrow);
        }
    }

    private int quantita_label_click = 0;

    public void onQuantitaLabelClick(View view) {
        TextView txt1 = (TextView) getView().findViewById(R.id.sticky_datetime);
        TextView txt2 = (TextView) getView().findViewById(R.id.sticky_code);
        TextView txt3= (TextView) getView().findViewById(R.id.sticky_color);
        TextView txt4 = (TextView) getView().findViewById(R.id.sticky_quantita);
        TextView txt5 = (TextView) getView().findViewById(R.id.sticky_position);

        txt1.setText(R.string.datetime_string);
        txt2.setText(R.string.code_string);
        txt3.setText(R.string.color_string);
        txt5.setText(R.string.position_string);

        Log.d(TAG, "Clicked on QuantitaLabel");
        AppContext.viber.vibrate(vibrationTime);

        if (quantita_label_click == 0) {
            quantita_label_click  ;
            updateEntryList(sort_quantita_desc);
            String arrow = getString(R.string.numero_string)   uniArrow_up;
            txt4.setText(arrow);
        } else {
            quantita_label_click--;
            updateEntryList(sort_quantita_asc);
            String arrow = getString(R.string.numero_string)   uniArrow_down;
            txt4.setText(arrow);
        }
    }

    private int position_label_click = 0;

    public void onPositionLabelClick(View view) {
        TextView txt1 = (TextView) getView().findViewById(R.id.sticky_datetime);
        TextView txt2 = (TextView) getView().findViewById(R.id.sticky_code);
        TextView txt3= (TextView) getView().findViewById(R.id.sticky_color);
        TextView txt4 = (TextView) getView().findViewById(R.id.sticky_quantita);
        TextView txt5 = (TextView) getView().findViewById(R.id.sticky_position);

        txt1.setText(R.string.datetime_string);
        txt2.setText(R.string.code_string);
        txt3.setText(R.string.color_string);
        txt4.setText(R.string.numero_string);

        Log.d(TAG, "Clicked on PositionLabel");
        AppContext.viber.vibrate(vibrationTime);

        if (position_label_click == 0) {
            position_label_click  ;
            updateEntryList(sort_position_desc);
            String arrow = getString(R.string.position_string)   uniArrow_up;
            txt5.setText(arrow);
        } else {
            position_label_click--;
            updateEntryList(sort_position_asc);
            String arrow = getString(R.string.position_string)   uniArrow_down;
            txt5.setText(arrow);
        }
    }

    public void onTriggerEvent(String operation) {
        Log.d(TAG, "FragmentVisualization: "   operation);
        Log.d(TAG, "FragmentVisualization: Tipologia: "   AppContext.currentAcq.AcquisitionName);

        if (operation.equals(getString(R.string.voice_command_VISUALIZZA))) {
            updateEntryList(sort_lastchoice);
            InventoryActivity.state = InventoryActivity.AcquisitionState.MOSTRADATI;
            notifyListener.onNotifyToActivity(InventoryActivity.state.toString());
        }

/*
        switch (InventoryActivity.state) {
            case MOSTRADATI:
                if (operation.equals(getString(R.string.voice_command_INDIETRO))) {
                    InventoryActivity.state = InventoryActivity.AcquisitionState.OPERAZIONE;
                    notifyListener.onNotifyToActivity(InventoryActivity.state.toString());
                } else if (operation.equals(getString(R.string.voice_command_TERMINA))) {
                    //pulire le tabelle di output?
                    //esportare qua le tabelle
                    dBManager.SaveOutput(getActivity());
                    InventoryActivity.state = InventoryActivity.AcquisitionState.OPERAZIONE;
                    notifyListener.onNotifyToActivity(InventoryActivity.state.toString());
                }
        }
*/
    }

    public void updateEntryList(String sortOrder) {
        if (sortOrder != null) sort_lastchoice = sortOrder;
        Log.d(TAG, "Updating Entry List");
        Log.d(TAG, "listView value"   listView.toString().trim());

        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Log.d(TAG, "listView value"   listView.toString().trim());
                Cursor mCursor = null;
                mCursor = dBManager.ReadAllOutputValues(sortOrder);
                outputAdapter = new ListOutputCursorAdapter(AppContext.getContext(), R.layout.db_entry_list, mCursor, 0);
                outputAdapter.notifyDataSetChanged();
                listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
                listView.setAdapter(outputAdapter);
                outputAdapter.swapCursor(mCursor);
            }
        });
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

        Activity activity = (Activity) context;

        try {
            notifyListener = (NotifyListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()   " must override onNotifyToActivity... ");
        }
    }   

}

}
  

Комментарии:

1. Извините, я не могу помочь ответить на вопрос… Но есть ли какой-нибудь способ показать меньше кода и при этом задать свой вопрос? Похоже, это много для вопроса.

2. Я постараюсь упростить код, чтобы лучше объяснить себя…