简体   繁体   中英

Android Calling API and parsing JSON

Trying to make an API call to the url below and parse the returning JSON, when the "refresh" button is called.

I can link to a button and get text (Hello world) to the screen, but can't seem to link the button click to the API request. Error message says I cannot reference non-static method "execute" from a static context

public class MainActivity extends AppCompatActivity {



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

public void retrieveInformation(View view){
    RetrieveFeedTask.execute();
    TextView textview = (TextView) findViewById(R.id.responseView);
    textview.setText("Hello world");
}

class RetrieveFeedTask extends AsyncTask<Void, Void, String> {
    String jsonString = "";

    private Exception exception;

    protected void onPreExecute() {

    }

    protected String doInBackground(Void... urls) {

        // Do some validation here

        try {
            URL url = new URL("www.liftin.co.uk/api/v1/journeys");
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            try {
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                StringBuilder stringBuilder = new StringBuilder();
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    stringBuilder.append(line).append("\n");
                }
                bufferedReader.close();
                return stringBuilder.toString();
            } finally {
                urlConnection.disconnect();
            }
        } catch (Exception e) {
            Log.e("ERROR", e.getMessage(), e);
            return null;
        }
    }

    protected void onPostExecute(String response) {
        if (response == null) {
            response = "THERE WAS AN ERROR";
        }
        Log.i("INFO", response);
        jsonString = response;
        try {
            getInformationFromJson(jsonString);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private String getInformationFromJson(String jsonString)
        throws JSONException {
        final String DRIVER = "driver";
        final String START = "start";
        final String DESTINATION = "destination";
        final String TIME = "pick_up_time";
        final String PASSENGERS = "passengers";
        final String SEATS = "seats_available";

        JSONObject journeyJson = new JSONObject(jsonString);
        String time = journeyJson.getString(TIME);
        String seats = journeyJson.getString(SEATS);

        String results = seats + "-----" + time;
        return results;
    }


}

}

Main_activity.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
    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="com.example.android.liftin.MainActivity">
    <Button
        android:id="@+id/queryButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="end"
        style="@style/Base.Widget.AppCompat.Button.Borderless"
        android:text="Refresh"
        android:onClick="retrieveInformation"/>
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center">
        <ScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent">
            <TextView
                android:id="@+id/responseView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />
        </ScrollView>
    </RelativeLayout>
</LinearLayout>

You should create asynchronous call for your AsyncTask like this :

public void retrieveInformation(View view){
    new RetrieveFeedTask().execute();    //asynchronous call
    TextView textview = (TextView) findViewById(R.id.responseView);
    textview.setText("Hello world");
} 

UPDATE

If you want to set data to textview after parsing data. You have to make little bit changes in your activity as follows.

  1. You should initialize your textview in onCreate() and make it global variable for your activity, so that you can access it in full activity.

  2. then in your onPostExecute() do this :

    textview.setText(getInformationFromJson(response));

Hope it will Help :)

You must create a object of AsyncTask (RetrieveFeedTask) before calling it. For example

   public void retrieveInformation(View view){
        TextView textview = (TextView) findViewById(R.id.responseView);
        textview.setText("Hello world");
        new RetrieveFeedTask().execute();
    }

You still need to pass something for Void .

public void retrieveInformation(View view){
    new RetrieveFeedTask().execute(null);
    TextView textview = (TextView) findViewById(R.id.responseView);
    textview.setText("Hello world");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM