Когда я закрываю свое приложение, весь динамически сгенерированный контент исчезает, так как я могу сохранить сгенерированный контент? - PullRequest
0 голосов
/ 24 февраля 2019

Кто-нибудь знает, как я могу сохранить динамически сгенерированные Textviews?Итак, в следующий раз, когда я открою приложение, TextViews отобразит тот же контент, который я ранее в них вставил.

Я изучил onSaveInstanceState, onRestoreInstanceState, но ни один из них не работает.Есть ли библиотеки, которые я могу использовать для сохранения сгенерированных TextViews?Или, может быть, какой-нибудь совет о лучшем способе сделать это.Я исследовал этот материал в течение нескольких дней и нашел устаревшую информацию и информацию, которая не кажется мне актуальной.Решения для кода будут высоко оценены

MainActivity.java:

package com.example.savingdynamiccontent;

import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;

import java.util.ArrayList;

public class MainActivity extends Activity {
    private LinearLayout mLayout;
    private LinearLayout ListItems;
    static final String counter_value = "int_value";
    static final String toDoList_value = "toDolist";
    private EditText mEditText;
    private Button mButton;
    private int counter;

    private ArrayList<String> toDoList;
    private ArrayList<String> keys;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);    
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

        if (toDoList != null){
             System.out.println("Success!");
            for(int i = 0; i< toDoList.size(); i++){
                System.out.println(toDoList.get(i));
                ListItems.addView(createNewTextView(toDoList.get(i)));
            }
        }
        else{
            System.out.println("Nope!");
            toDoList = new ArrayList<String>();

        }

        counter = 1;
        mLayout = (LinearLayout) findViewById(R.id.linearLayout);
        ListItems = (LinearLayout) findViewById(R.id.listItems);
        mEditText = (EditText) findViewById(R.id.editText);
        mButton = (Button) findViewById(R.id.button);
        mButton.setOnClickListener(onClick());
        TextView textView = new TextView(this);
        textView.setText("New text");
    }

    private View.OnClickListener onClick() {
        return new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                ListItems.addView(createNewTextView(mEditText.getText().toString()));
        }
    };
}

private TextView createNewTextView(String text) {
    final RadioGroup.LayoutParams lparams = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.WRAP_CONTENT, RadioGroup.LayoutParams.WRAP_CONTENT);
    final TextView textView = new TextView(this);
    textView.setLayoutParams(lparams);
    textView.setFreezesText(true);
    textView.setText(counter + ":" + text);
    textView.setId(counter);
    System.out.println(textView.getId());

    toDoList.add(text);

    counter++;
    return textView;
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState){

    super.onRestoreInstanceState(savedInstanceState);

    counter = savedInstanceState.getInt(counter_value);
    toDoList = savedInstanceState.getStringArrayList("key");

    // Add this for-loop to restoring your list
    for(String str : toDoList){
        ListItems.addView(createNewTextView(str));
    }

    //REad values from the savedInstanceState" -object and put them in your textview
}

    @Override
    protected void onSaveInstanceState(Bundle outState){
    // Save the values you need from your textview into "outSTate" -object
    //        outState.putParcelableArrayList("key", toDoList);

    outState.putInt(counter_value, counter);
    outState.putStringArrayList("key", toDoList);
    super.onSaveInstanceState(outState);
}
}

Activit_Main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/linearLayout"
    android:weightSum="1">

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:id="@+id/listItems"></LinearLayout>

    <EditText
        android:id="@+id/editText"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        />
    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Add+"
        />
</LinearLayout>
...