如何将单个项目添加到现有微调器?

时间:2019-03-29 17:30:17

标签: java android spinner adapter

我有一个微调器,其中已经包含一些项目。我正在尝试通过setResult和onActivityResult从另一个活动获取它之后向其中添加新项目:

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null 
    {...}
    else if(requestCode == GET_NEW_STUDENT_NAME)
    {
        String name = data.getStringExtra("name");
        ArrayAdapter<String> adapter = (ArrayAdapter<String>)studentsSpinner.getAdapter();
        adapter.add(name);
        studentsSpinner.setAdapter(adapter);
    }
}

但是,每次代码运行时,活动都会关闭。正在显示此异常:

  

03-29 19:20:30.925 26953-26953 / com.example.user.privatelessons E / AndroidRuntime:致命异常:main       流程:com.example.user.privatelessons,PID:26953       java.lang.RuntimeException:无法将结果ResultInfo {who = null,request = 2,result = -1,data = Intent {(has extras}}}传递给活动{com.example.user.privatelessons / com.example.user .privatelessons.AddLessonActivity}:java.lang.NullPointerException:println需要一条消息           在android.app.ActivityThread.deliverResults(ActivityThread.java:4179)           在android.app.ActivityThread.handleSendResult(ActivityThread.java:4222)           在android.app.ActivityThread.-wrap20(ActivityThread.java)           在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1581)           在android.os.Handler.dispatchMessage(Handler.java:102)           在android.os.Looper.loop(Looper.java:163)           在android.app.ActivityThread.main(ActivityThread.java:6238)           在java.lang.reflect.Method.invoke(本机方法)           在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:904)           在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)        原因:java.lang.NullPointerException:println需要一条消息           在android.util.Log.println_native(本机方法)           在android.util.Log.e(Log.java:236)           在com.example.user.privatelessons.AddLessonActivity.onActivityResult(AddLessonActivity.java:123)           在android.app.Activity.dispatchActivityResult(Activity.java:7121)           在android.app.ActivityThread.deliverResults(ActivityThread.java:4175)           在android.app.ActivityThread.handleSendResult(ActivityThread.java:4222)           在android.app.ActivityThread.-wrap20(ActivityThread.java)           在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1581)           在android.os.Handler.dispatchMessage(Handler.java:102)           在android.os.Looper.loop(Looper.java:163)           在android.app.ActivityThread.main(ActivityThread.java:6238)

[EDIT]:首先,我使用以下代码初始化微调器:

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
        android.R.layout.simple_spinner_item, db.GetStudentslist());;
spinner.setAdapter(adapter);

GetStudentslist()返回String []。

以下代码仅在logcat中显示名称(不将其添加到微调器中),可以正常工作:

 if(requestCode == GET_NEW_STUDENT_NAME && data != null)
            {
                String name = data.getStringExtra("name");
/*                List<String> names = Arrays.asList(db.GetStudentslist());
                names.add(name);
                ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                        android.R.layout.simple_spinner_item, names);;
                studentsSpinner.setAdapter(adapter);*/
                Log.e("Name", name);
            }

3 个答案:

答案 0 :(得分:2)

您必须将方法db.GetStudentslist()的输出存储到类(活动)中的某个字段(列表)中。而当您想添加/删除/更改元素时,只需修改列表,然后在适配器中进行更新即可。

我创建了一个简单的示例:

活动

package training.com.myapplication;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    // List with three predefined elements
    private List<String> listOfElements = new ArrayList<>(Arrays.asList(
            "Hello world", "Hello world", "Hello world"
    ));

    // Adapter for the Spinner
    private ArrayAdapter<String> adapter;

    private Spinner spinner;

    private Button addButton;
    private Button removeButton;

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

        // Initialize adapter
        adapter = new ArrayAdapter<>(this,
                android.R.layout.simple_spinner_item, listOfElements);

        spinner = findViewById(R.id.action_bar_spinner);

        addButton = findViewById(R.id.add_button);
        removeButton = findViewById(R.id.remove_button);

        // Set adapter
        spinner.setAdapter(adapter);

        addButton.setOnClickListener(view -> {
            // Add new element to the list
            listOfElements.add("Hello world");
        });

        removeButton.setOnClickListener(view -> {
            // Remove last item from the list
            int lastIndex = listOfElements.size() - 1;
            listOfElements.remove(lastIndex);
        });
    }
}

使用简单的布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="40dp"
    android:orientation="vertical">

    <Spinner
        android:id="@+id/action_bar_spinner"
        android:layout_width="match_parent"
        android:layout_height="50dp" />

    <Button
        android:id="@+id/add_button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:text="+"
        android:textSize="30sp" />

    <Button
        android:id="@+id/remove_button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:text="-"
        android:textSize="30sp" />

</LinearLayout>

预期产量

Layout


如果您通过onActivityResult()接收数据,则可以采用以下相同的方式进行操作:

// Read data
String name = data.getStringExtra("name");

// Add to list
listOfElements.add(name);

记住要正确开始活动:

startActivityForResult(intent, GET_NEW_STUDENT_NAME);

,如果您想发回数据:

Intent returnIntent = new Intent();
returnIntent.putExtra("name",result);
setResult(Activity.RESULT_OK,returnIntent);
finish();

,并且在您的onActivityResult()方法中,您必须检查两个条件:

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    // Check result
    if (resultCode == Activity.RESULT_OK) {
        // And check what was requested
        if (requestCode == GET_NEW_STUDENT_NAME) {
            String name = data.getStringExtra("name");
            listOfElements.add(name);
        }
    }
}

答案 1 :(得分:0)

我终于开始工作了。原来,这个问题是Unable to modify ArrayAdapter in ListView: UnsupportedOperationException

的重复

答案 2 :(得分:0)

为此,在onCreate方法上方全局设置 List <>变量,ArrayAdapter。
在oncreate方法中添加默认项,并为该微调器配置Arrayadapter。


然后在onActivityResult中,在List.add(“ String”)中添加新值。

之后,添加此行。
adapter.notifydatasetchanges(); 它将把您的数据更新到微调控件中。



如果需要更多帮助,我将在此处给出示例。