【问题标题】:MVVM not updating server dataMVVM 不更新服务器数据
【发布时间】:2021-11-10 14:54:27
【问题描述】:

我是 MVVM 的初学者,并按照教程进行了尝试。它正在工作并从服务器获取数据,但问题是如果数据库中的数据发生更改,那么应用程序中的数据不会更改。

数据在MYSQL数据库中发生变化时,是否有可能在应用程序上自动更新,还是每次都需要调用api来获取最新数据?

我做错了什么?有什么帮助吗?

主要活动:

    public class MainActivity extends AppCompatActivity {

    ViewModel viewModel;
    TextView textView;

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

        textView = findViewById(R.id.textView);
        viewModel = new ViewModel(this);

        viewModel.getPostsDataFromViewModel().observe(this, new Observer<List<Post>>() {
            @Override
            public void onChanged(List<Post> posts) {
                for (int i = 0; i < posts.size() ; i++) {
                    Toast.makeText(MainActivity.this, posts.get(i).getId()+"\n"+posts.get(i).getTitle(), Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}

视图模型:

    public class ViewModel extends androidx.lifecycle.ViewModel {

    ApiRepo apiRepo;
    MutableLiveData<List<Post>> getPosts;

    public ViewModel(Context context)
    {
        apiRepo = new ApiRepo(context);
    }

    public LiveData<List<Post>> getPostsDataFromViewModel(){
        if(getPosts == null) {
            getPosts = apiRepo.getPostsDataFromRepo();
        }
        return getPosts;
    }
}

ApiRepo:

    public class ApiRepo {

    Context context;

    public ApiRepo(Context context)
    {
        this.context = context;
    }

    public MutableLiveData<List<Post>> getPostsDataFromRepo()
    {
        final MutableLiveData<List<Post>> postsModel = new MutableLiveData<>();

        JsonPlaceholderApi jsonPlaceholderApi = RetrofitBuilder.getInstance(context).create(JsonPlaceholderApi.class);
        jsonPlaceholderApi.getPosts().enqueue(new Callback<List<Post>>() {
            @Override
            public void onResponse(Call<List<Post>> call, Response<List<Post>> response) {
                postsModel.setValue(response.body());
            }

            @Override
            public void onFailure(Call<List<Post>> call, Throwable t) {
                Toast.makeText(context, t.getMessage(), Toast.LENGTH_LONG).show();
            }
        });

        return postsModel;
    }
}

RetrofitBuilder:

public class RetrofitBuilder {

    private static Retrofit retrofit = null;
    private static final String BASE_URL = Constants.BASE_URL;
    //private static final String API_VERSION = BuildConfig.VERSION;

    private static OkHttpClient.Builder httpClientBuilder = null;

    public static Retrofit getInstance(Context context) {
        if (retrofit == null) {

            httpClientBuilder = new OkHttpClient.Builder().readTimeout(5, TimeUnit.SECONDS);
            initHttpLogging();

            Retrofit.Builder builder = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .client(httpClientBuilder.build());


            retrofit = builder.build();

        }
        return retrofit;
    }


    private static void initHttpLogging() {
        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);
        if (BuildConfig.DEBUG) httpClientBuilder.addInterceptor(logging);
    }

    private static void initSSL(Context context) {

        SSLContext sslContext = null;
        try {
            sslContext = createCertificate(context.getResources().openRawResource(R.raw.star_webddocsystems_com));
        } catch (CertificateException | IOException | KeyStoreException | KeyManagementException | NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        if(sslContext!=null){
            httpClientBuilder.sslSocketFactory(sslContext.getSocketFactory(), systemDefaultTrustManager());
        }

    }

    private static SSLContext createCertificate(InputStream trustedCertificateIS) throws CertificateException, IOException, KeyStoreException, KeyManagementException, NoSuchAlgorithmException {

        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        Certificate ca;
        try {
            ca = cf.generateCertificate(trustedCertificateIS);
        } finally {
            trustedCertificateIS.close();
        }

        // creating a KeyStore containing our trusted CAs
        String keyStoreType = KeyStore.getDefaultType();
        KeyStore keyStore = KeyStore.getInstance(keyStoreType);
        keyStore.load(null, null);
        keyStore.setCertificateEntry("ca", ca);

        // creating a TrustManager that trusts the CAs in our KeyStore
        String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
        tmf.init(keyStore);

        // creating an SSLSocketFactory that uses our TrustManager
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, tmf.getTrustManagers(), null);
        return sslContext;

    }

    private static X509TrustManager systemDefaultTrustManager() {

        try {
            TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init((KeyStore) null);
            TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
            if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
                throw new IllegalStateException("Unexpected default trust managers:" + Arrays.toString(trustManagers));
            }
            return (X509TrustManager) trustManagers[0];
        } catch (GeneralSecurityException e) {
            throw new AssertionError(); // The system has no TLS. Just give up.
        }

    }

}

JsonPlaceholderApi:

 public interface JsonPlaceholderApi {

    @GET("posts")
    Call<List<Post>> getPosts();
}

常量:

    public class Constants {
    public static final String BASE_URL = "https://jsonplaceholder.typicode.com/";
}

Logcat:

    2021-09-15 19:06:00.501 4355-4355/? E/oc.mvvmtutoria: Unknown bits set in runtime_flags: 0x8000
2021-09-15 19:06:00.501 4355-4355/? E/oc.mvvmtutoria: Unknown bits set in runtime_flags: 0x8000
2021-09-15 19:06:00.501 4355-4355/? E/oc.mvvmtutoria: Unknown bits set in runtime_flags: 0x8000
2021-09-15 19:06:02.350 4355-4355/com.webdoc.mvvmtutorial E/GraphicExt: Can't load libboost_ext_fwk
2021-09-15 19:06:02.350 4355-4355/com.webdoc.mvvmtutorial E/GraphicExt: GraphicExtModuleLoader::CreateGraphicExtInstance false
2021-09-15 19:06:02.363 4355-4730/com.webdoc.mvvmtutorial E/GED: Failed to get GED Log Buf, err(0)
2021-09-15 19:06:02.390 4355-4730/com.webdoc.mvvmtutorial E/IMGSRV: :0: GetRenderableInternalFormatInfoEntry: Unsupported renderable internal format 37808
2021-09-15 19:06:02.390 4355-4730/com.webdoc.mvvmtutorial E/IMGSRV: :0: GetRenderableInternalFormatInfoEntry: Unsupported renderable internal format 37810
2021-09-15 19:06:02.390 4355-4730/com.webdoc.mvvmtutorial E/IMGSRV: :0: GetRenderableInternalFormatInfoEntry: Unsupported renderable internal format 37809
2021-09-15 19:06:02.390 4355-4730/com.webdoc.mvvmtutorial E/IMGSRV: :0: GetRenderableInternalFormatInfoEntry: Unsupported renderable internal format 37811
2021-09-15 19:06:02.390 4355-4730/com.webdoc.mvvmtutorial E/IMGSRV: :0: GetRenderableInternalFormatInfoEntry: Unsupported renderable internal format 37812
2021-09-15 19:06:02.390 4355-4730/com.webdoc.mvvmtutorial E/IMGSRV: :0: GetRenderableInternalFormatInfoEntry: Unsupported renderable internal format 37813
2021-09-15 19:06:02.390 4355-4730/com.webdoc.mvvmtutorial E/IMGSRV: :0: GetRenderableInternalFormatInfoEntry: Unsupported renderable internal format 37814
2021-09-15 19:06:02.390 4355-4730/com.webdoc.mvvmtutorial E/IMGSRV: :0: GetRenderableInternalFormatInfoEntry: Unsupported renderable internal format 37815
2021-09-15 19:06:02.390 4355-4730/com.webdoc.mvvmtutorial E/IMGSRV: :0: GetRenderableInternalFormatInfoEntry: Unsupported renderable internal format 37816
2021-09-15 19:06:02.390 4355-4730/com.webdoc.mvvmtutorial E/IMGSRV: :0: GetRenderableInternalFormatInfoEntry: Unsupported renderable internal format 37817
2021-09-15 19:06:02.390 4355-4730/com.webdoc.mvvmtutorial E/IMGSRV: :0: GetRenderableInternalFormatInfoEntry: Unsupported renderable internal format 37818
2021-09-15 19:06:02.390 4355-4730/com.webdoc.mvvmtutorial E/IMGSRV: :0: GetRenderableInternalFormatInfoEntry: Unsupported renderable internal format 37819
2021-09-15 19:06:02.390 4355-4730/com.webdoc.mvvmtutorial E/IMGSRV: :0: GetRenderableInternalFormatInfoEntry: Unsupported renderable internal format 37820
2021-09-15 19:06:02.390 4355-4730/com.webdoc.mvvmtutorial E/IMGSRV: :0: GetRenderableInternalFormatInfoEntry: Unsupported renderable internal format 37821
2021-09-15 19:06:02.394 4355-4355/com.webdoc.mvvmtutorial E/DecorView: mWindow.mActivityCurrentConfig is null
2021-09-15 19:06:02.424 4355-4730/com.webdoc.mvvmtutorial E/ion: ioctl c0044901 failed with code -1: Invalid argument
2021-09-15 19:06:02.578 4355-4355/com.webdoc.mvvmtutorial E/DecorView: mWindow.mActivityCurrentConfig is null
2021-09-15 19:06:04.121 4355-4355/com.webdoc.mvvmtutorial E/DecorView: mWindow.mActivityCurrentConfig is null
2021-09-15 19:06:04.171 4355-4355/com.webdoc.mvvmtutorial E/GraphicExt: GraphicExtModuleLoader::CreateGraphicExtInstance false

【问题讨论】:

  • 你可以做的是:返回ApiResult。不像 MutableLiveData 它可能是 SUCCESS 或 ERROR。简而言之,您的响应数据或一些 null 或错误。在 ViewModel 中。你可以这样做。 getPosts.postValue(api response) private MutableLiveData> getPosts; LiveData> observePost = getPosts // Kotlin 语法。您可以检查Java。并在 Activity 或 Fragment.. observePost LiveData

标签: java android mvvm retrofit


【解决方案1】:

你可以试试直接观察你的

apiRepo.getPostsDataFromRepo()

喜欢关注-

public LiveData<List<Post>> getPostsDataFromViewModel(){
  return getPosts = apiRepo.getPostsDataFromRepo();
}

无需在您的视图模型类中创建另一个对象。

【讨论】:

  • 感谢您的回答,但仍未更新
  • 请打印您的 logcat 跟踪,您的网络调用中一定有错误
  • 你能确认一下,你的'postsModel.setValue(response.body());'被调用?
  • 我已经在问题中发布了 logcat
  • logcat 没有显示与您的网络调用相关的任何内容,似乎不完整。在响应的网络调用上设置一个断点并进行验证。
猜你喜欢
  • 2017-03-24
  • 1970-01-01
  • 2020-10-27
  • 2012-04-16
  • 1970-01-01
  • 1970-01-01
  • 2021-07-11
  • 2016-10-10
  • 1970-01-01
相关资源
最近更新 更多