Coder Social home page Coder Social logo

patloew / countries Goto Github PK

View Code? Open in Web Editor NEW
614.0 35.0 104.0 560 KB

An example Android app using Retrofit, Realm, Parceler, Dagger and the MVVM pattern with the data binding lib.

License: Other

Java 11.23% Kotlin 88.77%
android android-architecture mvvm android-mvvm realm dagger parceler data-binding mvvm-pattern retrofit

countries's Introduction

Countries

Build Status

A sample Android app written in Kotlin, which lists all countries with some additional information (currencies, languages, …). The app uses the MVVM pattern with the Android data binding lib. Countries can be bookmarked and are then stored locally with Realm. Retrofit is used to fetch the country information from the free REST Countries service. For JSON parsing, custom Gson TypeAdapters are used. PaperParcel is used to make the Country objects Parcelable. Also, Dagger 2 is used for dependency injection.

The purpose of this is app is to show how:

This project can also be used as a template for new apps. Check out the template branch for a cleaned up version of this project.

License

Copyright 2016 Patrick Löwenstein

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

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.

countries's People

Contributors

floschu avatar patloew avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

countries's Issues

Realm instances properly closed?

Awesome project - thanks a lot for the demo;

One minor issue though:

I found that realm instances created here:

...are never closed. Either I miss an important point here or a memory leak is created
when the backup store is queried... (Realm.getInstance() Is called on every query...)

I am not sure if this is intended... what do I miss?
In activities, the Realm is properly closed within onDestroy()... so no problem there.

Adding a third tab and going back and forth crashes the app

Thank you very much for sharing this code. I've been playing with it to learn DI, realm, and all that good stuff. When I add another tab in MainAdapter.java:

@Override
    public Fragment getItem(int position) {
        switch (position) {
            case 0:
                return new AllCountriesFragment();
            case 1:
                return new FavoriteCountriesFragment();
            //case 2:
            //    return new FavoriteCountriesFragment();
        }
        return null;
    }
    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return res.getString(R.string.tab_title_all);
            case 1:
                return res.getString(R.string.tab_title_favorites);
            //case 2:
            //    return res.getString(R.string.tab_title_favorites);
        }

        return null;
    }

I get an exception in BaseFragment.java:

protected final View setAndBindContentView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState, @LayoutRes int layoutResID) {
        if (viewModel == null)
            throw new IllegalStateException("viewModel must already be set via injection");

java.lang.IllegalStateException: viewModel must already be set via injection

Commenting out the viewModel in onDestroyView

//viewModel = null;

avoids the crash but strange things happen afterwards.

Any pointers on what to do to help me understand the bigger picture and fix this? The question really is why isn't the viewModel being injected on a tab change. Thanks a lot.

Shared Element Transition

Navigator is injected into ViewModels and used there.
What is the correct way of adding some shared views to navigation?

Size of installed application is very large

Why the size of installed app can be very large, I enabled APK split feature at Gradle confiuguration, in my case APK size is 4 through 6 MB and installed app size is +40 MB (My device Xiaomi Redmi 4x) ?

Cannot resolve symbol 'DaggerAppComponent'

Just checked out the project and imported it to Android Studio.

It says 'Cannot find symbol "DaggerAppComponent"' which should be located inside ../injection/components but it´s not. Has it been replaced or removed? In that case, the CountriesApp.java onCreate() code should be modified?

Thanks!

Kotlin: Crash on resume / orientation change

Device: Nexus 6P
Android 7.1.1

02-14 15:38:55.521 20057-20057/com.patloew.countries.dev E/AndroidRuntime: FATAL EXCEPTION: main Process: com.patloew.countries.dev, PID: 20057 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.patloew.countries.dev/com.patloew.countries.ui.main.MainActivity}: kotlin.UninitializedPropertyAccessException: lateinit property activityComponent has not been initialized at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726) at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4519) at android.app.ActivityThread.-wrap19(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1483) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:154) at android.app.ActivityThread.main(ActivityThread.java:6119) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) Caused by: kotlin.UninitializedPropertyAccessException: lateinit property activityComponent has not been initialized at com.patloew.countries.ui.base.BaseActivity.getActivityComponent$app_devBackendDebug(BaseActivity.kt:66) at com.patloew.countries.ui.base.BaseFragment.onAttach(BaseFragment.kt:90) at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1231) at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1528) at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1595) at android.support.v4.app.FragmentManagerImpl.dispatchCreate(FragmentManager.java:2883) at android.support.v4.app.FragmentController.dispatchCreate(FragmentController.java:190) at android.support.v4.app.FragmentActivity.onCreate(FragmentActivity.java:353) at android.support.v7.app.AppCompatActivity.onCreate(AppCompatActivity.java:85) at com.patloew.countries.ui.base.BaseActivity.onCreate(BaseActivity.kt:76) at com.patloew.countries.ui.main.MainActivity.onCreate(MainActivity.kt:38) at android.app.Activity.performCreate(Activity.java:6679) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)  at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4519)  at android.app.ActivityThread.-wrap19(ActivityThread.java)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1483)  at android.os.Handler.dispatchMessage(Handler.java:102)  at android.os.Looper.loop(Looper.java:154)  at android.app.ActivityThread.main(ActivityThread.java:6119)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) 

ClassNotFoundException when unmarshalling: io.realm.NeedRealmProxy$$Parcelable #4459

Hi,

Please I follow your tutorial [https://nullpointer.wtf/android/using-retrofit-realm-parceler/](Using Retrofit with Realm and Parceler) but I always have this error

android.os.BadParcelableException: ClassNotFoundException when unmarshalling: io.realm.NeedRealmProxy$$Parcelable
at android.os.Parcel.readException(Parcel.java:1427)
at android.os.Parcel.readException(Parcel.java:1379)
at android.app.ActivityManagerProxy.startActivity(ActivityManagerNative.java:1761)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1411)
at android.app.Activity.startActivityForResult(Activity.java:3351)
at android.support.v4.app.BaseFragmentActivityJB.startActivityForResult(BaseFragmentActivityJB.java:50)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:79)
at android.support.v4.app.ActivityCompatJB.startActivityForResult(ActivityCompatJB.java:30)
 at android.support.v4.app.ActivityCompat.startActivityForResult(ActivityCompat.java:146)
at android.support.v4.app.FragmentActivity.startActivityFromFragment(FragmentActivity.java:932)
at android.support.v4.app.FragmentActivity$HostCallbacks.onStartActivityFromFragment(FragmentActivity.java:1047)
at android.support.v4.app.Fragment.startActivity(Fragment.java:940)
 at com.nkapsi.ui.fragment.HomeFragment.onTaskClick(HomeFragment.java:201)

I got that error when running this snippet of code from a fragment HomeFragment

public void onTaskClick(View view, Need need, int position) {
        Log.d(TAG, "onTaskClick() - " + need.toString());

        Intent intent = new Intent(getActivity(), TaskDetailsActivity.class);

        Bundle bundle = new Bundle();
        bundle.putParcelable(TaskDetailsActivity.EXTRA_OBJ_NEED, Parcels.wrap(need));

        startActivity(intent, bundle);
    }

Here is Need.java

@Parcel(implementations = {NeedRealmProxy.class}, value = Parcel.Serialization.FIELD, analyze = { Need.class })
public class Need extends RealmObject implements Serializable {

    @PrimaryKey
    @SerializedName("_id")
    private String id;

    @SerializedName("created")
    private Date created;

    @SerializedName("status")
    private String status;

    @SerializedName("fees")
    float fees;

    @SerializedName("user")
    private User user;

    @ParcelPropertyConverter(RealmListParcelConverter.class)
    @SerializedName("places")
    private RealmList<Place> places;

    @SerializedName("user_location")
    private Place userLocation;

    @ParcelPropertyConverter(RealmListParcelConverter.class)
    @SerializedName("items_ordered")
    private RealmList<ItemOrdered> itemsOrdered;

    @ParcelPropertyConverter(RealmListParcelConverter.class)
    @SerializedName("movings")
    private RealmList<Moving> movings;

    @ParcelPropertyConverter(RealmListParcelConverter.class)
    @SerializedName("messages")
    private RealmList<Message> messages;

    @SerializedName("run")
    private Run run;


    public Need() {}

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public List<Place> getPlaces() {
        return places;
    }

    public List<ItemOrdered> getItemsOrdered() {
        return itemsOrdered;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public Double getAmount() {
        double p = 0;
        for (ItemOrdered e: itemsOrdered) {
            if (e.getItem().getPrice() != null) {
                p += e.getItem().getPrice() * e.getQuantity();
            }
        }

        return p;
    }

    public Place getUserLocation() {
        return userLocation;
    }

    public void setUserLocation(Place userLocation) {
        this.userLocation = userLocation;
    }

    public Date getCreated() {
        return created;
    }

    public String getCreatedFormatted() {
        SimpleDateFormat format = new SimpleDateFormat("MMM dd, HH:mm");

        return format.format(created);
    }

    public void setCreated(Date created) {
        this.created = created;
    }

    public String getStatus() {
        return status;
    }

    public List<Message> getMessages() {
        return messages;
    }

    public Run getRun() {
        return this.run;
    }

    public List<Moving> getMovings() {
        return movings;
    }

    public void setMovings(RealmList<Moving> movings) {
        this.movings = movings;
    }

    public float getFees() {
        return fees;
    }

    public void setFees(float fees) {
        this.fees = fees;
    }

    public void setPlaces(RealmList<Place> places) {
        this.places = places;
    }

    public void setItemsOrdered(RealmList<ItemOrdered> itemsOrdered) {
        this.itemsOrdered = itemsOrdered;
    }

    public void setMessages(RealmList<Message> messages) {
        this.messages = messages;
    }

    @Override
    public String toString() {
        return "Need{" +
                "id= '" + id + '\'' +
                ", movings='" + movings.size() + '\'' +
                ", places=" + places.size() +
                ", itemsOrdered=" + itemsOrdered.size() +
                ", userLocation=" + userLocation.getLng() + "," + userLocation.getLat() +
                ", user=" + user +
                '}';
    }
}

Here is RealmListParcelConverter.java

public class RealmListParcelConverter implements
        TypeRangeParcelConverter<RealmList<? extends RealmObject>, RealmList<? extends RealmObject>> {
    private static final int NULL = -1;

    @Override
    public void toParcel(RealmList<? extends RealmObject> input, android.os.Parcel parcel) {
        parcel.writeInt(input == null ? NULL : input.size());
        if (input != null) {
            for (RealmObject item : input) {
                parcel.writeParcelable(Parcels.wrap(item), 0);
            }
        }
    }

    @Override
    public RealmList fromParcel(android.os.Parcel parcel) {
        int size = parcel.readInt();
        RealmList list = new RealmList();
        for (int i=0; i<size; i++) {
            Parcelable parcelable = parcel.readParcelable(getClass().getClassLoader());
            list.add((RealmObject) Parcels.unwrap(parcelable));
        }
        return list;
    }
}

Please help me to solve this error .

Template Guideline

Hi Patloew,

I really appreciate your work for this template, and I want to learn your template, but I don't know where to get started. Would you like give me some guidelines or instruction for using this template?

thank you

Build error

Hi sir, i want try your mvvm structure but i got exception, kotlin-template (android studio 3.4) (kotlin 1.3.21)

e: error: incremental out directory should be set to aar output directory.
e: [kapt] An exception occurred: java.lang.RuntimeException: failure, see logs for 
details.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.