为什么doInBackground在我的android REST调用中返回null?

时间:2017-07-17 18:19:08

标签: android rest android-asynctask

在AVD中,我测试了webservice http://10.0.2.2:8080/details,它运行良好。但是在我的Android应用程序中,getForObject方法在null中返回doInBackground。我不知道这里有什么问题。请帮帮我们。以下是我的代码:

的Manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.user.myapp">

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>

</manifest> 

的build.gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.3"
    defaultConfig {
        applicationId "com.example.user.myapp"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    //Added by me
    packagingOptions {
        exclude 'META-INF/ASL2.0'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/license.txt'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/notice.txt'
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.0-alpha7'
    compile 'com.android.support:design:25.3.1'
//****** Mes dependencies for Android RestTemplate and Spring interaction
compile 'org.springframework.android:spring-android-rest-template:1.0.1.RELEASE'
compile 'com.fasterxml.jackson.core:jackson-databind:2.3.2'
//*****END
testCompile 'junit:junit:4.12'
}

我的数据类

@JsonIgnoreProperties(ignoreUnknown = true)
public class Moyennes {
    private String id,name,age;

    /*Getters and setters*/

    //Constructor

    public Students(){

    }  

}

**我的活动班**

public class MainActivity extends AppCompatActivity {

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

    }

    @Override
    protected void onStart() {
        super.onStart();
        new HttpRequestTask().execute();
    }

    private class HttpRequestTask extends AsyncTask<Void, Void, Students> {

        @Override
        protected Students doInBackground(Void... params) {

            // To allow Debugging 
            if(android.os.Debug.isDebuggerConnected())
                android.os.Debug.waitForDebugger();

            try {
                final String url = "http://10.0.2.2:8080/details";
                RestTemplate restTemplate = new RestTemplate();
                restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
                Students students = restTemplate.getForObject(url, Students.class);
                return students ;
            } catch (Exception e) {
                // Log.e("MainActivity", e.getMessage(), e);
                Message.message(context,e.getMessage());
            }

            return null;
        }

    @Override
    protected void onPostExecute(Students student) {
        String id = student.getId();
        String name = student.getName();
        String age = student.getAge();
        // some other work
    }
}

1 个答案:

答案 0 :(得分:0)

在回答之前:Students课程是1名学生的课程;不是学生名单。

问题与应用程序无法理解Web服务的返回类型(尽管是JSON)这一事实有关。应用程序期待它可以转换为一个但从getForObject接收List的东西。

要解决此问题,以下是对doInBackground所做的更改:

@Override
protected Students[] doInBackground(Integer... params) {

    if(android.os.Debug.isDebuggerConnected()) // To allow Debugging => using breaking points below in doInBackground
        android.os.Debug.waitForDebugger();

        try {
            publishProgress(count);
            final String url = "http://10.0.2.2:8080/details";

            RestTemplate restTemplate = new RestTemplate();
            restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());

            ResponseEntity<Students[]> res = restTemplate.getForEntity(url, Students[].class);
            Students[] m = res.getBody();

            return m;

        } catch (Exception e) {
            Log.e("Error : ", e.getMessage(), e);
        }

    return null;
}