【问题标题】:Android: startActivity() works for one activity but not anotherAndroid:startActivity() 适用于一项活动,但不适用于另一项活动
【发布时间】:2015-11-22 16:34:07
【问题描述】:

我正在开发的应用程序的一部分有两个按钮,我的问题是,当我调用 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));
        }
    });
}

}

【问题讨论】:

  • 发布您的 MainActivity.java 和完整清单
  • 尝试重启你的手机/模拟器。
  • 您的问题解决了吗?我也有这个

标签: java android


【解决方案1】:

在清单中更改您的&lt;activity&gt;

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

【讨论】:

  • 不幸的是,当我这样做时没有任何变化。
  • 为什么你的 MainActivity 扩展 FragmentActivity??...用 AppCompatActivity @KevinDoyle 改变它
  • 它扩展了 FragmentActivity 因为它包含片段,这是 Android Studio 生成的结构,所以我选择了它。在这里使用 AppCompatActivity 有什么特别的原因吗?将其更改为扩展 AppCompatActivity 也不能解决问题,我很害怕。谢谢你的帮助!
  • 要包含Fragment,可以使用AppCompatActivity,然后在framelayout中使用Fragment。
【解决方案2】:

尝试以下操作:

像这样引用你的按钮:

     mButton1 = (Button) findViewById(R.id.button_1);
     mButton2 = (Button) findViewById(R.id.button_2);

使用 onClickListener 调用您的按钮

   mButton1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
                   Intent button1 = new Intent(StartScreenActivity.this, FiltersActivity.class);
                   startActivity(button1);
        }
   }    

   mButton2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
                   Intent button2= new Intent(StartScreenActivity.this, MainActivity.class);
                   startActivity(button);
        }
   }    

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-13
    • 2015-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多