Dezo
Dezo

Reputation: 871

Can anyone help me fetch a data from a web service with the retrofit?

I am trying to fetch some data from a web service to my android app. I am doing that with a retrofit but I can't get a specific string(joke) value based on id. I fetch data from this URL: http://api.icndb.com/jokes/random/3.

When I enter an id as an integer in my app EditText I want with this id retrieve a joke with specific id from web service I mentioned above.

For example when I enter 179 as id in my app EditText and click "Start Retrofit" button I want to get this String value from web service "Chuck Norris? favourite cut of meat is the roundhouse." This string value I want to show as a toast message in my app.

I have already prepared my app code but I need some correction in interface @Query and @GET method and especially in Callback interface success method where I want to show a fetched data.

My app has next classes: MainActivity.class, activity_main.xml, Joke.class(I used a POJO to get this class from JSON), JokeInterface. I have already entered a internet permission in a manifest and "implementation 'com.squareup.retrofit:retrofit:1.9.0'" in my build.gradle as a dependency.

I put a comment in MainActivity.class and JokeInterface.class where I think that need to enter some code to accomplish my task.

Here is my code:

activity_main:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:background="@android:color/holo_blue_bright"
    android:padding="20dp"
    tools:context=".MainActivity">


    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="19dp"
        android:textSize="20sp"
        android:textColor="@android:color/black"
        android:text="Joke Id" />

    <EditText
        android:id="@+id/etEnterId"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="57dp"
        android:gravity="center"
        android:ems="10"
        android:hint="Enter id"
        android:inputType="number" />

    <Button
        android:id="@+id/btnStartRetrofit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="188dp"
        android:text="Start Retrofit" />
</RelativeLayout>

MainActivity.class:

package com.example.dezox.restwebservis;


import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.dezox.restwebservis.model.Joke;

import java.util.List;

import retrofit.RestAdapter;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

public class MainActivity extends AppCompatActivity {

    private EditText etEnterId;
    private Button btnStartRetrofit;
    private JokeInterface jokeInterface;
    private Callback<Joke> call;

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

        initWidgets();
        setupListener();
        setupRestAdapter();
    }

    private void initWidgets() {
        etEnterId = findViewById(R.id.etEnterId);
        btnStartRetrofit = findViewById(R.id.btnStartRetrofit);
    }

    private void setupListener() {

        btnStartRetrofit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (etEnterId.getText().length() > 0){
                    int id = Integer.parseInt(etEnterId.getText().toString());
                    getJokeMethod(id);
                }

            }
        });
    }

    private void getJokeMethod(int id) {
        jokeInterface.getJoke(id, call);
    }

    private void setupRestAdapter(){
        RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint(JokeInterface.ENDPOINT_URL).build();
        jokeInterface = restAdapter.create(JokeInterface.class);

        call = new Callback<Joke>() {
            @Override
            public void success(Joke joke, Response response) {
                StringBuilder builder = new StringBuilder();
                builder.append(joke.getType()+"\n");
 /*NOTE:               
 Here I need some code for a showing the string data in a toast message*/    


                Toast.makeText(getApplicationContext(), builder, Toast.LENGTH_LONG).show();
            }

            @Override
            public void failure(RetrofitError error) {

            }
        };

    }


}

Joke.class:(POJO)

package com.example.dezox.restwebservis.model;

import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Joke {

    @SerializedName("type")
    @Expose
    private String type;
    @SerializedName("value")
    @Expose
    private List<Value> value = null;

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public List<Value> getValue() {
        return value;
    }

    public void setValue(List<Value> value) {
        this.value = value;
    }

}


    class Value {

    @SerializedName("id")
    @Expose
    private Integer id;
    @SerializedName("joke")
    @Expose
    private String joke;
    @SerializedName("categories")
    @Expose
    private List<String> categories = null;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getJoke() {
        return joke;
    }

    public void setJoke(String joke) {
        this.joke = joke;
    }

    public List<String> getCategories() {
        return categories;
    }

    public void setCategories(List<String> categories) {
        this.categories = categories;
    }

}

JokeInterface.class:

package com.example.dezox.restwebservis;

import com.example.dezox.restwebservis.model.Joke;


import retrofit.Callback;
import retrofit.http.GET;
import retrofit.http.Query;

public interface JokeInterface {

    public static final String ENDPOINT_URL = "http://api.icndb.com/";

    @GET("/")


    void getJoke(@Query("") int id, Callback<Joke> callback);


/*NOTE:
Here I need some code in GET and Query in order to fetch a string
joke with specific id.*/

        }

Upvotes: 0

Views: 445

Answers (1)

Kara
Kara

Reputation: 46

Now I found out, the url you are calling returned list of jokes. "http://api.icndb.com/jokes/random/3" means - you are getting 3 object of random jokes. So if you call like "http://api.icndb.com/jokes/random/179", then you will get list of 179 random jokes. In this case 3 and 179 are not ids, they meant to be object count.

If you want only one joke at a time with specific id, you can call like "http://api.icndb.com/jokes/179", this will give you output like -

{ "type": "success", "value": { "id": 179, "joke": "Chuck Norris? favourite cut of meat is the roundhouse.", "categories": [] } }

and the "value" in "Joke" (POJO class) will not be list anymore,

@SerializedName("value")
@Expose
private Value value;

call as,

@GET("jokes/{id}")
void getJoke(@Path("id") int id, Callback<Joke> callback);

and you can show the returned joke value like,

 @Override
        public void success(Joke joke, Response response) { 
            Toast.makeText(getApplicationContext(), joke.getValue().getJoke(), Toast.LENGTH_LONG).show();
        }

Hopes this help!

Upvotes: 1

Related Questions