Android 从JSON响应更新获取字符串数据

Android 从JSON响应更新获取字符串数据,android,retrofit2,Android,Retrofit2,我使用的是JSON响应,我可以从我的服务器获得该响应,一开始我必须登录我的应用程序,因此我使用这样的api: @Headers("Content-type: application/json") @POST("/v1/login") Call<Post> auth(@Body Post body); 毕竟,在我的mainactivity类中初始化它: public void sendPost() { final EditText titleEt =

我使用的是JSON响应,我可以从我的服务器获得该响应,一开始我必须登录我的应用程序,因此我使用这样的api:

@Headers("Content-type: application/json")
    @POST("/v1/login")
    Call<Post> auth(@Body Post body);
毕竟,在我的mainactivity类中初始化它:

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();

            }
        });
    }
public void sendPost(){
final EditText titleEt=findViewById(R.id.login);
最终编辑文本bodyEt=findviewbyd(R.id.password);
最后一个字符串a=titleEt.getText().toString().trim();
最终字符串b=bodyEt.getText().toString().trim();
HttpLoggingInterceptor拦截器=新的HttpLoggingInterceptor();
拦截器.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient客户端=新建OkHttpClient.Builder().addInterceptor(拦截器).build();
改装改装=新改装.Builder()
.baseUrl(“https://server/")
.客户(客户)
.addConverterFactory(GsonConverterFactory.create())
.build();
APIService-mAPIService=reformation.create(APIService.class);
//改造.create(APIService.class);
mAPIService.auth(newpost(a,b)).enqueue(newcallback()){
@凌驾
public void onResponse(@NonNull调用,@NonNull响应){
if(response.issusccessful()){
Toast.makeText(LoginActivity.this,“Post submitted to API.”,Toast.LENGTH_LONG.show();
意向意向=新意向(LoginActivity.this,SecondScreen.class);
findViewById(R.id.btn_submit).getBackground().setColorFilter(Color.parseColor(“#1cd000”)、PorterDuff.Mode.MULTIPLY);
星触觉(意向);
saveData();
/*试一试{
字符串responseString=String.valueOf(response.body());
TextView txt=findviewbyd(R.id.post);
txt.setText(responseString);
}
捕获(例外e){
e、 printStackTrace();
}*/
}否则{
Toast.makeText(LoginActivity.this,“无法向API提交帖子。错误!!!”,Toast.LENGTH\u LONG.show();
findviewbyd(R.id.btn_submit).getBackground().setColorFilter(Color.parseColor(“#FF0000”)、PorterDuff.Mode.MULTIPLY);
}
}
@凌驾
public void onFailure(@NonNull Call Call,@NonNull Throwable t){
Toast.makeText(LoginActivity.this,“无法向API提交帖子”,Toast.LENGTH_LONG.show();
}
});
}

正如您所见,我在试图从JSON响应中获取一些数据时发表了评论,一般来说,我希望从响应中获取访问令牌,如果可能的话,我也不想创建一些用于获取的类,因为我已经在MainActivity类中初始化了我的改装。登录后,我也可以获得JSON格式的接收和发送消息,但我想将这些数据插入简单的listview。所以我希望在这个论坛上有人能帮助我解决我的问题。对不起,我的英语可能不好。

您必须了解,每个改装请求都是异步的,这意味着,它最终将在应用程序运行时执行。您应该使用RxJava来帮助您,因为您应该使用它来观察从API获取所需的数据

重要注意事项:由于未在主线程中运行,更新改装响应中的UI可能会触发异常

实现所需功能的一些有用链接:


我的眼睛在寻找堆叠的痕迹。而且,这个问题我也不太清楚。你是在问我尝试的堆栈跟踪吗?因为我无法从json responce中获取任何字符串数据),所以必须将response.body()作为字符串获取,并使用此字符串创建JSONObject或JSONObject,然后可以像往常一样从json获取字段。我不记得是body().toString()还是body().string()方法根据您的请求,您的响应将返回一个
Post
类型的json对象,要获取这些变量,您必须执行
response.body.getUsername()/getPassword()
…因此,根据您的所有评论,我无法从response-my-access\u-token)中获取这些变量。)
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();

            }
        });
    }