无法在 android 上使用改造显示 MySQL JSON 数据

Posted

技术标签:

【中文标题】无法在 android 上使用改造显示 MySQL JSON 数据【英文标题】:Cannot display MySQL JSON data using retrofit on android 【发布时间】:2021-04-19 04:21:39 【问题描述】:

我正在尝试通过 this example 进行改造,通过 php 获取 mysql 数据。该应用程序运行良好(没有错误),但是当我尝试单击按钮时,未检索到数据。我尝试查找一些东西以确保一些东西,例如android.permission.INTERNETbuild.gradle 上的更新改造库。但它们似乎都不起作用。可以请在这里启发我...这是我到目前为止所拥有的:

ManActivity:

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Button;
import android.widget.Toast;
import android.view.View;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class MainActivity extends AppCompatActivity 

    TextView nametxt, agetxt, phonetxt, emailtxt;
    Button retrieveBtn;

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

        nametxt = (TextView) findViewById(R.id.nametxt);
        agetxt = (TextView) findViewById(R.id.agetxt);
        phonetxt = (TextView) findViewById(R.id.phonetxt);
        emailtxt = (TextView) findViewById(R.id.emailtxt);
        retrieveBtn = (Button) findViewById(R.id.retrieveBtn);

        retrieveBtn.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View v) 

                fetchData();
            
        );
    


    private void fetchData() 
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Api.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        Api api = retrofit.create(Api.class);
        Call<List<Details_Pojo>> call = api.getstatus();
        call.enqueue(new Callback<List<Details_Pojo>>() 
            @Override
            public void onResponse(Call<List<Details_Pojo>> call, Response<List<Details_Pojo>> response) 
                List<Details_Pojo> adslist = response.body();

                String name = adslist.get(0).getName();
                String age = adslist.get(0).getAge();
                String phone = adslist.get(0).getPhone();
                String email = adslist.get(0).getEmail();

                nametxt.setText(name);
                agetxt.setText(age);
                phonetxt.setText(phone);
                emailtxt.setText(email);

            

            @Override
            public void onFailure(Call<List<Details_Pojo>> call, Throwable t) 
                Toast.makeText(MainActivity.this, ""+t.getMessage().toString(), Toast.LENGTH_SHORT).show();
            
        );
    

Details_Pojo:

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

public class Details_Pojo 
    @SerializedName("Name")
    @Expose
    private String Name;
    @SerializedName("Age")
    @Expose
    private String Age;
    @SerializedName("Phone")
    @Expose
    private String Phone;
    @SerializedName("Email")
    @Expose
    private String Email;

    public String getName() 
        return Name;
    

    public void setName(String name) 
        Name = name;
    

    public String getAge() 
        return Age;
    

    public void setAge(String age) 
        Age = age;
    

    public String getPhone() 
        return Phone;
    

    public void setPhone(String phone) 
        Phone = phone;
    

    public String getEmail() 
        return Email;
    

    public void setEmail(String email) 
        Email = email;
    

API:

import retrofit2.Call;
import retrofit2.http.GET;
import java.util.List;

public interface Api 
    String BASE_URL = "http://127.0.0.1/~xxxx/";     //xxxx is the user name and the php works
    @GET("Apppi.php")
    Call<List<Details_Pojo>> getstatus();


JSON:

["name":"Peter","age":"10","phone":"2345343","email":"1232e@yahoo.com"]

activity_main.xml:

<LinearLayout 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_
    android:layout_
    android:orientation="vertical"
    android:padding="100dp"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/nametxt"
        android:layout_
        android:layout_
        android:textSize="20dp"
        android:hint="Name"/>

    <TextView
        android:id="@+id/agetxt"
        android:layout_
        android:layout_
        android:textSize="20dp"
        android:hint="Age"/>

    <TextView
        android:id="@+id/phonetxt"
        android:layout_
        android:layout_
        android:textSize="20dp"
        android:hint="Phone"/>

    <TextView
        android:id="@+id/emailtxt"
        android:layout_
        android:layout_
        android:textSize="20dp"
        android:hint="Email"/>

    <Button
        android:id="@+id/retrieveBtn"
        android:layout_
        android:layout_
        android:layout_marginTop="40dp"
        android:text="Retrieve Data"/>

</LinearLayout>

Build.gradle:

dependencies 

    implementation 'androidx.appcompat:appcompat:1.2.0'
    implementation 'com.google.android.material:material:1.2.1'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.2'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    implementation 'com.google.code.gson:gson:2.8.5'

这就是我在 Logcat 上看到的,在网上搜索后,retrofit2.9.0 似乎出现了警告......

2021-01-13 22:46:26.657 3193-3193/com.example.fetching3 I/ample.fetching: Not late-enabling -Xcheck:jni (already on)
2021-01-13 22:46:26.711 3193-3193/com.example.fetching3 I/ample.fetching: Unquickening 12 vdex files!
2021-01-13 22:46:26.715 3193-3193/com.example.fetching3 W/ample.fetching: Unexpected CPU variant for X86 using defaults: x86
2021-01-13 22:46:28.176 3193-3193/com.example.fetching3 D/NetworkSecurityConfig: No Network Security Config specified, using platform default
2021-01-13 22:46:28.177 3193-3193/com.example.fetching3 D/NetworkSecurityConfig: No Network Security Config specified, using platform default
2021-01-13 22:46:28.317 3193-3238/com.example.fetching3 D/libEGL: loaded /vendor/lib/egl/libEGL_emulation.so
2021-01-13 22:46:28.320 3193-3238/com.example.fetching3 D/libEGL: loaded /vendor/lib/egl/libGLESv1_CM_emulation.so
2021-01-13 22:46:28.327 3193-3238/com.example.fetching3 D/libEGL: loaded /vendor/lib/egl/libGLESv2_emulation.so
2021-01-13 22:46:28.488 3193-3193/com.example.fetching3 W/ample.fetching: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (greylist, reflection, allowed)
2021-01-13 22:46:28.488 3193-3193/com.example.fetching3 W/ample.fetching: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (greylist, reflection, allowed)
2021-01-13 22:46:28.786 3193-3234/com.example.fetching3 D/HostConnection: HostConnection::get() New Host Connection established 0xecf1ee00, tid 3234
2021-01-13 22:46:28.810 3193-3234/com.example.fetching3 D/HostConnection: HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_YUV_Cache ANDROID_EMU_async_unmap_buffer GL_OES_EGL_image_external_essl3 GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_host_side_tracing ANDROID_EMU_gles_max_version_3_0 
2021-01-13 22:46:28.823 3193-3234/com.example.fetching3 W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
2021-01-13 22:46:28.829 3193-3234/com.example.fetching3 D/EGL_emulation: eglCreateContext: 0xecf1ecb0: maj 3 min 0 rcv 3
2021-01-13 22:46:28.852 3193-3234/com.example.fetching3 D/EGL_emulation: eglMakeCurrent: 0xecf1ecb0: ver 3 0 (tinfo 0xed270a10) (first time)
2021-01-13 22:46:28.908 3193-3234/com.example.fetching3 I/Gralloc4: mapper 4.x is not supported
2021-01-13 22:46:28.909 3193-3234/com.example.fetching3 D/HostConnection: createUnique: call
2021-01-13 22:46:28.909 3193-3234/com.example.fetching3 D/HostConnection: HostConnection::get() New Host Connection established 0xecf1fc70, tid 3234
2021-01-13 22:46:28.963 3193-3234/com.example.fetching3 D/goldfish-address-space: allocate: Ask for block of size 0x100
2021-01-13 22:46:28.963 3193-3234/com.example.fetching3 D/goldfish-address-space: allocate: ioctl allocate returned offset 0x3fe663000 size 0x2000
2021-01-13 22:46:28.984 3193-3234/com.example.fetching3 D/HostConnection: HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_YUV_Cache ANDROID_EMU_async_unmap_buffer GL_OES_EGL_image_external_essl3 GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_host_side_tracing ANDROID_EMU_gles_max_version_3_0 
2021-01-13 22:46:29.286 3193-3193/com.example.fetching3 I/Choreographer: Skipped 34 frames!  The application may be doing too much work on its main thread.
2021-01-13 22:46:45.706 3193-3193/com.example.fetching3 W/ample.fetching: Accessing hidden method Ljava/lang/invoke/MethodHandles$Lookup;-><init>(Ljava/lang/Class;I)V (greylist, reflection, allowed)
2021-01-13 22:46:45.931 3193-3193/com.example.fetching3 W/ample.fetching: Accessing hidden method Ldalvik/system/CloseGuard;->get()Ldalvik/system/CloseGuard; (greylist,core-platform-api, reflection, allowed)
2021-01-13 22:46:45.932 3193-3193/com.example.fetching3 W/ample.fetching: Accessing hidden method Ldalvik/system/CloseGuard;->open(Ljava/lang/String;)V (greylist,core-platform-api, reflection, allowed)
2021-01-13 22:46:45.932 3193-3193/com.example.fetching3 W/ample.fetching: Accessing hidden method Ldalvik/system/CloseGuard;->warnIfOpen()V (greylist,core-platform-api, reflection, allowed)
2021-01-13 22:46:46.076 3193-3193/com.example.fetching3 D/CompatibilityChangeReporter: Compat change id reported: 147798919; UID 10158; state: ENABLED

【问题讨论】:

【参考方案1】:

SerializedName注解的值改为Json中对应的key

试试下面的,

public class Details_Pojo 
    @SerializedName("name")
    @Expose
    private String Name;
    @SerializedName("age")
    @Expose
    private String Age;
    @SerializedName("phone")
    @Expose
    private String Phone;
    @SerializedName("email")
    @Expose
    private String Email;

  //rest of the logic remains the same


编辑:

getstatus返回Array而不是List,并在任何地方使用适当的方法

public interface Api 
    String BASE_URL = "http://127.0.0.1/~xxxx/";     //xxxx is the user name and the php works
    @GET("Apppi.php")
    Call<Array<Details_Pojo>> getstatus();


【讨论】:

好收获!我已经更改了大写以匹配它,但目前它仍然没有显示来自 MySQL 的 JSON 数据....(应用程序正在运行,但单击按钮时没有显示数据..) 现在检查答案,看看是否能解决错误 感谢您的建议。我试图用import java.sql.Array; 实现Call&lt;Array&lt;Details_Pojo&gt;&gt; getstatus(); 但它带有错误Type 'java.sql.Array' does not have type parameters?我不能在这里使用数组...嗯 使用标准库,'java.utils.Array` 你也可以看看这个链接吗:***.com/questions/65912445/…【参考方案2】:

根据日志,这可能是由于 http 而不是 https。 我们有两种选择,要么使用network_configs 排除这些,要么在Manifest 中启用明文流量。

还要将 POJO 对象保留为 @rcs 提及的所有小写字符。

尝试在下面使用,让我知道会发生什么,也请在成功和失败案例中记录数据,看看发生了什么

android:usesCleartextTraffic="true"

【讨论】:

以上是关于无法在 android 上使用改造显示 MySQL JSON 数据的主要内容,如果未能解决你的问题,请参考以下文章

android-jetifier: "无法解析所有工件";新项目上的“改造工件失败”

Android - 使用改造时出现错误“无法构造实例(尽管至少存在一个创建)”

改造解析JSON响应空值Android

MySQL客户端显示binary字符代码改造

如何在 Kotlin android 的改造中使用 enque 方法

在 Android 中使用改造