setOnItemSelectedListener 没有被调用?

setOnItemSelectedListener not being called?

我是 Android 的新手,正在开发我的第一个应用程序。我试图解析 Google Sheet 电子表格的内容,特别是将名称列表解析为 Spinner。我通过使用 ArrayAdapterArrayList 成功地做到了这一点,因为当我展开 Spinner 时可以看到选项。我面临的问题是 Spinner 在选择一个项目时不显示当前选择的项目。如果你尝试 运行 我的代码,你会看到如果你尝试点击提交 Button,它会告诉你 null 正在被选中,所以我已经缩小了将我的问题归结为当前未选择的名称字符串。

这是我的 MainActivity class:

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

ArrayList<String> names = new ArrayList<String>();

Spinner spBusinessType;
Button btnsubmit;

ArrayAdapter<String> adapterBusinessType;

String sbusinesstype;


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

    spBusinessType = (Spinner) findViewById(R.id.spBussinessType);

    btnsubmit=(Button)findViewById(R.id.submit);
    btnsubmit.setOnClickListener(this);

    new DownloadWebpageTask(new AsyncResult() {
        @Override
        public void onResult(JSONObject object) {
            processJson(object);
        }
    }).execute("https://spreadsheets.google.com/tq?key=1JKU2Vt_gMNUYYALct4m9xElLdpGlQ3N4uhS9qFRzxOQ");

    adapterBusinessType = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, names);
    adapterBusinessType.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spBusinessType.setAdapter(adapterBusinessType);

    spBusinessType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> adapter, View v,
                                   int position, long id) {
            // On selecting a spinner item
            sbusinesstype = adapter.getItemAtPosition(position).toString();
            System.out.println(sbusinesstype);

            // Showing selected spinner item
            Toast.makeText(getApplicationContext(),
                    "Bussiness Type : " + sbusinesstype, Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
            // TODO Auto-generated method stub

        }
    });

}

@Override
public void onClick(View v) {
    Toast.makeText(getApplicationContext(), "You have selected " + sbusinesstype,Toast.LENGTH_SHORT).show();
}

private void processJson(JSONObject object) {

    try {
        JSONArray rows = object.getJSONArray("rows");

        for (int r = 0; r < rows.length(); ++r) {
            JSONObject row = rows.getJSONObject(r);
            JSONArray columns = row.getJSONArray("c");

            String name = columns.getJSONObject(0).getString("v");
            names.add(name);
        }

    } catch (JSONException e) {
        e.printStackTrace();
    }
}

AsyncResult 接口 我正在使用从 Google Sheets:

获取一个 JSON 对象
public interface AsyncResult
{
    void onResult(JSONObject object);
}

正在获取和解析 JSON 对象的 DownloadWebpageTask class:

public class DownloadWebpageTask extends AsyncTask<String, Void, String> {
AsyncResult callback;

public DownloadWebpageTask(AsyncResult callback) {
    this.callback = callback;
}

@Override
protected String doInBackground(String... urls) {

    // params comes from the execute() call: params[0] is the url.
    try {
        return downloadUrl(urls[0]);
    } catch (IOException e) {
        return "Unable to download the requested page.";
    }
}

// onPostExecute displays the results of the AsyncTask.
@Override
protected void onPostExecute(String result) {
    // remove the unnecessary parts from the response and construct a JSON
    int start = result.indexOf("{", result.indexOf("{") + 1);
    int end = result.lastIndexOf("}");
    String jsonResponse = result.substring(start, end);
    try {
        JSONObject table = new JSONObject(jsonResponse);
        callback.onResult(table);
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

private String downloadUrl(String urlString) throws IOException {
    InputStream is = null;

    try {
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(10000 /* milliseconds */);
        conn.setConnectTimeout(15000 /* milliseconds */);
        conn.setRequestMethod("GET");
        conn.setDoInput(true);
        // Starts the query
        conn.connect();
        int responseCode = conn.getResponseCode();
        is = conn.getInputStream();

        String contentAsString = convertStreamToString(is);
        return contentAsString;
    } finally {
        if (is != null) {
            is.close();
        }
    }
}

private String convertStreamToString(InputStream is) {
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line = null;
    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sb.toString();
}

activity_main布局文件:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<include layout="@layout/content_main" />

</RelativeLayout>

和我将 Spinner 放入的 content_main 布局文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context=".MainActivity">
tools:showIn="@layout/activity_main">

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Select Business Type"
    android:textColor="#000000"
    android:textSize="20sp" />

<Spinner
    android:id="@+id/spBussinessType"
    style="@style/Base.Widget.AppCompat.Spinner.Underlined"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"></Spinner>

<Button
    android:id="@+id/submit"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_margin="10dp"
    android:text="Submit"
    android:textSize="15sp" />

</LinearLayout>

什么原因导致适配器无法检测到何时选择了其中一个名称字符串?这可能与我如何从 Google Sheet 解析它们有关吗?

您没有通知 ArrayAdapter 数据已更改,您最初传递了空 Arraylist 并在填充数组列表时,您必须通知 Adapter 数据已更改以及它考虑的时间,例如

private void processJson(JSONObject object) {
    try {
        JSONArray rows = object.getJSONArray("rows");

        for (int r = 0; r < rows.length(); ++r) {
            JSONObject row = rows.getJSONObject(r);
            JSONArray columns = row.getJSONArray("c");

            String name = columns.getJSONObject(0).getString("v");
            names.add(name);
        }
        adapterBusinessType.notifyDataSetChanged();
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

这应该有所帮助。

您的适配器中似乎没有显示任何数据。无法选择任何内容。您的侦听器代码看起来不错。

adapterBusinessType.notifyDatasetChanged()放入processJson方法。在 catch 之外或将所有数据添加到列表之后。

或者...将names.add替换为adapterBusinessType.add