Java 如何从JSON对象的结果填充ListView?

Java 如何从JSON对象的结果填充ListView?,java,android,listview,android-arrayadapter,Java,Android,Listview,Android Arrayadapter,我使用谷歌搜索实现来搜索用户点击按钮时输入的结果 我听那个按钮,点击并获取/解析JSON结果 我已经解析了JSON的“标题”和“url”,并希望将其填充到列表视图中 但是,我认为我没有正确使用ArrayAdapter类 MyActivity.java: 私有ListView listViewGoogle private String[] resultArray; private EditText searchBox; private Button searchBtn; private St

我使用谷歌搜索实现来搜索用户点击按钮时输入的结果

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

我已经解析了JSON的“标题”和“url”,并希望将其填充到
列表视图中

但是,我认为我没有正确使用
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;
    }
}
private String[]resultArray;
私人编辑文本搜索框;
私人按钮搜索;
专用字符串搜索\u url=”http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=";
私有字符串搜索和查询;
@凌驾
创建时受保护的void(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
listViewGoogle=(ListView)findViewById(R.id.listViewGoogle);
searchBox=(EditText)findViewById(R.id.searchBox);
searchBtn=(按钮)findviewbyd(R.id.searchBtn);
searchBtn.setOnClickListener(新视图.OnClickListener()
{
@凌驾
公共void onClick(视图v)
{
新建JsonSearchTask().execute();
尝试
{
search\u query=search\u url+searchBox.getText().toString();
新建JsonSearchTask().execute();
ArrayAdapter=新的ArrayAdapter(this,R.layout.activity\u listviewgoogle,resultArray);
setAdapter(适配器);
}
捕获(例外e)
{
//TODO:处理异常
}
}
});
}
私有类JsonSearchTask扩展了AsyncTask
{
@凌驾
受保护的Void doInBackground(Void…arg0)
{
尝试
{
parseResult(sendQuery(search_query));
}
捕获(JSONException e)
{
//TODO自动生成的捕捉块
e、 printStackTrace();
}
捕获(IOE异常)
{
//TODO自动生成的捕捉块
e、 printStackTrace();
}
返回null;
}
}
私有字符串sendQuery(字符串查询)引发IOException
{
字符串queryResult=“”;
URL searchURL=新URL(查询);
HttpURLConnection HttpURLConnection=(HttpURLConnection)searchURL.openConnection();
if(httpURLConnection.getResponseCode()==httpURLConnection.HTTP\u确定)
{
InputStreamReader InputStreamReader=新的InputStreamReader(httpURLConnection.getInputStream());
BufferedReader BufferedReader=新的BufferedReader(inputStreamReader,8192);
字符串行=null;
而((line=bufferedReader.readLine())!=null)
{
queryResult+=行;
}
bufferedReader.close();
}
返回查询结果;
}
私有void parseResult(字符串json)抛出JSONException
{
字符串parsedResult=“”;
JSONObject JSONObject=新的JSONObject(json);
JSONObject JSONObject_responseData=JSONObject.getJSONObject(“responseData”);
JSONArray JSONArray_results=jsonObject_responseData.getJSONArray(“结果”);
resultArray=新字符串[jsonArray_results.length()];
for(int i=0;i
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>

活动_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(上下文,int,int)不适用(参数 不匹配;无法转换为上下文) 构造函数ArrayAdapter.ArrayAdapter(上下文、int、字符串[])不可用 适用(参数不匹配;不能为 转换为上下文)构造函数 ArrayAdapter.ArrayAdapter(上下文、int、列表)不适用 (参数不匹配;无法转换为 (上下文)

是否有一种方法可以使用ArrayAdapter用数据填充
列表视图
,还是有其他方法


很抱歉,我是android新手。

ArrayAdapter的第一个参数应该是您的上下文…尝试使用ActivityName。这里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>

你做错了。您已调用AsyncTsk并将适配器设置为:

new JsonSearchTask().execute();
ArrayAdapter adapter = new ArrayAdapter<String>(this, R.layout.activity_listviewgoogle, resultArray);
listViewGoogle.setAdapter(adapter);
在setOnClickListener中。因此,在那时,
引用的是OnClickListener的上下文引用,而不是您的活动引用

所以试试看

ArrayAdapter adapter = new ArrayAdapter<String>(MainActivity.this, R.layout.activity_listviewgoogle, resultArray);
ArrayAdapter=新的ArrayAdapter(MainActivity.this,R.layout.activity\u listviewgoogle,resultArray);
而不是

ArrayAdapter adapter = new ArrayAdapter<String>(this, R.layout.activity_listviewgoogle, resultArray);
ArrayAdapter=新的ArrayAdapter(this,R.layout.activity\u listviewgoogle,resultArray);

我希望有帮助

我想这是可行的,因为我再也没有收到错误了,但是键盘没有消失。实际上,我已经修复了它,你知道我为什么要点击按钮两次吗?如果我单击一次,什么也不会出现,但是如果我再次单击,列表视图将填充,键盘将消失。我认为问题在于您的xml,因为它修复了我的另一个问题,我将您的答案标记为适当的答案!
ArrayAdapter adapter = new ArrayAdapter<String>(this, R.layout.activity_listviewgoogle, resultArray);