如何使用Retrofit2从API获取数据到spinner?

时间:2018-06-18 09:19:27

标签: java android retrofit2 android-spinner

我的项目包括spinner。它必须GET数据并将数据放入此spinner内。但它没有成功地做到这一点。它在调试中显示null。  我尝试了几个不同的代码,我已在我的代码中作为评论向您展示。

修改:我添加了JSON个回复,SendMessageGetDataModelLogcat

 SendMessagePage.java
public class SendMessagePage extends BaseActivity {
    Spinner spinnerCategory;
    private SendMessageGetModel sendMessageGetModel;
    private ArrayList<SendMessageGetDataModel> category = new ArrayList<>();



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

        getCategory();
spinnerCategory = (Spinner) findViewById(R.id.spinner);
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.spinner_text);
 adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinnerCategory.setAdapter(adapter);
 }
     protected void getCategory(){
        startProgress();
        String auth = SessionHelper.getCustomerTokenWithBearer();
        Call<SendMessageGetModel> call = ApiService.apiInterface.getCategory(auth);

        call.enqueue((new Callback<SendMessageGetModel>() {
            @Override
            public void onResponse(Call<SendMessageGetModel> call, Response<SendMessageGetModel> response) {
                stopProgress();

                if (response.isSuccessful()){

                  /*  if (response.body().getData() != null){
//                        safeBehaviourDetailDataModel = response.body().getData().get(0);
                       // sendMessageModel = response.body().getData.get(0);
                        title = response.body().getData();
                        spinnerCategory.getAdapter(title);
*/
                 //   }

                  /*  if (response.body() != null && response.body().getData().size() > 0){
                        category.addAll(response.body().getData());

                    }*/
                    if (response.body() !=null){

                        sendMessageGetModel = response.body();
                        Log.e("","sendMessageGetModel");

                        category = sendMessageGetModel.getData();
                        spinnerCategory.getAdapter();

                    }
                }
            }

            @Override
            public void onFailure(Call<SendMessageGetModel> call, Throwable t) {

            }
        }));
    }
}
SendMessageGetDataModel.java
public class SendMessageGetDataModel {
private String Title;
private String Id;

public String getTitle() {
    if (Title == null){
        Title = "";
    }
    return Title;
}

public void setTitle(String title) {
    Title = title;
}

public String getId() {
    if (Id == null){
        Id = "";
    }
    return Id;
}

public void setId(String id) {
    Id = id;
}
}

Json回复

{
    "Data": [
        {
            "Title": "Deneme",
            "Id": 1
        }
    ],
    "IsSuccess": true,
    "Error": null,
    "Header": null
}

错误

06-18 09:41:45.351 19642-19651/? I/art: Background sticky concurrent mark sweep GC freed 21567(2MB) AllocSpace objects, 2(136KB) LOS objects, 5% free, 19MB/20MB, paused 5.386ms total 38.828ms
06-18 09:43:25.344 19642-19651/? I/art: Background sticky concurrent mark sweep GC freed 17908(1861KB) AllocSpace objects, 2(136KB) LOS objects, 5% free, 19MB/20MB, paused 5.780ms total 47.486ms
06-18 09:43:45.440 19642-19651/? I/art: Background partial concurrent mark sweep GC freed 33296(4MB) AllocSpace objects, 60(1296KB) LOS objects, 19% free, 16MB/20MB, paused 3.507ms total 128.808ms
06-18 09:45:19.816 13495-24930/? I/EventLogChimeraService: Aggregate from 1529313490974 (log), 1529313490974 (data)
06-18 09:45:20.174 13495-24934/? I/vgd: com.google.android.gms.security__nonwearable-SnetDropBoxIntentOperation -- metadata{ service_id: 0 }
06-18 09:46:11.570 13509-19182/? E/WakeLock: release without a matched acquire!
06-18 09:46:11.673 13509-13555/? I/oqs: 51-GetConfigurationSnapshotOperationCall -- metadata{ service_id: 0 }
06-18 09:46:11.685 13509-13555/? I/oqs: 51-CommitToConfigurationOperationCall -- metadata{ service_id: 0 }
06-18 09:46:12.005 13509-24956/? W/Conscrypt: Could not set socket write timeout: java.lang.reflect.InvocationTargetException
        at java.lang.reflect.Method.invoke(Native Method)
        at com.google.android.gms.org.conscrypt.Platform.setSocketWriteTimeout(:com.google.android.gms@12685026@12.6.85 (040700-197041431):13)
    Caused by: android.system.ErrnoException: setsockopt failed: EBADF (Bad file descriptor)
        at libcore.io.Posix.setsockoptTimeval(Native Method)
        at libcore.io.ForwardingOs.setsockoptTimeval(ForwardingOs.java:157)
06-18 09:46:12.163 13509-24956/? W/Conscrypt: Could not set socket write timeout: java.lang.reflect.InvocationTargetException
        at java.lang.reflect.Method.invoke(Native Method)
        at com.google.android.gms.org.conscrypt.Platform.setSocketWriteTimeout(:com.google.android.gms@12685026@12.6.85 (040700-197041431):13)
    Caused by: android.system.ErrnoException: setsockopt failed: EBADF (Bad file descriptor)
06-18 09:46:12.164 13509-24956/? W/Conscrypt:     at libcore.io.Posix.setsockoptTimeval(Native Method)
        at libcore.io.ForwardingOs.setsockoptTimeval(ForwardingOs.java:157)
06-18 09:46:14.583 24961-24961/? W/art: Unexpected CPU variant for X86 using defaults: x86
06-18 09:46:14.591 19642-5074/? I/ActivityManager: Start proc 24961:com.google.android.talk/u0a56 for service com.google.android.talk/com.google.android.apps.hangouts.concurrent.impl.GcmTriggeredNotifier
06-18 09:46:14.853 24961-24961/? I/Babel_telephony: TeleModule.onApplicationCreate
06-18 09:46:14.857 24961-24983/? I/Babel_SMS: MmsConfig: mnc/mcc: 310/260
06-18 09:46:14.859 24961-24983/? I/Babel_SMS: MmsConfig.loadMmsSettings
06-18 09:46:14.864 24961-24983/? I/Babel_SMS: MmsConfig.loadDeviceMmsSettings from API: userAgent=GoldfishNexus, uaProfUrl=http://gsm.lge.com/html/gsm/Nexus5-M3.xml
    MmsConfig.loadFromDatabase
06-18 09:46:14.864 24961-24961/? I/Babel_App: Startup - clean
06-18 09:46:14.890 24961-24983/? E/SQLiteLog: (1) no such table: mmsconfig
06-18 09:46:14.891 24961-24983/? I/Babel_SMS: MmsConfig: no mmsconfig table android.database.sqlite.SQLiteException: no such table: mmsconfig (code 1): , while compiling: SELECT key, value, type FROM mmsconfig WHERE numeric=?
    MmsConfig.loadFromResources
06-18 09:46:14.894 24961-24983/? E/Babel_SMS: canonicalizeMccMnc: invalid mccmnc nullnull
06-18 09:46:14.894 24961-24983/? W/Babel_SMS: MmsConfig: invalid key=userAgent or type=string
    MmsConfig: invalid key=uaProfUrl or type=string
06-18 09:46:14.894 24961-24983/? I/Babel_SMS: MmsConfig.loadMmsSettings: userAgent=GoldfishNexus, uaProfUrl=http://gsm.lge.com/html/gsm/Nexus5-M3.xml
06-18 09:46:14.933 24961-24961/? D/Babel_SmsDep: disabled
06-18 09:46:14.937 24961-24961/? D/Babel_SmsDepStand: count:3
06-18 09:46:14.942 24961-24961/? D/Babel_SmsDep: disabled
06-18 09:46:14.990 24961-24961/? I/Babel_ConcService: Binding ConcurrentService
06-18 09:46:15.071 24961-24992/? I/Babel_ConcService: Scheduling delay with GcmNetworkManager of 101506 s for task geyaccount_reg_renewal_263362168_4 and tag network_connectivity_wakeup:persisted
06-18 09:46:15.086 24961-24992/? I/Babel_ConcService: Scheduling delay with GcmNetworkManager of 82799 s for task ghqDB_CLEANUP_401102596_4 and tag :persisted
06-18 09:46:15.092 24961-24994/? I/Babel_ConcService: Acquired partial wake lock to keep ConcurrentService alive
06-18 09:46:15.096 24961-24994/? I/Babel_ConcService: Released partial wake lock as ConcurrentService became idle
06-18 09:46:15.101 24961-24997/? I/Babel_ConcService: Acquired partial wake lock to keep ConcurrentService alive
06-18 09:46:15.103 13509-13520/? E/NetworkScheduler.ATC: Received callback from client for task that is already complete. ComponentInfo{com.google.android.talk/com.google.android.apps.hangouts.concurrent.impl.GcmTriggeredNotifier} :persisted
06-18 09:46:15.132 24961-25000/? D/Babel_SmsDepStand: count:3
06-18 09:46:15.132 24961-25000/? D/Babel_SmsDepNotif: not sms
06-18 09:46:15.132 24961-25000/? D/Babel_SmsDepUtil: imp:-1:3686
06-18 09:46:15.137 24961-25000/? I/Babel: Invalid account: 0 isEmptyName: true nameEqualsGaiaId: false
    Invalid account: 1 isEmptyName: true nameEqualsGaiaId: false
06-18 09:46:15.153 24961-25003/? I/Babel: Deleting: false for 0
06-18 09:46:15.154 24961-25003/? I/Babel: Deleting: false for 1
06-18 09:46:15.165 24961-25002/? D/Babel_SmsDep: disabled
06-18 09:46:15.184 24961-25000/? D/Babel_Notif_Persistent: PersistentMessageNotifier.cancelOngoingNotification
06-18 09:46:15.185 24961-25000/? D/Babel_Notif_SMS: cancelOngoingNotification
06-18 09:46:15.195 24961-25000/? I/Babel_ConcService: Released partial wake lock as ConcurrentService became idle

1 个答案:

答案 0 :(得分:1)

尝试此解决方案: -

1)在声明微调ID

后首先调用getCategory()
spinnerCategory = (Spinner) findViewById(R.id.spinner);
getCategory();

2)使用此Response类而不是SendMessageGetDataModel

public class ResponseClass {

public boolean isResult() {
    return result;
}

public void setResult(boolean result) {
    this.result = result;
}


@SerializedName("IsSuccess")
private boolean result;

public String getError() {
    return Error;
}

public void setError(String error) {
    Error = error;
}

public String getHeader() {
    return Header;
}

public void setHeader(String header) {
    Header = header;
}

@SerializedName("Error")
private String Error;


@SerializedName("Header")
private String Header;


public ArrayList<SpinnerModalClass> getSpinnerModalClassArrayList() {
    return spinnerModalClassArrayList;
}

public void setSpinnerModalClassArrayList(ArrayList<SpinnerModalClass> couponsListingModalArrayList) {
    this.spinnerModalClassArrayList = couponsListingModalArrayList;
}

@SerializedName("Data")
private ArrayList<SpinnerModalClass> spinnerModalClassArrayList;

public class SpinnerModalClass {
    public String getTitle() {
        return Title;
    }

    public void setTitle(String title) {
        Title = title;
    }

    public String getId() {
        return Id;
    }

    public void setId(String id) {
        Id = id;
    }

    @SerializedName("Title")
    private String Title;

    @SerializedName("Id")
    private String Id;



}

} 3)仅声明此arraylist

private ArrayList<ResponseClass.SpinnerModalClass> spinnerArrayList = new ArrayList<>();

4)然后在onResponse

                   if (response.body() !=null){
                        spinnerArrayList =response.body().getSpinnerModalClassArrayList();  
                        // set adapter for spinner using this arraylist

                      } 

5)如果不正确,请在API接口类中检查此方法,如路径 的getCategory

6)使用自定义适配器进行微调器

并使用此

Call<ResponseClass> call = ApiService.apiInterface.getCategory(auth);

Change the usage everywhere