java - Android:startActivity() 适用于一个 Activity ,但不适用于另一个 Activity

标签 java android

我正在处理的应用程序的一部分有两个按钮,我的问题是当我调用 startActivity() 时,它会按预期用于一个 Activity 而不是另一个 Activity 。

所以这是可行的:

startActivity(new Intent(StartScreenActivity.this, FiltersActivity.class));

但这不是:

startActivity(new Intent(StartScreenActivity.this, MainActivity.class));

昨天两者都运行良好,但自从今天早上更新 Android Studio 后,当我尝试启动 MainActivity 时没有任何反应。两者都出现在我的 list 中:

<activity
    android:name=".FiltersActivity"
    android:label="@string/title_activity_filters"
    android:theme="@style/AppTheme.NoActionBar" >
</activity>
<activity
    android:name=".MainActivity"
    android:label="@string/title_activity_main"
    android:theme="@style/AppTheme.NoActionBar" >
</activity>

不会向 LogCat 或类似的东西抛出任何错误,只是其中一个有效,而另一个没有任何反应。我会假设 MainActivity 类有问题,但它在几个小时前工作正常,从那时起唯一的变化就是更新 Studio,正如我提到的,我对主 Activity 布局文件进行了一些小的 xml 布局更改尝试撤消,但这并不能解决问题。


完整 list :

<?xml version="1.0" encoding="utf-8"?>

<!--
     The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
     Google Maps Android API v2, but you must specify either coarse or fine
     location permissions for the 'MyLocation' functionality. 
-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".StartScreenActivity"
        android:label="@string/app_name"
        android:theme="@style/AppTheme.NoActionBar" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <!--
         The API key for Google Maps-based APIs is defined as a string resource.
         (See the file "res/values/google_maps_api.xml").
         Note that the API key is linked to the encryption key used to sign the APK.
         You need a different API key for each encryption key, including the release key that is used to
         sign the APK for publishing.
         You can define the keys for the debug and release targets in src/debug/ and src/release/. 
    -->
    <meta-data
        android:name="com.google.android.geo.API_KEY"
        android:value="@string/google_maps_key" />

    <activity
        android:name=".FiltersActivity"
        android:label="@string/title_activity_filters"
        android:theme="@style/AppTheme.NoActionBar" >
    </activity>
    <activity
        android:name=".MainActivity"
        android:label="@string/title_activity_main"
        android:theme="@style/AppTheme.NoActionBar" >
    </activity>
    <activity
        android:name=".AddNewVenue"
        android:theme="@style/AppTheme.NoActionBar" >
    </activity>
    <activity
        android:name=".AddNewMenuItemActivity"
        android:label="@string/title_activity_add_new_menu_item"
        android:theme="@style/AppTheme.NoActionBar" >
    </activity>
</application>


主要 Activity .java:

package me.theglassboard.vee;

public class MainActivity extends FragmentActivity
    implements VenueListFragment.OnFragmentInteractionListener, LocationListener {

private VenueDao venueDao;
private ArrayList<Venue> venues;

private LocationManager locationManager;
private Location userLocation;

// Static strings to be used when putting and getting extras to/from intents
public static String MAX_PRICE = "maxPrice";
public static String MAX_DISTANCE = "maxDistance";
public static String ACCEPTS_CARD = "acceptsCard";
public static String WHEELCHAIR_ACCESS = "wheelchairAccess";
public static String SERVES_NON_VEGAN = "servesNonVegan";
public static float DEFAULT_MAX_DISTANCE = 5000;
public static int DEFAULT_MAX_PRICE = 999;

public static FragmentManager fragmentManager;
public SectionsPagerAdapter mSectionsPagerAdapter;

/**
 * Request codes:
 *
 * Used in the MapFragment and ListFragment when adding a new
 * Venue or Menu Item. Those operations use startActivityForResult()
 * and the request code parameter of that method will be one of these
 * codes. They are therefor public static to ensure the fragments
 * have access, and final to ensure their values can't change at runtime.
 */
public static final int ADD_NEW_VENUE = 111;
public static final int ADD_NEW_MENU_ITEM = 222;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    setupLocation();
    //venueDao = new VenueDao(this);
    //venues = venueDao.getAllVenues();

    fragmentManager = getSupportFragmentManager();

    // Enable custom back button
    findViewById(R.id.toolbarLeftButton).setVisibility(View.VISIBLE);
    findViewById(R.id.toolbarLeftButton).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            finish();
        }
    });

}

private void searchVenues() {

    Log.d("INSIDE", "searchVenues()");

    Bundle extras = getIntent().getExtras();
    int maxPrice = extras.getInt(FiltersActivity.MAX_PRICE, DEFAULT_MAX_PRICE);
    float maxDistance = extras.getFloat(FiltersActivity.MAX_DISTANCE, DEFAULT_MAX_DISTANCE);
    Boolean acceptsCard = extras.getBoolean(FiltersActivity.ACCEPTS_CARD, false);
    Boolean wheelchairAccess = extras.getBoolean(FiltersActivity.WHEELCHAIR_ACCESS, false);
    Boolean servesNonVegan = extras.getBoolean(FiltersActivity.SERVES_NON_VEGAN, false);

    GetVenuesTask getVenuesTask = new GetVenuesTask(
            (int)maxDistance,
            (float)userLocation.getLatitude(),
            (float)userLocation.getLongitude(),
            maxPrice,
            acceptsCard,
            wheelchairAccess,
            servesNonVegan,
            this);

    getVenuesTask.execute();

}

public void launchMainActivity(ArrayList<Venue> fetchedVenues) {

    Log.d("INSIDE", "launchMainActivity()");

    // Create the adapter that will return a fragment for both of the
    // primary sections of the activity.

    venues = fetchedVenues;

    //findViewById(R.id.loadingFrame).setVisibility(View.GONE);

    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

    // Set up the ViewPager with the sections adapter
    ViewPager mViewPager = (ViewPager) findViewById(R.id.container);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(mViewPager);
    tabLayout.setTabsFromPagerAdapter(mSectionsPagerAdapter);
}

@Override
public void onFragmentInteraction(String id) {

}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    // Pass the activity result to both the map and list fragments
    // to perform whatever task they need to do.
    for(Fragment fragment : fragmentManager.getFragments())
        fragment.onActivityResult(requestCode, resultCode, data);
}


/**
 * Fragment Adapter that returns either the VenueMap or VenueList fragments
 */
public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    VenueMapFragment mapFragment;
    VenueListFragment listFragment;

    @Override
    public Fragment getItem(int position) {
        // getItem is called to instantiate the fragment for the given page.
        // Return a PlaceholderFragment (defined as a static inner class below).

        if(position == 0/* && GooglePlayServicesUtil.isGooglePlayServicesAvailable(MainActivity.this) == ConnectionResult.SUCCESS*/) {
            mapFragment = VenueMapFragment.newInstance(venues);
            return mapFragment;
        }

        if(position == 1) {
            listFragment = VenueListFragment.newInstance(venues);
            return listFragment;
        }

        return PlaceholderFragment.newInstance(position + 1);
    }

    @Override
    public int getCount() {
        // Show 2 total pages.
        return 2;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return "MAP";
            case 1:
                return "LIST";
        }
        return null;
    }
}

/**
 * The placeholder fragment initially provided by Studio.
 *
 * I am keeping it here for the time being as a default fragment
 * to be displayed if, for some reason, the map or list fragment
 * cannot be loaded.
 */
public static class PlaceholderFragment extends Fragment {
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
    private static final String ARG_SECTION_NUMBER = "section_number";

    /**
     * Returns a new instance of this fragment for the given section
     * number.
     */
    public static PlaceholderFragment newInstance(int sectionNumber) {
        PlaceholderFragment fragment = new PlaceholderFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

    public PlaceholderFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, container, false);
        TextView textView = (TextView) rootView.findViewById(R.id.section_label);
        textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
        return rootView;
    }
}

public void onLocationChanged(Location location) {

    userLocation = location;

    if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
            ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60000, 5, this);
        searchVenues();
        return;
    }
    locationManager.removeUpdates(this);
    searchVenues();
}

public void onProviderDisabled(String provider) {
    //CODE
}

public void onProviderEnabled(String provider) {
    //CODE
}

public void onStatusChanged(String provider, int status, Bundle extras) {
    //CODE
}

public void setupLocation() {
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
            ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60000, 5, this);
        return;
    }
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60000, 5, this);
}

@Override
protected void onResume()
{
    super.onResume();

    if(venues == null)
        finish();

    if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
            ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60000, 5, this);
        return;
    }
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60000, 5, this);
}

@Override
protected void onPause()
{
    super.onPause();
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
            ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60000, 5, this);
        return;
    }
    locationManager.removeUpdates(this);
}
}

StartScreenActivity.java:

public class StartScreenActivity extends AppCompatActivity {

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

    VenueDao venueDao = new VenueDao(this);

    findViewById(R.id.startScreenGoButton).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Log.d("CLICKED", "Start Main Activity");
            Intent mainActivity = new Intent(StartScreenActivity.this, MainActivity.class);
            mainActivity.putExtra(MainActivity.MAX_PRICE, MainActivity.DEFAULT_MAX_PRICE);
            mainActivity.putExtra(MainActivity.MAX_DISTANCE, MainActivity.DEFAULT_MAX_DISTANCE);
            mainActivity.putExtra(MainActivity.ACCEPTS_CARD, false);
            mainActivity.putExtra(MainActivity.WHEELCHAIR_ACCESS, false);
            mainActivity.putExtra(MainActivity.SERVES_NON_VEGAN, false);

            startActivity(mainActivity);
        }
    });

    findViewById(R.id.startScreenFilterButton).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startActivity(new Intent(StartScreenActivity.this, FiltersActivity.class));
        }
    });
}

}

最佳答案

更改您的 <activity>在 list 中:

<activity
    android:name=".FiltersActivity"
    android:label="@string/title_activity_filters"
    android:theme="@style/AppTheme.NoActionBar" >
        <intent-filter>
            <action android:name="me.theglassboard.vee.FiltersActivity" />

            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
</activity>
<activity
    android:name=".MainActivity"
    android:label="@string/title_activity_main"
    android:theme="@style/AppTheme.NoActionBar" >
        <intent-filter>
            <action android:name="me.theglassboard.vee.MainActivity" />

            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
</activity>

关于java - Android:startActivity() 适用于一个 Activity ,但不适用于另一个 Activity ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33857220/

相关文章:

java - 如何关闭另一个类的 Intent Activity

java - 在Java中打印带有下一行的字符串(斑马线模式)

c# - 如何在 monodroid 中删除用于编辑文本的 TextChangedListener

Android Studio 找不到 Boost header

java - Android keystore 签名问题

java - Spring MockMvc - 从 REST 获取 java.time.Instant

java - Spring MVC 教程不工作

java - 将 json 数组转换为 java 列表对象

android - 关于奇巧的通知

android - 启动画面图标未完全显示