【问题标题】:Add item in ArrayListAdapter from another activity Using SharedPreferences从另一个活动使用 SharedPreferences 在 ArrayListAdapter 中添加项目
【发布时间】:2019-11-02 19:29:46
【问题描述】:

我想将MainActivity 中的一些元素添加到另一个activity,在那里我有一个arrayList,但我的问题是,当我插入一些东西时,交易就完成了,但只添加了一个元素。我想向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);
        }
    });
}
}

【问题讨论】:

    标签: android android-listview sharedpreferences android-adapter


    【解决方案1】:

    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();
    

    当你添加另一个用户对象时,增加用户 ID

    ++userID;
    

    所以现在您的 shared preferences 将包含两个元素,其键为 &lt;username_0&gt;&lt;username_1&gt;

    另外,在从preferences 获取数据时,不要忘记使用正确的密钥。

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

    For 循环:假设你有 5 个元素并且你想将它们添加到你的 List

    onCreateMainActivity 中。

     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中获取数据。

    【讨论】:

    • 我做了,但现在它只保存了我输入的第一个值,我的列表不会增加
    • 您只向列表中添加一个元素,要一次添加多个值,请使用循环。
    • 好的,但我不知道在这种情况下如何实现该循环,请告诉我好吗?
    • 你知道如何获取登录列表的长度以循环使用它吗?我尝试使用 login.size() 但这不起作用
    • 如果没有用,你可以记录列表大小,如果在添加元素到列表之前使用login.size(),它将返回0。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-08
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    • 1970-01-01
    相关资源
    最近更新 更多