Pangu
Pangu

Reputation: 3819

How to populate a ListView from results of a JSON object?

I'm using a google search implementation to search for a result that the user enters when they click on a button.

I listen to that button click and fetch/parse the JSON result.

I have parsed the "title" and "url" of the JSON and would like to populate it in a ListView.

However, I don't think I'm using the ArrayAdapter class properly.

MyActivity.java:

private 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>

I seem to be getting this error:

Error:(71, 44) error: no suitable constructor found for ArrayAdapter(,int,String[]) constructor ArrayAdapter.ArrayAdapter(Context,int,int) is not applicable (argument mismatch; cannot be converted to Context) constructor ArrayAdapter.ArrayAdapter(Context,int,String[]) is not applicable (argument mismatch; cannot be converted to Context) constructor ArrayAdapter.ArrayAdapter(Context,int,List) is not applicable (argument mismatch; cannot be converted to Context)

Is there a way to use the ArrayAdapter to populate the ListView with data, or is there another way?

I apologize, I'm new to android.

Upvotes: 0

Views: 723

Answers (2)

Dominic D&#39;Souza
Dominic D&#39;Souza

Reputation: 981

The first argument of the ArrayAdapter should be your Context ...try using ActivityName.this where ActivityName is your Activity Name....

For ur keyboard i think the problem is with your 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>

Upvotes: 1

Rajesh Jadav
Rajesh Jadav

Reputation: 12861

You are doing wrong. you have called AsyncTsk and set adapter like:

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

JsonSearchTask run in seperate thread while listViewGoogle.setAdapter(adapter); calls in Main thread before getting result of JsonSearchTask. so you have to call this method in onPostExecute() method of JsonSearchTask.

Error:

Error:(71, 44) error: no suitable constructor found for ArrayAdapter(,int,String[]) constructor ArrayAdapter.ArrayAdapter(Context,int,int) is not applicable (argument mismatch; cannot be converted to Context) constructor ArrayAdapter.ArrayAdapter(Context,int,String[]) is not applicable (argument mismatch; cannot be converted to Context) constructor ArrayAdapter.ArrayAdapter(Context,int,List) is not applicable (argument mismatch; cannot be converted to Context)

You have called like this:

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

in your setOnClickListener. so at that time this referes OnClickListener's context reference not your Activity's Reference.

so Try

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

instead of

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

I hope it helps!

Upvotes: 1

Related Questions