简体   繁体   English

ViewModelProvider.of 和 ViewModelProvider 在 Android Java 中均已弃用

[英]ViewModelProvider.of and ViewModelProvider both are deprecated in Android Java

I am not able to use both ViewModelProviders.of and ViewModelProvider .我无法同时使用ViewModelProviders.ofViewModelProvider Both are deprecated in implementation "androidx.lifecycle:lifecycle-viewmodel:2.6.0-alpha01".两者都在实现“androidx.lifecycle:lifecycle-viewmodel:2.6.0-alpha01”中被弃用。 I'm providing the code.我正在提供代码。

/*
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.example.android.quakereport; 

import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast; 
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity; 
import java.util.ArrayList;
import java.util.List;

public class EarthquakeActivity extends AppCompatActivity {
    private MainViewModel viewModel;
    public final String USGS_REQUEST_URL = "https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&eventtype=earthquake&orderby=time&minmag=6&limit=10";
    TextView mEmptyStateTextView;
    public static final String LOG_TAG = EarthquakeActivity.class.getName();
    private DataAdapter mAdapter;

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.earthquake_activity);

        // Find a reference to the {@link ListView} in the layout
        ListView earthquakeListView = (ListView) findViewById(R.id.list);
        mEmptyStateTextView = (TextView) findViewById(R.id.empty_view);
        earthquakeListView.setEmptyView(mEmptyStateTextView);

        // Can't resolve ViewModelProviders
        viewModel = new ViewModelProvider(this).get(MainViewModel.class);

        // Network Connectivity
        ConnectivityManager connMgr = (ConnectivityManager)
        getSystemService(Context.CONNECTIVITY_SERVICE);

        // Get details on the currently active default data network
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();

        // If there is a network connection, fetch data
        if (networkInfo != null && networkInfo.isConnected()) {
            Toast.makeText(EarthquakeActivity.this, "Connected", Toast.LENGTH_SHORT).show();
        } else {
            // Otherwise, display error
            // First, hide loading indicator so error message will be visible
            mEmptyStateTextView.setText("No Internet Connection");
        }

        // Create a new adapter that takes an empty list of earthquakes as input
        mAdapter = new DataAdapter(this, new ArrayList<Data>());

        // Set the adapter on the {@link ListView}
        // so the list can be populated in the user interface
        earthquakeListView.setAdapter(mAdapter);
        EarthquakeAsyncTask task = new EarthquakeAsyncTask();
        task.execute(USGS_REQUEST_URL);
        // Set an item click listener on the ListView, which sends an intent to a web browser
        // to open a website with more information about the selected earthquake.
        earthquakeListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                // Find the current earthquake that was clicked on
                Data currentEarthquake = mAdapter.getItem(position);

                // Convert the String URL into a URI object (to pass into the Intent constructor)
                Uri earthquakeUri = Uri.parse(currentEarthquake.getUrl());

                // Create a new intent to view the earthquake URI
                Intent websiteIntent = new Intent(Intent.ACTION_VIEW, earthquakeUri);

                // Send the intent to launch a new activity
                startActivity(websiteIntent);
            }
        });
    }

    // Here I used AsyncTask I will replaced it too after fixing the ViewModelProvider Issue.
    private class EarthquakeAsyncTask extends AsyncTask<String, Void, List<Data>> {
        protected List<Data>  doInBackground(String... urls) {
            if (urls.length < 1 || urls[0] == null) {
                return null;
            }
            List<Data> result = QueryUtils.fetchEarthquakeData(urls[0]);
            return result;
        }

        protected void onPostExecute(List<Data> data) {
            // Clear the adapter of previous earthquake data
            mAdapter.clear();

            // If there is a valid list of {@link Earthquake}s, then add them to the adapter's
            // data set. This will trigger the ListView to update.
            if (data != null && !data.isEmpty()) {
                mAdapter.addAll(data);
            }
        }
    }
}

If you want to use new ViewModelProvider(this) , you need to import ViewModelProvider :如果要使用new ViewModelProvider(this) ,则需要导入ViewModelProvider

import androidx.lifecycle.ViewModelProvider

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用Android上的Dagger和Java,ViewModelProvider.Factory在片段上保持为空 - ViewModelProvider.Factory remains null on fragment using Dagger and Java on Android 如何在 Java 中使用 androidx.lifecycle.ViewModelProvider - How to use the androidx.lifecycle.ViewModelProvider in Java 在 Android 中,如何在单独的文件中获取 OnItemSelectedListener 中的 viewmodelprovider? - In Android, how to get viewmodelprovider in OnItemSelectedListener in separate file? ViewModelProvider Fragment 实例化 model - ViewModelProvider Fragment instantiate model ViewModelProvider 构造函数有什么区别 - what is the difference between ViewModelProvider constructors 在 AppCompatActivity 中使用 ViewModelProvider(this) 的运行时错误 - Runtime Error using ViewModelProvider(this) in AppCompatActivity Dagger 2 ViewModelProvider.Factory绑定多次 - Dagger 2 ViewModelProvider.Factory bound multiple times 执行 ViewModelProvider.Factory 并且我收到空指针异常 - Impementing a ViewModelProvider.Factory and I am getting a null pointer exeception ViewModelProvider() 创建一个错误,虽然自己的活动正在扩展 AppCompatActivity - ViewModelProvider() creates an error, although own activity is extending AppCompatActivity 为什么在ViewModelProvider.Factory实现中添加@Singleton批注会导致编译错误[Dagger / MissingBinding]? - Why adding @Singleton annotation to ViewModelProvider.Factory implementation causes a compile error [Dagger/MissingBinding]?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM