Android将项目添加到现有的Spinner崩溃应用

时间:2018-02-14 11:53:37

标签: java android firebase firebase-realtime-database spinner

我正在开发一个函数,它将firebase数据库中的字符串添加到现有的微调器中。目前我有2个微调器,第一个微调器取自strings.xml文件,另一个微调器取自firebase中的项目。问题是,当我选择其中任何一个时,它们会相互叠加,并且sharedPreferneces也会被覆盖。我的问题是如何实现添加firebase数组" array"将键放入具有strings.xml的微调器中?提前致谢

PS。另一个问题是onPause和onResume和onBackpressed清除te saredPrefs

更新

public class HomeActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener{


private ZXingScannerView scannerView;
private final int permission_code = 1;

String [] selectedProfile;
Spinner spinner;
ArrayAdapter<CharSequence> adapter;


Spinner spinnerUser;
Map<String,Object> map;

private String userID;
private FirebaseDatabase mFirebaseDatabase;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private DatabaseReference myRef;

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

    mAuth = FirebaseAuth.getInstance();
    mFirebaseDatabase = FirebaseDatabase.getInstance();
    myRef = mFirebaseDatabase.getReference();
    FirebaseUser user = mAuth.getCurrentUser();
    userID = user.getUid();

    if(mAuth.getCurrentUser() == null){
        finish();
        startActivity(new Intent(this, MainActivity.class));
    }

    startSpinner();

}

    public void startSpinner(){

    //built in Profiles
    spinner = (Spinner) findViewById(R.id.spinnerProfiles);
    adapter = ArrayAdapter.createFromResource(this, R.array.restrictions, android.R.layout.simple_spinner_item);

    myRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            // This method is called once with the initial value and again
            // whenever data at this location is updated.
            map = (Map<String, Object>) dataSnapshot.child("users").child(userID).getValue();
            ArrayList<String> array  = new ArrayList<>();
            int x = 16;
            for (Map.Entry<String,Object> entry : map.entrySet()) {
                // key contains Profile Name
                String key = entry.getKey();
                adapter.insert(key, x);
                x++;
            }
            adapter.setDropDownViewResource(android.R.layout.simple_list_item_1);
            spinner.setAdapter(adapter);
            spinner.setOnItemSelectedListener(HomeActivity.this);
        }
        @Override
        public void onCancelled(DatabaseError databaseError) {
            //Auto Generated Method
        }
    });
}

//restores spinner object
public void restoreSpinner(){
    SharedPreferences sharedPref = getSharedPreferences("Preferences",MODE_PRIVATE);
    int profileVal = sharedPref.getInt("userProfile",-1);
    if(profileVal != -1) {
        spinner.setSelection(profileVal);
    }
}

//selects an item from the spinner and passes it to InformationActivity
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

    //Saves spinner value
    int profileVal = spinner.getSelectedItemPosition();
    SharedPreferences sharedPref = getSharedPreferences("Preferences", 0);
    SharedPreferences.Editor prefEditor = sharedPref.edit();
    prefEditor.putInt("userProfile", profileVal);
    prefEditor.apply();

    switch (profileVal) {
        case 0:
            break;
        case 1:
            selectedProfile = getResources().getStringArray(R.array.Wheat);
            break;
        case 2:
            selectedProfile = getResources().getStringArray(R.array.Crustaceans);
            break;
        case 3:
            selectedProfile = getResources().getStringArray(R.array.Eggs);
            break;
        default:
            String text = spinner.getSelectedItem().toString();
            map.get(text);

            ArrayList<String> array  = new ArrayList<>();
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                //Key contains Profile name
                String key = entry.getKey();
                if (key.equals(text)) {
                    // value is the corresponding list
                    Object value = entry.getValue();
                    array.addAll((ArrayList) value);
                }
            }
            //set the selected profile
            selectedProfile = array.toArray(new String[0]);
    }

}


}

2 个答案:

答案 0 :(得分:1)

您可以创建本地布尔字段以确定在微调器中显示的数据类型。它允许您使用一个微调视图

public class HomeActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {

    String[] selectedProfile;
    Spinner spinner;
    ArrayAdapter<String> adapter;
    Map<String, Object> map = new HashMap<>();

    private String userID;
    private FirebaseDatabase mFirebaseDatabase;
    private FirebaseAuth mAuth;
    private FirebaseAuth.AuthStateListener mAuthListener;
    private DatabaseReference myRef;

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

        mAuth = FirebaseAuth.getInstance();
        mFirebaseDatabase = FirebaseDatabase.getInstance();
        myRef = mFirebaseDatabase.getReference();
        FirebaseUser user = mAuth.getCurrentUser();
        userID = user.getUid();

        startSpinner();
    }

    //creates spinner objects
    public void startSpinner() {
        map.clear();
        map.put(getString(R.string.Wheat), Arrays.asList(getResources().getStringArray(R.array.Wheat)));
        map.put(getString(R.string.Crustaceans), Arrays.asList(getResources().getStringArray(R.array.Crustaceans)));
        map.put(getString(R.string.Eggs), Arrays.asList(getResources().getStringArray(R.array.Eggs)));

        //built in Profiles
        spinner = findViewById(R.id.spinnerProfiles);
        adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, new ArrayList<>(map.keySet()));
        adapter.setDropDownViewResource(android.R.layout.simple_list_item_1);
        spinner.setAdapter(adapter);
        spinner.setOnItemSelectedListener(this);

        //User Profiles
        myRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                // This method is called once with the initial value and again
                // whenever data at this location is updated.
                Map<String, Object> usersMap = (Map<String, Object>) dataSnapshot.child("users").child(userID).getValue();
                ArrayList<String> array = new ArrayList<>();
                for (Map.Entry<String, Object> entry : usersMap.entrySet()) {
                    map.put(entry.getKey(), entry.getValue());
                    // key contains Profile Name
                    String key = entry.getKey();
                    array.add(key);
                }
                adapter.addAll(array);
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                //Auto Generated Method
            }
        });
    }

    //restores spinner object
    public void restoreSpinner() {
        SharedPreferences sharedPref = getSharedPreferences("Preferences", MODE_PRIVATE);
        String profileVal = sharedPref.getString("userProfile", null);
        if (profileVal != null) {
            for (int i = 0; i < adapter.getCount(); i++) {
                String item = adapter.getItem(i);
                if (profileVal.equals(item)) {
                    spinner.setSelection(i);
                    break;
                }
            }
        }
    }

    //selects an item from the spinner and passes it to InformationActivity
    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        String text = spinner.getSelectedItem().toString();

        ArrayList<String> array = new ArrayList<>();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            //Key contains Profile name
            String key = entry.getKey();
            if (key.equals(text)) {
                // value is the corresponding list
                Object value = entry.getValue();
                array.addAll((List) value);
            }
        }
        //set the selected profile
        selectedProfile = array.toArray(new String[0]);

        SharedPreferences sharedPref = getSharedPreferences("Preferences", 0);
        SharedPreferences.Editor prefEditor = sharedPref.edit();
        prefEditor.putString("userProfile", text);
        prefEditor.apply();
    }

    // other methods
}

答案 1 :(得分:0)

为了让一个微调器包含来自strings.xml和Firebase数据库的字符串,您需要使用单个适配器和包含组合值的单个ArrayList。为了实现这一点,您需要将数据库中的字符串和strings.xml中的字符串添加到onDataChange方法内的ArrayList中。关于微调器的所有代码也应该在onDataChange方法中移动。适配器也应该在里面设置,否则ArrayList将只包含strings.xml中的字符串。我建议您这样做,因为onDataChange具有异步行为,您不能简单地在该方法之外使用它。这行代码adapter.addAll(array);永远不会起作用,因为在创建适配器时,您还没有从数据库中获取数据。因此,最好的解决方案是将所有逻辑移到onDataChange方法中。查看有关异步方法的更多详细信息here