首页 > 解决方案 > 无法在 android 上使用改造显示 MySQL JSON 数据

问题描述

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

人活动:

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

详情_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;
    }
}

接口:

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"}]

活动主.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_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="100dp"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/nametxt"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="20dp"
        android:hint="Name"/>

    <TextView
        android:id="@+id/agetxt"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="20dp"
        android:hint="Age"/>

    <TextView
        android:id="@+id/phonetxt"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="20dp"
        android:hint="Phone"/>

    <TextView
        android:id="@+id/emailtxt"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="20dp"
        android:hint="Email"/>

    <Button
        android:id="@+id/retrieveBtn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="40dp"
        android:text="Retrieve Data"/>

</LinearLayout>

构建.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

标签: phpandroidmysqlretrofitretrofit2

解决方案


将注解的值改为JsonSerializedName中对应的值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

}

编辑:

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

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


推荐阅读