Добавить элемент в ArrayListAdapter из другого действия, используя SharedPreferences - PullRequest
1 голос
/ 02 ноября 2019

Я хочу добавить некоторые элементы из MainActivity в другой activity, где у меня есть arrayList, но моя проблема в том, что, когда я вставляю что-то, сделка завершается, но добавляется только 1 элемент. Я хочу добавить несколько элементов к arrayList. В MainActivity у меня есть 2 EditText и 2 buttons (Сохранить и GoToNextActivity, где я ставлю намерение перейти от MainActivity к списку list.class) Что я могу сделать, чтобы добавить больше элементов всписок, когда я нажимаю кнопку сохранения?

public class items {

private String username;
private String password;

items(String user,String parola){
    username=user;
    password=parola;
}

public String getPassword() {
    return password;
}

public String getUsername() {
    return username;
}
}


public class itemsAdapter extends ArrayAdapter<items> {

private static final String LOG_TAG = itemsAdapter.class.getSimpleName();

public itemsAdapter(Activity context, ArrayList<items> item) {
    super(context, 0,item);
}

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

    View listItemView = convertView;
    if (listItemView == null) {
        listItemView = LayoutInflater.from(getContext()).inflate(R.layout.list_items, parent, false);
    }

    items curentItems=getItem(position);

    TextView user=(TextView)listItemView.findViewById(R.id.list_user);
    TextView password=(TextView)listItemView.findViewById(R.id.list_password);

    user.setText(curentItems.getUsername());
    password.setText(curentItems.getPassword());


    return listItemView;
}
}

открытый список классов расширяет AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_list);

    SharedPreferences sharedPreferences= getSharedPreferences("user", Context.MODE_PRIVATE);
    String name=sharedPreferences.getString("username","");
    String password=sharedPreferences.getString("password","");

    final ArrayList<items> login = new ArrayList<items>();
    login.add(new items(name,password));

    itemsAdapter itemsAdapter=new itemsAdapter(this,login);

    ListView listView = (ListView) findViewById(R.id.list_activity_container);
    listView.setAdapter(itemsAdapter);

}
}

открытый класс MainActivity расширяет AppCompatActivity {

EditText username;
EditText password;
TextView show;
Button save;
Button display;
Button go;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    username=(EditText)findViewById(R.id.username);
    password=(EditText)findViewById(R.id.password);
    show=(TextView)findViewById(R.id.show);
    save=(Button)findViewById(R.id.save);
    display=(Button)findViewById(R.id.displayInfo);
    go=(Button)findViewById(R.id.goToList);

    save.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            SharedPreferences sharedPreferences= getSharedPreferences("user", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor=sharedPreferences.edit();

            editor.putString("username",username.getText().toString());
            editor.putString("password",password.getText().toString());
            editor.apply();

          //  Toast.makeText(this,"Saved",Toast.LENGTH_LONG).show();
        }
    });

    display.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            SharedPreferences sharedPreferences= getSharedPreferences("user", Context.MODE_PRIVATE);
            String name=sharedPreferences.getString("username","");
            String password=sharedPreferences.getString("password","");
            show.setText(name+"  "+password);
        }
    });

    go.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent=new Intent(MainActivity.this,list.class);
            startActivity(intent);
        }
    });
}
}

1 Ответ

0 голосов
/ 03 ноября 2019

Shared Preferences сохранить пару ключ-значение . Чтобы сохранить несколько элементов в SharedPreferences, вам необходимо назначить уникальный ключ для каждого элемента. Давайте назовем наш ключ как «userID».

int userID = 0;

и сохраним информацию о пользователе в общих настройках, как это

 SharedPreferences sharedPreferences= getSharedPreferences("user", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor=sharedPreferences.edit();

        editor.putString("username_"+userID,username.getText().toString());
        editor.putString("password_"+userID,password.getText().toString());
        editor.apply();

Когда вы добавляете другой объект пользователя, увеличивайтеuserID

++userID;

Так что теперь ваш shared preferences будет содержать два элемента с ключами <username_0> и <username_1>.

Также при получении данных из preferences не забудьтеиспользуйте правильный ключ.

String name=sharedPreferences.getString("username_"+userID,"");

Для циклов: предположим, что у вас есть 5 элементов, и вы хотите добавить их к вашим List

в onCreate из MainActivity.

 final ArrayList<items> login = new ArrayList<items>(itemCount);
    for (int i = 0; i < 5; i++) {
        // command below will be executed 5 times, and i will range from 0 to 4(both inclusive)
        login.add(new items("name" + i, "password" + i));
    }
    // now our login list has 5 elements(namely name0,name1...name4)

При нажатии на кнопку прослушивания кнопки сохранения, сохраните все list в shared preferences

save.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            SharedPreferences sharedPreferences = getSharedPreferences("user", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPreferences.edit();

            for (int i = 0; i < 5; i++) {
                // save entire list using loop.
                editor.putString("username" + i, login.get(i).getUsername());
                editor.putString("password" + i, login.get(i).getPassword());
            }
            editor.apply();

            //  Toast.makeText(this,"Saved",Toast.LENGTH_LONG).show();
        }
    });

в List activityчитать данные из предпочтений.

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_list);

    final ArrayList<items> login = new ArrayList<items>();

    SharedPreferences sharedPreferences = getSharedPreferences("user", Context.MODE_PRIVATE);
    for (int i = 0; i < 5; i++) {
        String name = sharedPreferences.getString("username" + i, "");
        String password = sharedPreferences.getString("password" + i, "");

        login.add(new items(name, password));
    }

    itemsAdapter itemsAdapter = new itemsAdapter(this, login);

    ListView listView = (ListView) findViewById(R.id.list_activity_container);
    listView.setAdapter(itemsAdapter);

}

Однако в ListActivity вам не нужно читать данные из shared preferences, вы можете связать данные в Intent, используемом для запуска ListActivity и в ListActivity получите данные из Intent.

...