Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
134 views
in Technique[技术] by (71.8m points)

android - Getting Array of an Object using Retrofit POST request

I have an issue getting the Array inside an object. I am using Android Studio and Java with a NodeJS/Express backend. I am trying to get back the User Role so that I can redirect the User to the correct fragment.

Here is my Login Model

package com.example.vmsandroid;

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

public class Login {

    @SerializedName("user")
    @Expose
    private List<User> user = null;

    public List<User> getUser() {
        return user;
    }

    public void setUser(List<User> user) {
        this.user = user;
    }

}

Here is my User model

package com.example.vmsandroid;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class User {

    @SerializedName("role")
    @Expose
    private String role;
    @SerializedName("username")
    @Expose
    private String username;

    public String getRole() {
        return role;
    }

    public void setRole(String role) {
        this.role = role;
    }

    public String getUsername() {
        return username;
    }

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

}

Here is my Retrofit instance:


        retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .client(okHttpClient)
                .build();

        retrofitInterface = retrofit.create(RetrofitInterface.class);

Here is my API Call

    @POST("/app/login")
    Call<Login> executeLogin(@Body HashMap<String, String> map);

Here is my ExpressJS POST request

accountRoutes.post('/app/login', function(req,res){
    var matched_users_promise = models.user.findAll({
        where: Sequelize.and(
            {username: req.body.username},
        )
    });
    matched_users_promise.then(function(users){
        if(users.length > 0){
            let user = users[0];
            let passwordHash = user.password;
            const userArray = [];
            if(bcrypt.compareSync(req.body.password, passwordHash)){
                client.select("role","username").from("users").where( { username: req.body.username }).then(data =>{
                    res.status(200).send(JSON.stringify({user:data}));
                    console.log(data);
                })
                // console.log(rolequery.role);
                // res.status(200).send(JSON.stringify(objToSend))
            }
            else{
                res.status(404).send();
            }
        }
        else{
           res.status(404).send();
            
        }
    });
});

My onResponse and onFailure

 private void handleLoginDialog() {

        View view = getLayoutInflater().inflate(R.layout.login, null);

        AlertDialog.Builder builder = new AlertDialog.Builder(this);

        builder.setView(view).show();

        Button loginBtn = view.findViewById(R.id.login);
        EditText usernameedit = view.findViewById(R.id.username);
        EditText passwordedit = view.findViewById(R.id.password);

        loginBtn.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                HashMap<String, String> map = new HashMap<>();

                map.put("username", usernameedit.getText().toString());

                map.put("password", passwordedit.getText().toString());

                Call<Login> call = retrofitInterface.executeLogin(map);

                call.enqueue(new Callback<Login>() {
                    @Override
                    public void onResponse(Call<Login> call, Response<Login> response) {
                            if (response.code() == 200){
//                                startActivity(new Intent(getApplicationContext(),MainMenu.class));

//                                AlertDialog.Builder builder1 = new AlertDialog.Builder(MainActivity.this);
//                                builder1.setTitle(loginresult.getRole());
//                                builder1.setMessage(loginresult.getUsername());
//                                builder1.show();
                                Toast.makeText(MainActivity.this, "role"+ response.body().getUser(), Toast.LENGTH_SHORT).show();
                            }
                            if (response.code() ==404){
                                Toast.makeText(MainActivity.this, "Invalid Username or Password", Toast.LENGTH_SHORT).show();
                            }
                 }

                    @Override
                    public void onFailure(Call<Login> call, Throwable t) {
                        Toast.makeText(MainActivity.this, "error" + t.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }

After I log in, this is the JSON response I get from HTTPinterceptor. {"user":[{"role":"Tenant", "username":"edvin"}]}

And for some reason, this is what the Toast sends back. role:com.example.vmsandroid.User@edbe883 "edbe833" always being different and random.

Help would be much appreciated, have been working on this for 2 days straight, still cant find a solution. Do tell me if there is anything else that I need to provide

question from:https://stackoverflow.com/questions/65626820/getting-array-of-an-object-using-retrofit-post-request

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

LOL. Literally after 5 mins of posting this, I found the solution. To anyone who also has an issue like me, here is the solution.

Change response.body().getUser() to response.body().getUser().get(0).getRole().


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...