ViewModelProviders.of(c).get(CountryViewModel.class);

224 Views Asked by At

In my Android project I work with MVVM - and when I use the ViewModelProviders it get deprecated(which mean that I get line over ViewModelProviders)

I work with RecyclerView that contains names of countries(that exist in one fragment), when I click on item in the RecyclerView, I need to pass to another Fragment that will show the detail of the country that was clicked.

and I need to know what is the problem

enter image description here

Here is the gradle file:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 28


    defaultConfig {
        applicationId "com.bhaa.ex7f"
        minSdkVersion 26
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:recyclerview-v7:28.0.0'
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
    def lifecycle_version = "2.1.0"
    implementation "androidx.lifecycle:lifecycle-extensions:$lifecycle_version"
    implementation "androidx.lifecycle:lifecycle-extensions:2.2.0"
    implementation 'androidx.fragment:fragment-ktx:1.1.0'
    implementation 'androidx.recyclerview:recyclerview:1.1.0-beta03';
    implementation 'android.arch.lifecycle:extensions:1.1.1';
}

Here is the adapter of the RecyclerView:

package com.bhaa.ex7f;

import android.app.MediaRouteButton;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.RecyclerView;


import java.util.ArrayList;

public class myAdapter extends RecyclerView.Adapter<myAdapter.subClass>  {

public static String tag="ex7.bhaa";
//**************************************************************************************************************************

    CountryViewModel viewModel;

//****************************************************************************************************************************

private static OnItemClickListener mListener;

public interface OnItemClickListener{
        void  onItemClick(ArrayList<Country> c, int position);
    }

public static void setOnClickListener(OnItemClickListener listener){
    mListener=listener;
}

//****************************************************************************************************************************

       public static Context adapterContext;
    public static ArrayList<Country> listOfCountries;
//****************************************************************************************************************************

    public myAdapter(Context c){
        adapterContext=c;
        listOfCountries=CountryXMLParser.parseCountries(c );
        viewModel = ViewModelProviders.of(c).get(CountryViewModel.class);
        viewModel.getAllCountriesLiveData().observe(c, countryList);
    }

    Observer<ArrayList<Country>> countryList = new Observer<ArrayList<Country>>() {
        @Override
        public void onChanged(ArrayList<Country> userArrayList) {

        }
    };


//--------------------------------------------------------------------------------------------------------------------------

    @NonNull
    @Override
    public subClass onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
     View v= LayoutInflater.from(parent.getContext()).inflate(R.layout.coutry,parent,false);
        subClass subC=new subClass(v,mListener);
        return subC;
    }
//--------------------------------------------------------------------------------------------------------------------------

    @Override
    public void onBindViewHolder(@NonNull subClass holder, int position) {
        try {
            holder.bindData(position);
        }catch (Exception  e){

        }

    }
//--------------------------------------------------------------------------------------------------------------------------
    @Override
    public int getItemCount() {
        return listOfCountries.size();
    }

//*************************************************************************************************************************

    public class subClass extends RecyclerView.ViewHolder {

        public  ImageView flag_Img;
        public  TextView country_Name;
        public  TextView country_description;
        View  mDividerView;
//=======================================================================================================================
        public subClass(@NonNull View itemView,final OnItemClickListener listener) {
            super(itemView);

            flag_Img=itemView.findViewById(R.id.flag);
            country_Name=(TextView) itemView.findViewById(R.id.countryName);
            country_description=(TextView) itemView.findViewById(R.id.poplution);

            mDividerView=itemView.findViewById(R.id.divider);
            itemView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    if (listener!=null){
                        int position=getAdapterPosition();
                        if(position!=RecyclerView.NO_POSITION){
                            listener.onItemClick(listOfCountries,position);

                        }
                    }
                return true;
                }
            });
        }
//============================================================================================================================
        public  void bindData(int position){
            Country currentCountry=myAdapter.listOfCountries.get(position);

            Log.i(tag,String.valueOf(position));
            if(position == getItemCount() - 1) {

                mDividerView.setVisibility(View.INVISIBLE) ;
            }
            flag_Img.setImageResource(adapterContext.getResources().getIdentifier(currentCountry.getFlag(),
                                            "drawable",adapterContext.getPackageName()));
            country_Name.setText(currentCountry.getName());
            country_description.setText(currentCountry.getShorty());

        }


       /* public  void setCountry(ArrayList<Country> cnt){
            myAdapter.listOfCountries=cnt;
            notifyDataSetChanged();
        }*/

    }


}


and here is the ViewModel :

package com.bhaa.ex7f;

import android.app.Application;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import java.lang.reflect.Array;

import java.util.ArrayList;

public class CountryViewModel extends ViewModel {





       MutableLiveData<ArrayList<Country>> allCountriesLiveData;
       ArrayList<Country> countryArrayList;

        MutableLiveData<String> details;
        String Details;


    public CountryViewModel() {

        allCountriesLiveData=new MutableLiveData<ArrayList<Country>>();
        details=new MutableLiveData<String>();
        init();
    }

    private void init() {
        populateList();
        allCountriesLiveData.setValue(countryArrayList);
    }

    private void populateList() {
        countryArrayList=new ArrayList<>();

        //countryArrayList=CountryXMLParser.parseCountries()

        //details=
    }


    public MutableLiveData<ArrayList<Country>> getAllCountriesLiveData() {
        return allCountriesLiveData;
    }

    public MutableLiveData<String> getDetails() {
        return details;
    }


}






first Fragment :

package com.bhaa.ex7f;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import android.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.lifecycle.ViewModelProviders;
import androidx.lifecycle.ViewModelStoreOwner;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;


import java.util.ArrayList;

public class Port_Frag_Rec extends Fragment {

    private RecyclerView myRecyclerView;
     myAdapter mAdapter;
    private RecyclerView.LayoutManager mLayoutManager;

    private CountryViewModel countryViewModel;


    @Override
    public View onCreateView( LayoutInflater inflater,  ViewGroup container,  Bundle savedInstanceState) {

        return inflater.inflate(R.layout.port_frag_rec, container, false);

    }

    @Override
    public void onViewCreated( View view,  Bundle savedInstanceState) {


       // countryViewModel=new ViewModelProvider((ViewModelStoreOwner) this.getParentFragment()).get(CountryViewModel.class);






       final ArrayList<Country> c = new ArrayList<>();

      //  c.add(new Country("bhqq", String.valueOf(R.drawable.brazil), "1955"));
        // c.add(new Country("651156", "rizik", "558"));

        myRecyclerView = view.findViewById(R.id.recyleView);
        mAdapter = new myAdapter(this.getContext());
        myRecyclerView.setHasFixedSize(false);
        myRecyclerView.setLayoutManager(new LinearLayoutManager(this.getContext()));
        myRecyclerView.setAdapter(mAdapter);

      mAdapter.setOnClickListener(new myAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(ArrayList<Country> c,int position) {
                c.remove(position);
                mAdapter.notifyItemRemoved(position);
              //  countryViewModel.select(c.get(position));
            }
        });
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public void onActivityCreated( Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }


    public interface ClickHandler{
        public void OnClickEvent();
    }

}

CountryXMLParser:

package com.bhaa.ex7f;


import android.content.Context;
import android.content.res.AssetManager;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;



public class CountryXMLParser {
    final static String KEY_COUNTRY="country";
    final static String KEY_NAME="name";
    final static String KEY_FLAG="flag";
    final static String KEY_ANTHEM="anthem";
    final static String KEY_SHORT="short";
    final static String KEY_DETAILS="details";


    public static ArrayList<Country> parseCountries(Context context){
        ArrayList<Country> data = null;
        InputStream in = openCountriesFile(context);
        XmlPullParserFactory xmlFactoryObject;
        try {
                xmlFactoryObject = XmlPullParserFactory.newInstance();
                XmlPullParser parser = xmlFactoryObject.newPullParser();

                parser.setInput(in, null);
                int eventType = parser.getEventType();
                Country currentCountry = null;
                String inTag = "";
                String strTagText = null;

                while (eventType != XmlPullParser.END_DOCUMENT){
                    inTag = parser.getName();
                    switch (eventType){
                        case XmlPullParser.START_DOCUMENT:
                            data = new ArrayList<Country>();
                            break;
                        case XmlPullParser.START_TAG:
                            if (inTag.equalsIgnoreCase(KEY_COUNTRY))
                                currentCountry = new Country();
                            break;
                        case XmlPullParser.TEXT:
                            strTagText = parser.getText();
                            break;
                        case XmlPullParser.END_TAG:
                            if (inTag.equalsIgnoreCase(KEY_COUNTRY))
                                data.add(currentCountry);
                            else if (inTag.equalsIgnoreCase(KEY_NAME))
                                currentCountry.setName( strTagText);
                            else if (inTag.equalsIgnoreCase(KEY_SHORT))
                                currentCountry.setShorty( strTagText);
                            else if (inTag.equalsIgnoreCase(KEY_FLAG))
                                currentCountry.setFlag(strTagText);
                            else if (inTag.equalsIgnoreCase(KEY_ANTHEM))
                                currentCountry.setAnthem(strTagText);
                            else if (inTag.equalsIgnoreCase(KEY_DETAILS))
                                currentCountry.setDetails(strTagText);
                            inTag ="";
                            break;                      
                    }//switch
                    eventType = parser.next();
                }//while
            } catch (Exception e) {e.printStackTrace();}
        return data;
    }

    private static InputStream openCountriesFile(Context context){
        AssetManager assetManager = context.getAssets();
        InputStream in =null;
        try {
            in = assetManager.open("countries.xml");
        } catch (IOException e) {e.printStackTrace();}
        return in;
    }
}

Country:

package com.bhaa.ex7f;

public class Country {
    String name;
    String flag;
    String details;
    String anthem;
    String shorty;

    public String getFlag() {
        return flag;
    }

    public void setFlag(String flag) {
        this.flag = flag;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getShorty() {
        return shorty;
    }

    public void setShorty(String shorty) {
        this.shorty = shorty;
    }

    public Country(String name, String flag, String shorty){
        this.name = name;
        this.flag = flag;
        this.shorty=shorty;
        this.details="";

    }

    public String getAnthem() {
        return anthem;
    }

    public void setAnthem(String anthem) {
        this.anthem = anthem;
    }

    public Country() {
        // TODO Auto-generated constructor stub
    }

    public void setDetails(String details){
        this.details=details;
    }
    public String getDetails(){
        return this.details;
    }

    public int compare(Country other) {
        return  this.name.compareTo(other.name);
    }

    @Override
    public String toString() {
        return name;
    }
}

0

There are 0 best solutions below