1

Trying out a test app but struggling with import issues. The code compiles but i don't see anything in the emulator.

Androidmanifest.xml

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

    <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>

AttractionsActivity class that governs the 'Attractions' tab

package com.example.nyctourguide;

import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;

public class AttractionsActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.container, new AttractionsFragment())
                .commit();
    }
}

AttractionsFragment that is tied to the above activity class

package com.example.nyctourguide;

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

import androidx.fragment.app.Fragment;

import java.util.ArrayList;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link AttractionsFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class AttractionsFragment extends Fragment {


    public AttractionsFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        //  return inflater.inflate(R.layout.word_list, container, false);
        View rootView = inflater.inflate(R.layout.site_list, container, false);

        //create a list of sites
        final ArrayList<Site> siteslist = new ArrayList<Site>();

        //populate the siteslist with the sites to be shown
        siteslist.add(new Site ("Empire State building","123 Main Street, NYC",R.drawable.color_green));
        siteslist.add(new Site ("Statue of Liberty","13 Main Street, NYC",R.drawable.color_brown));
        siteslist.add(new Site ("Bannon City Hall","133 Main Street, NYC",R.drawable.color_mustard_yellow));
        siteslist.add(new Site ("Brookyln Bridge","13 Main Street, NYC",R.drawable.color_gray));
        siteslist.add(new Site ("Staten Island","163 Main Street, NYC",R.drawable.color_white));
        siteslist.add(new Site ("Manhattan Bridge","133 Main Street, NYC",R.drawable.color_green));
        siteslist.add(new Site ("Chrysler Building","113 Main Street, NYC",R.drawable.color_dusty_yellow));
        siteslist.add(new Site ("Daimler Building","3 Main Street, NYC",R.drawable.color_brown));
        siteslist.add(new Site ("Rockefeller Center","15 Main Street, NYC",R.drawable.color_green));

        // view recycling with adaptor
        SiteAdapter adaptor = new SiteAdapter(getActivity(), siteslist, R.color.category_attractions);
        ListView listView = (ListView) rootView.findViewById(R.id.list);
        listView.setAdapter(adaptor);

        //return the entire root view
        return rootView;

    }

}

Main Activity

package com.example.nyctourguide;

import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;

import com.google.android.material.tabs.TabLayout;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Set the content of the activity to use the activity_main.xml layout file
        setContentView(R.layout.activity_main);

        // Find the view pager that will allow the user to swipe between fragments
        ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);

        // Create an adapter that knows which fragment should be shown on each page
        SimpleFragmentPagerAdapter adapter = new SimpleFragmentPagerAdapter(this,getSupportFragmentManager());

        // Set the adapter onto the view pager
        viewPager.setAdapter(adapter);

        // Find the tab layout that shows the tabs  - 7/28
        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);

        // Connect the tab layout with the view pager. This will
        //   1. Update the tab layout when the view pager is swiped
        //   2. Update the view pager when a tab is selected
        //   3. Set the tab layout's tab names with the view pager's adapter's titles
        //      by calling onPageTitle()
        tabLayout.setupWithViewPager(viewPager);
    }
}

SimpleFragmentAdapter

package com.example.nyctourguide;

import android.content.Context;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;

//import android.support.design.widget.TabLayout;

//import androidx.fragment.app.FragmentPagerAdapter;
//import android.support.v4.app.FragmentManager;
//import android.support.v4.app.FragmentPagerAdapter;

/*Provides the appropriate {@link Fragment} for a view pager.*/
public class SimpleFragmentPagerAdapter extends FragmentPagerAdapter {

    /** Context of the app */
    private Context mContext;

    //context is the context of the app
    //fm is the fragment manager that will keep each fragment's state in the adapter across swipes.
    public SimpleFragmentPagerAdapter(Context context, FragmentManager fm) {
        super(fm);
        mContext = context;
    }

    //Return the Fragment that should be displayed for the given page
    @Override
    public Fragment getItem(int position) {
            if (position == 0) {
                return new AttractionsFragment();
            } else if (position == 1){
                return new MuseumFragment();
            } else if (position == 2){
                return new ParksFragment();
            } else {
                return new RestaurantFragment();
         }
    }

    //return the total number of pages
    @Override
    public int getCount() {
        return 4;
    }

    //show the right tab layout name
    @Override
    public CharSequence getPageTitle(int position) {
        if (position == 0){
            return mContext.getString(R.string.category_attractions);
        } else if (position == 1){
            return mContext.getString(R.string.category_museums);
        } else if (position == 2){
            return mContext.getString(R.string.category_parks);
        } else {
            return mContext.getString(R.string.category_restaurants);
        }

    }
}

Activity_main.xml

<!-- Layout for the main screen -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">


    <!-- added for tabbed layout  -->
    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />


    <!-- added for viewpager -->
    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

Build.gradle (you can see all my trial and error here at adding the right stuff)

plugins {
    id 'com.android.application'
}

android {
    compileSdkVersion 30
    buildToolsVersion "30.0.3"

    defaultConfig {
        applicationId "com.example.nyctourguide"
        minSdkVersion 16
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

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

dependencies {
  //  implementation 'androidx.appcompat:appcompat:1.3.0' //original
    implementation 'com.google.android.material:material:1.4.0' //original
   // implementation 'androidx.constraintlayout:constraintlayout:2.0.4' //original
   // implementation 'androidx.legacy:legacy-support-v4:1.0.0' //original
    testImplementation 'junit:junit:4.+' //original
    // androidTestImplementation 'androidx.test.ext:junit:1.1.3' //original
    //androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0' //original
    implementation 'com.android.support:appcompat-v7:28.0.0' //added
    implementation 'com.android.support:support-v4:28.0.0' //added
    implementation 'com.android.support:design:28.0.0'//added
    implementation 'com.android.support:viewpager:28.0.0'//added
    implementation 'com.android.support:design:26.0.+'//added
    implementation 'com.android.support:design:23.3.0' //added
    implementation "com.google.android.material:material:1.0.0" //added

    //noinspection GradleCompatible,GradleCompatible

}

gradle.properties

# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
# AndroidX package structure to make it clearer which packages are bundled with the
# Android operating system, and which are packaged with your app"s APK
# https://developer.android.com/topic/libraries/support-library/androidx-rn
android.useAndroidX=true
android.enableJetifier=true
RBuser
  • 11
  • 2
  • I'm not sure what you mean by "i don't see anything in the emulator", but I would point out that `AttractionsActivity` is not used at all anywhere, so you might just get rid of it for now to prevent confusion. Beyond that, please be very specific about what you're observing in the emulator. – Mike M. Jul 29 '21 at 18:59
  • Thanks Mike. In the emulator - nothing happens but after a while i get the 'App crashed' info. The AttractionsActivity is used to load the AttractionsFragment (per my beginner's understanding of this code - i'm totally new to android). – RBuser Jul 29 '21 at 19:07
  • If it's crashing, you'll need to look at [the stack trace](https://stackoverflow.com/a/23353174) to determine the cause. Please feel free to [edit] your question to add it here, if you'd like some assistance in reading it. – Mike M. Jul 29 '21 at 19:09
  • Actually, looking again, you're right about the androidx class mix-up. You've got the wrong class names in the `activity_main` layout. Compare those to the imports in your code files. The imports are the correct ones. `` -> `` and `` -> ``. Fix those first, then see if we still have a problem. – Mike M. Jul 29 '21 at 19:11
  • Thanks Mike - could you clarify by what you meant by wrong class names in activity_main? I don't see any class names there and the imports are already added there. Could you kindly advise? Thank you. – RBuser Jul 29 '21 at 19:41
  • `activity_main` is the layout XML file that you've posted, in the 6th code block above. It has the old class names in its tags. – Mike M. Jul 29 '21 at 19:43
  • 1
    Got it! It was showing up in red so i knew i had to change it but I did not know what to change it to. Added the imports that you suggested - and now it works correctly! Thank you! Mike - you made my day :). – RBuser Jul 29 '21 at 20:08
  • Is there a way in Studio to automatically refactor the entire project to move to AndroidX. For e.g I do see Refactor -> Migrate, but don't see an option to move to AndroidX and fix all these import issues automatically. It's next to impossible to find this out ourselves. – RBuser Jul 29 '21 at 20:09
  • Hmm, are you running an old version of Android Studio? I had to double-check, but my next-to-most-recent version has [Refactor -> Migrate to AndroidX...](https://i.stack.imgur.com/rOlgd.png) specifically, toward the bottom. Does yours not have that? I wouldn't think they'd remove that, but I haven't upgraded to the most recent yet, so I can't be sure. – Mike M. Jul 29 '21 at 20:12
  • 1
    Yep i see it now at the level of each file. Thanks again Mike. Appreciate it. – RBuser Jul 29 '21 at 20:42

0 Answers0