Android:startActivity()适用于一个活动但不适用于另一个活动

时间:2015-11-22 16:34:07

标签: java android

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

这样可行:

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

但这不是:

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

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

<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,正如我所提到的,并且我对主活动布局文件进行了一些小的xml布局更改尝试撤消,但这并没有解决问题。

完整清单:

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

MainActivity.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));
        }
    });
}

}

2 个答案:

答案 0 :(得分:0)

使用以下内容更改清单中的<activity>

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

答案 1 :(得分:-1)

尝试以下操作:

像这样引用你的按钮:

new-password

使用onClickListener

调用您的按钮
     mButton1 = (Button) findViewById(R.id.button_1);
     mButton2 = (Button) findViewById(R.id.button_2);

如果不起作用,请发送MainsActivity.class和StartScreenActivity的打印输出