【问题标题】:How to populate a ListView from results of a JSON object?如何从 JSON 对象的结果中填充 ListView?
【发布时间】:2015-08-28 02:55:57
【问题描述】:

我正在使用 google 搜索实现来搜索用户在单击按钮时输入的结果。

我听那个按钮点击并获取/解析 JSON 结果。

我已经解析了 JSON 的“标题”和“url”,并希望将其填充到 ListView

但是,我认为我没有正确使用 ArrayAdapter 类。

MyActivity.java:

私有 ListView listViewGoogle;

private String[] resultArray;

private EditText searchBox;

private Button searchBtn;

private String search_url = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=";

private String search_query;

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

    listViewGoogle = (ListView)findViewById(R.id.listviewgoogle);

    searchBox = (EditText)findViewById(R.id.searchBox);
    searchBtn = (Button)findViewById(R.id.searchBtn);

    searchBtn.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            new JsonSearchTask().execute();

            try
            {
                search_query = search_url + searchBox.getText().toString();

                new JsonSearchTask().execute();

                ArrayAdapter adapter = new ArrayAdapter<String>(this, R.layout.activity_listviewgoogle, resultArray);
                listViewGoogle.setAdapter(adapter);

            }
            catch (Exception e)
            {
                // TODO: handle exception
            }
        }
    });
}

private class JsonSearchTask extends AsyncTask<Void, Void, Void>
{
    @Override
    protected Void doInBackground(Void... arg0)
    {
        try
        {
            parseResult(sendQuery(search_query));
        }
        catch (JSONException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return null;
    }
}

private String sendQuery(String query) throws IOException
{
    String queryResult = "";

    URL searchURL = new URL(query);

    HttpURLConnection httpURLConnection = (HttpURLConnection) searchURL.openConnection();

    if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK)
    {
        InputStreamReader inputStreamReader = new InputStreamReader(httpURLConnection.getInputStream());
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader, 8192);

        String line = null;

        while ((line = bufferedReader.readLine()) != null)
        {
            queryResult += line;
        }

        bufferedReader.close();
    }

    return queryResult;
}

private void parseResult(String json) throws JSONException
{
    String parsedResult = "";

    JSONObject jsonObject = new JSONObject(json);

    JSONObject jsonObject_responseData = jsonObject.getJSONObject("responseData");

    JSONArray jsonArray_results = jsonObject_responseData.getJSONArray("results");

    resultArray = new String[jsonArray_results.length()];

    for(int i = 0; i < jsonArray_results.length(); i++)
    {
        JSONObject jsonObject_i = jsonArray_results.getJSONObject(i);
        parsedResult = "title: " + jsonObject_i.getString("title") + "\n";
        parsedResult += "url: " + jsonObject_i.getString("url") + "\n";
        //parsedResult += "\n";
        resultArray[i] = parsedResult;
    }
}

activity_listviewgoogle.xml:

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/label"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dip"
    android:textSize="16dip"
    android:textStyle="bold"
    android:gravity="center" >
</TextView>

activity_my.xml:

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal"
    android:id="@+id/parentOuter" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >

        <EditText
            android:layout_width="fill_parent"
            android:layout_height="match_parent"
            android:hint="type to search..."
            android:layout_weight="2"
            android:id="@+id/searchBox" />

        <Button
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="Search Me!"
            android:layout_weight="2"
            android:id="@+id/searchBtn" />

        <ListView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/listviewgoogle"
            android:layout_weight="1" />

    </LinearLayout>

</LinearLayout>

我似乎遇到了这个错误:

错误:(71, 44) 错误: 没有找到合适的构造函数 ArrayAdapter(,int,String[]) 构造函数 ArrayAdapter.ArrayAdapter(Context,int,int) 不适用(参数 不匹配;不能转换为上下文) 构造函数 ArrayAdapter.ArrayAdapter(Context,int,String[]) 不是 适用(参数不匹配;不能 转换为 Context) 构造函数 ArrayAdapter.ArrayAdapter(Context,int,List) 不适用 (参数不匹配;无法转换为 上下文)

有没有办法使用 ArrayAdapter 用数据填充ListView,或者还有其他方法吗?

抱歉,我是安卓新手。

【问题讨论】:

    标签: java android listview android-arrayadapter


    【解决方案1】:

    你做错了。你已经调用了 AsyncTsk 并设置了如下适配器:

    new JsonSearchTask().execute();
    ArrayAdapter adapter = new ArrayAdapter<String>(this, R.layout.activity_listviewgoogle, resultArray);
    listViewGoogle.setAdapter(adapter);
    

    JsonSearchTask 在单独的线程中运行,而listViewGoogle.setAdapter(adapter); 在获得JsonSearchTask 的结果之前在主线程中调用。所以你必须在JsonSearchTaskonPostExecute()方法中调用这个方法。

    错误:

    错误:(71, 44) 错误: 没有找到合适的构造函数 ArrayAdapter(,int,String[]) 构造函数 ArrayAdapter.ArrayAdapter(Context,int,int) 不适用(参数 不匹配;不能转换为 Context) 构造函数 ArrayAdapter.ArrayAdapter(Context,int,String[]) 不适用 (参数不匹配;不能转换为上下文)构造函数 ArrayAdapter.ArrayAdapter(Context,int,List) 不适用 (参数不匹配;无法转换为上下文)

    你是这样调用的:

    ArrayAdapter adapter = new ArrayAdapter<String>(this, R.layout.activity_listviewgoogle, resultArray);
    

    在您的 setOnClickListener 中。所以当时 this 引用 OnClickListener 的上下文引用而不是您的 Activity 的引用。

    所以试试

    ArrayAdapter adapter = new ArrayAdapter<String>(MainActivity.this, R.layout.activity_listviewgoogle, resultArray);
    

    而不是

    ArrayAdapter adapter = new ArrayAdapter<String>(this, R.layout.activity_listviewgoogle, resultArray);
    

    希望对你有帮助!

    【讨论】:

    • 感谢它解决了我的另一个问题,我将您的答案标记为合适的!
    【解决方案2】:

    ArrayAdapter 的第一个参数应该是您的 Context ...尝试使用 ActivityName.this 其中 ActivityName 是您的活动名称...。

    对于你的键盘,我认为问题在于你的 xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/parentOuter"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
    
    
        <EditText
            android:id="@+id/searchBox"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="type to search..." />
    
        <Button
            android:id="@+id/searchBtn"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Search Me!" />
    
        <ListView
            android:id="@+id/listviewgoogle"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1" />
    
    </LinearLayout>
    

    【讨论】:

    • 这行得通(我认为)因为我不再收到错误,但键盘并没有消失。
    • 其实nm,我修好了,你知道我为什么要按两次按钮吗?如果我单击它一次,什么都不会出现,但如果我再次单击它,列表视图会填充并且键盘会消失
    • 我认为问题在于您的 xml
    猜你喜欢
    • 2023-03-21
    • 2011-01-24
    • 1970-01-01
    • 2018-09-20
    • 2011-09-10
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 2014-07-23
    相关资源
    最近更新 更多