简体   繁体   中英

Fetch string data from JSON response retrofit

I'm working with JSON response which I can get from my server, at the beginning I have to log in at my application so I use such api:

@Headers("Content-type: application/json")
    @POST("/v1/login")
    Call<Post> auth(@Body Post body);

and also my POJO-class:

public class Post {
    @SerializedName("username")
    private String username;
    @SerializedName("password")
    private String password;

    public Post(String username, String password) {
        this.username = username;
        this.password = password;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername (String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

and after all initialize it at my mainactivity class:

public void sendPost() {
        final EditText titleEt = findViewById(R.id.login);
        final EditText bodyEt = findViewById(R.id.password);
        final String a = titleEt.getText().toString().trim();
        final String b = bodyEt.getText().toString().trim();

        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://server/")
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        APIService mAPIService = retrofit.create(APIService.class);
        //retrofit.create(APIService.class);

        mAPIService.auth(new Post(a, b)).enqueue(new Callback<Post>() {
            @Override
            public void onResponse(@NonNull Call<Post> call, @NonNull Response<Post> response) {
                if (response.isSuccessful()) {
                    Toast.makeText(LoginActivity.this, "Post submitted to API.", Toast.LENGTH_LONG).show();
                    Intent intent = new Intent(LoginActivity.this, SecondScreen.class);
                    findViewById(R.id.btn_submit).getBackground().setColorFilter(Color.parseColor("#1cd000"), PorterDuff.Mode.MULTIPLY);
                    startActivity(intent);
                    saveData();
                   /* try {
                        String responseString = String.valueOf(response.body());
                        TextView txt = findViewById(R.id.post);
                        txt.setText(responseString);
                    }
                    catch (Exception e){
                        e.printStackTrace();
                    }*/


                } else {
                    Toast.makeText(LoginActivity.this, "Unable to submit post to API.Error!!!", Toast.LENGTH_LONG).show();
                    findViewById(R.id.btn_submit).getBackground().setColorFilter(Color.parseColor("#FF0000"), PorterDuff.Mode.MULTIPLY);
                }
            }

            @Override
            public void onFailure(@NonNull Call<Post> call, @NonNull Throwable t) {
                Toast.makeText(LoginActivity.this, "Unable to submit post to API.", Toast.LENGTH_LONG).show();

            }
        });
    }

as you can see I commented my trying to fetch some data from JSON response, in general, I would like to get my access token from the response and I also wouldn't like to create some classes for fetching if it is possible, because I have already initialized my retrofit at my MainActivity class. After logging in a can get my received and sent messages in JSON too, but I would like to insert this data into the simple listview. So I hope that somebody at this forum will help me with my problem. Sorry for my maybe bad English.

You have to understand that each Retrofit request is asynchronous , that means, it will eventually be executed while your application runs. You should use RxJava to help you with that, since you should use to observe the data you need to get from your API .

Important Note : Also updating UI in your response from retrofit might trigger exceptions due to not running in Main Thread.

Some useful links to implement what you need :

https://www.toptal.com/android/functional-reactive-android-rxjava

https://www.journaldev.com/20433/android-rxjava-retrofit

https://medium.com/3xplore/handling-api-calls-using-retrofit-2-and-rxjava-2-1871c891b6ae

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