Вставить список элементов из диалога нижнего листа - PullRequest
0 голосов
/ 24 апреля 2020

Я хотел бы вставить элемент с помощью диалога нижней таблицы, сделав код, который я сделал, и получаю эту ошибку: 'android .content.SharedPreferences android .content.Context.getSharedPreferences (java .lang .String, int) 'для ссылки на пустой объект.

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

Код ниже.

Основная деятельность

public class MainActivity extends AppCompatActivity {
public RecyclerView recyclerView;
public Adapter adapter;
public ArrayList<String> items = new ArrayList<>();
com.github.clans.fab.FloatingActionButton fab;
SharedPreferences sharedPreferences,sharedPreferences2,sharedPreferences3;
SharedPreferences.Editor editor;
public int n_cards;
Context context;
BottomSheetDialog bottomSheet;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    sharedPreferences2 = getSharedPreferences("Count",Context.MODE_PRIVATE);
    n_cards=sharedPreferences2.getInt("Num",0);

    for(int i=1;i<=n_cards;i++){
        sharedPreferences3 = getSharedPreferences("Card"+i,Context.MODE_PRIVATE);
        String rec = sharedPreferences3.getString("Values",null);
        items.add(rec);
    }

    Log.d("PASS","OncreateMain");

    recyclerView = findViewById(R.id.recyclerView);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    context = getApplicationContext();
    implementView();
    fab = (com.github.clans.fab.FloatingActionButton) findViewById(R.id.call0);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            bottomSheet = new BottomSheetDialog();
            bottomSheet.show(getSupportFragmentManager(), "exampleBottomSheet");
            Log.d("PASS","OnclickMain");
        }
    });
}

public void implementView(){
    adapter = new Adapter(MainActivity.this,items);
    recyclerView.setAdapter(adapter);
                            }

public void recieve(){
    sharedPreferences2 = getSharedPreferences("Count",Context.MODE_PRIVATE);
    n_cards=sharedPreferences2.getInt("Num",0);
    sharedPreferences = getSharedPreferences("Card"+n_cards,Context.MODE_PRIVATE);
    String rec = sharedPreferences.getString("Values",null);
    items.add(rec);
    implementView();
}}

BottomSheetDialog

public class BottomSheetDialog extends BottomSheetDialogFragment {
private BottomSheetListener mListener;

//Dialog components
TextView tw1,tw2,tw3,tw4;
SeekBar seekBar;
RadioGroup radioGroup;
RadioButton rb1,rb2,rb3,rb4,rb5,rb6;
NumberPicker numberPicker,numberPicker2;
Button button;
//Stop dialog

SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
public int prog;
int n_cards;
MainActivity main;

//dati
String serv,val;
int d,m,p;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.custom_dialog, container, false);
    main = new MainActivity();

    tw1 = v.findViewById(R.id.txt_dia);
    tw2 = v.findViewById(R.id.txt_dia2);
    tw3 = v.findViewById(R.id.txt_dia3);
    tw4 = v.findViewById(R.id.euro);

    radioGroup = v.findViewById(R.id.radioGroup);
    rb1 = v.findViewById(R.id.rb1);
    rb2 = v.findViewById(R.id.rb2);
    rb3 = v.findViewById(R.id.rb3);
    rb4 = v.findViewById(R.id.rb4);
    rb5 = v.findViewById(R.id.rb5);

    numberPicker = v.findViewById(R.id.day);
    numberPicker2 = v.findViewById(R.id.month);
    numberPicker.setMinValue(1);
    numberPicker.setMaxValue(31);
    numberPicker2.setMinValue(1);
    numberPicker2.setMaxValue(12);

    seekBar = v.findViewById(R.id.seekBar);

    button = v.findViewById(R.id.done);

    Log.d("PASS","OncreateviewDialog");

    seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

                                           @Override
                                           public void onProgressChanged(SeekBar seekBar,int progress, boolean fromUser) {
                                               tw4.setText(String.valueOf(progress)+"€");
                                               prog=progress;
                                           }


                                           @Override
                                           public void onStartTrackingTouch(SeekBar seekBar) {

                                           }

                                           @Override
                                           public void onStopTrackingTouch(SeekBar seekBar) {

                                           }
                                       });

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int radioButtonID = radioGroup.getCheckedRadioButtonId();
            View radioButton = radioGroup.findViewById(radioButtonID);
            int idx = radioGroup.indexOfChild(radioButton);
            RadioButton r = (RadioButton) radioGroup.getChildAt(idx);
            serv = r.getText().toString();
            int d = numberPicker.getValue();
            int m = numberPicker2.getValue();
            sharedPreferences = getActivity().getSharedPreferences("Count",Context.MODE_PRIVATE);
            n_cards = sharedPreferences.getInt("Num",0);
            n_cards++;
            editor = sharedPreferences.edit();
            editor.putInt("Num",n_cards);
            editor.commit();
            sharedPreferences = getActivity().getSharedPreferences("Card"+n_cards,Context.MODE_PRIVATE);
            editor = sharedPreferences.edit();
            val=serv+"/"+d+"/"+m+"/"+prog;
            editor = sharedPreferences.edit();
            val=serv+"/"+d+"/"+m+"/"+prog;
            editor.putString("Values",val);
            editor.commit();
            dismiss();
        }
    });
    return v;
}

public interface BottomSheetListener {
    void onButtonClicked(String text);
}

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

@Override
public void onDismiss(DialogInterface dialog) {
    super.onDismiss(dialog);
    Log.d("PASS","dismiss");
    //main.additem(val);
    //main.implementView();
    main.recieve();
}}

Я оставлю вам также список адаптеров, может быть, может помочь.

Адаптер

public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> {

private LayoutInflater layoutInflater;
private List<String> data;

Adapter(Context context, List<String> data){
    this.layoutInflater = LayoutInflater.from(context);
    this.data = data;
}

@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
    View view = layoutInflater.inflate(R.layout.custom_view,viewGroup,false);
    return new ViewHolder(view);
}

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

    // bind the textview with data received

    String title = data.get(i);
    String[] separated = title.split("/");
    String title1=separated[0];
    String p1=separated[1];
    String p2=separated[2];
    String p3=separated[3];
    String subtitle="Pagamento il: "+p1+"/"+p2+" Prezzo:"+p3+"€";
    viewHolder.textTitle.setText(title1);
    viewHolder.textDescription.setText(subtitle);
    if(title1.equals("Netflix")){
        viewHolder.imageView.setBackgroundResource(R.drawable.netflix);
        viewHolder.cs.setBackgroundResource(R.drawable.netflix_background);
    }
    else if(title1.equals("Disney+")){
        viewHolder.imageView.setBackgroundResource(R.drawable.disney);
        viewHolder.cs.setBackgroundResource(R.drawable.disney_background);
    }
    else if(title1.equals("Spotify")){
        viewHolder.imageView.setBackgroundResource(R.drawable.spotify);
        viewHolder.cs.setBackgroundResource(R.drawable.spotify_background);
    }
    else if(title1.equals("Prime")){
        viewHolder.imageView.setBackgroundResource(R.drawable.prime);
        viewHolder.cs.setBackgroundResource(R.drawable.prime_background);
    }
    else if(title1.equals("Sky")){
        viewHolder.imageView.setBackgroundResource(R.drawable.sky);
        viewHolder.cs.setBackgroundResource(R.drawable.sky_background);
    }
    else if(title1.equals("Infinity")){
        viewHolder.imageView.setBackgroundResource(R.drawable.infinity);
        viewHolder.cs.setBackgroundResource(R.drawable.infinity_background);
    }
    else if(title1.equals("Twitch")){
        viewHolder.imageView.setBackgroundResource(R.drawable.twitch);
        viewHolder.cs.setBackgroundResource(R.drawable.twitch_background);
    }

}

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

public class ViewHolder extends RecyclerView.ViewHolder{

    TextView textTitle,textDescription;
    ImageView imageView;
    ConstraintLayout cs;

    public ViewHolder(@NonNull View itemView) {
        super(itemView);
        textTitle = itemView.findViewById(R.id.textTitle);
        textDescription = itemView.findViewById(R.id.textDesc);
        imageView = itemView.findViewById(R.id.imageView);
        cs = itemView.findViewById(R.id.background);
    }
}}

Я действительно в отчаянии, я пробовал все:

  • Вызовите вставку элемента из класса диалога
  • Получите значения объекта диалога из основного действия

Я действительно потерян. Спасибо за помощь.

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