没有调用setOnItemSelectedListener?

时间:2016-10-28 03:57:39

标签: java android android-spinner

我是Android新手,正在开发我的第一款应用。我试图将Google表格电子表格的内容,特别是名称列表解析为Spinner。我使用ArrayAdapterArrayList成功完成了这项工作,因为我可以在展开Spinner时查看选项。我遇到的问题是Spinner在选择一个项目时不会显示当前所选项目。如果您尝试运行我的代码,您会看到,如果您尝试点击提交Button,它会告诉您null正在被选中,因此我就是这样做的。我将我的问题缩小到当前选择的名称字符串未被选中。

这是我的 MainActivity类:

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表格中获取JSON对象:

public interface AsyncResult
{
    void onResult(JSONObject object);
}

获取并解析JSON对象的 DownloadWebpageTask类

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表格中解析它们有关吗?

2 个答案:

答案 0 :(得分:0)

您没有通知ArrayAdapter数据已更改,您最初传递空Arraylist并填写数组列表时,您必须通知适配器数据已更改及其时间考虑,如

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

这应该有所帮助。

答案 1 :(得分:0)

您的适配器中似乎没有显示任何数据。什么都不能选择。你的听众代码看起来很好。

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

或者......用names.add

替换adapterBusinessType.add