我是Android编程的新手,最近,我的很多应用都遇到了这个错误。
这是运行时堆栈跟踪:
01/26 17:02:17: Launching WelcomeActivity
$ adb shell am start -n "com.example.android.smartswitch/com.example.android.smartswitch.WelcomeActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Client not ready yet..Connected to process 4258 on device genymotion-custom_phone___7_0_0___api_24___768x1280-192.168.160.101:5555
W/System: ClassLoader referenced unknown path: /data/app/com.example.android.smartswitch-2/lib/x86
I/InstantRun: Instant Run Runtime started. Android package is com.example.android.smartswitch, real application class is null.
W/System: ClassLoader referenced unknown path: /data/app/com.example.android.smartswitch-2/lib/x86
W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.smartswitch, PID: 4258
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.android.smartswitch/com.example.android.smartswitch.WelcomeActivity}: java.lang.IllegalStateException: Already attached
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: java.lang.IllegalStateException: Already attached
at android.support.v4.app.FragmentManagerImpl.attachController(FragmentManager.java:2815)
at android.support.v4.app.FragmentController.attachHost(FragmentController.java:104)
at android.support.v4.app.FragmentActivity.onCreate(FragmentActivity.java:317)
at android.support.v7.app.AppCompatActivity.onCreate(AppCompatActivity.java:88)
at com.example.android.smartswitch.WelcomeActivity.onCreate(WelcomeActivity.java:36)
at android.app.Activity.performCreate(Activity.java:6664)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Application terminated.
我正在尝试创建一个具有类似here的内置滑块的Android应用。这是MainActivity.java文件:
package com.example.android.smartswitch;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
int controllerButton = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// but this is for testing
slidingScreenLauncher prefManager = new slidingScreenLauncher(getApplicationContext());
prefManager.setFirstTimeLaunch(true);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
public void onButtonClick (View view) {
String message = null;
switch (view.getId()) {
case R.id.settingsButton:
Intent intent = new Intent(this, logging_screen.class);
startActivity(intent);
break;
case R.id.controllerButton:
if (controllerButton == 1) {
Button button1 = (Button) findViewById(R.id.controllerButton);
button1.setBackgroundColor(Color.GREEN); //Changing the background of the controllerButton.
button1.setText(getString(R.string.controller_off_text));
Button headerButton = (Button) findViewById(R.id.headerText);
headerButton.setBackgroundColor(Color.RED);
headerButton.setTextColor(Color.BLACK);
headerButton.setText(getString(R.string.banner_off_text));
controllerButton--; //Setting the button int to zero for next change.
}
if (controllerButton == 0) {
Button button1 = (Button) findViewById(R.id.controllerButton);
button1.setBackgroundColor(Color.BLUE); //Changing the background of the controllerButton.
button1.setText(getString(R.string.controller_on_text));
Button headerButton = (Button) findViewById(R.id.headerText);
headerButton.setBackgroundColor(Color.BLACK);
headerButton.setTextColor(Color.WHITE);
headerButton.setText(getString(R.string.banner_on_text));
controllerButton++; //Setting the button int to one for nex change. An altering loop.
}
break;
}
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.scheduleSettingsSideBar) {
//Intent to send the user to scheduleSettings Screen.
Intent intent = new Intent(this, WelcomeActivity.class);
startActivity(intent);
} else if (id == R.id.manualSettingsSideBar) {
} else if (id == R.id.tempSettingsSideBar) {
//Intent to send the user to tempSettings Screen.
Intent intent = new Intent(this, temp_screen.class);
startActivity(intent);
}
else if (id == R.id.randomDelaySideBar) {
Intent intent = new Intent(this, random_delay.class);
startActivity(intent);
} else if (id == R.id.humiditySettingsSideBar) {
Intent intent = new Intent(this, humidity_settings.class);
startActivity(intent);
} else if (id == R.id.loggingSideBar) {
//Intent to send the user to loggingSidebar.
Intent intent = new Intent(this, logging_screen.class);
startActivity(intent);
} else if (id ==R.id.generalSettingsSideBar) {
} else if (id == R.id.playSliderAgain) {
/* We normally won't show the welcome slider again in real app
// but this is for testing
slidingScreenLauncher prefManager = new slidingScreenLauncher(getApplicationContext());
// make first time launch TRUE
prefManager.setFirstTimeLaunch(true);
startActivity(new Intent(MainActivity.this, WelcomeActivity.class));
finish(); */
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
以下是应该显示introslider的WelcomActivity.java文件:
package com.example.android.smartswitch;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
public class WelcomeActivity extends AppCompatActivity {
private ViewPager viewPager;
private MyViewPagerAdapter myViewPagerAdapter;
private LinearLayout dotsLayout;
private TextView[] dots;
private int[] layouts;
private Button btnSkip, btnNext;
private slidingScreenLauncher prefManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
super.onCreate(savedInstanceState);
// Checking for first time launch - before calling setContentView()
prefManager = new slidingScreenLauncher(this);
if (!prefManager.isFirstTimeLaunch()) {
launchHomeScreen();
finish();
}
// Making notification bar transparent
if (Build.VERSION.SDK_INT >= 21) {
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
}
setContentView(R.layout.activity_welcome);
viewPager = (ViewPager) findViewById(R.id.view_pager);
dotsLayout = (LinearLayout) findViewById(R.id.layoutDots);
btnSkip = (Button) findViewById(R.id.btn_skip);
btnNext = (Button) findViewById(R.id.btn_next);
// layouts of all welcome sliders
// add few more layouts if you want
layouts = new int[]{
R.layout.welcome_slide1,
R.layout.welcome_slide2,
R.layout.welcome_slide3,
R.layout.welcome_slide4};
// adding bottom dots
addBottomDots(0);
// making notification bar transparent
changeStatusBarColor();
myViewPagerAdapter = new MyViewPagerAdapter();
viewPager.setAdapter(myViewPagerAdapter);
viewPager.addOnPageChangeListener(viewPagerPageChangeListener);
btnSkip.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
launchHomeScreen();
}
});
btnNext.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// checking for last page
// if last page home screen will be launched
int current = getItem(+1);
if (current < layouts.length) {
// move to next screen
viewPager.setCurrentItem(current);
} else {
launchHomeScreen();
}
}
});
}
private void addBottomDots(int currentPage) {
dots = new TextView[layouts.length];
int[] colorsActive = getResources().getIntArray(R.array.array_dot_active);
int[] colorsInactive = getResources().getIntArray(R.array.array_dot_inactive);
dotsLayout.removeAllViews();
for (int i = 0; i < dots.length; i++) {
dots[i] = new TextView(this);
dots[i].setText(Html.fromHtml("•"));
dots[i].setTextSize(35);
dots[i].setTextColor(colorsInactive[currentPage]);
dotsLayout.addView(dots[i]);
}
if (dots.length > 0)
dots[currentPage].setTextColor(colorsActive[currentPage]);
}
private int getItem(int i) {
return viewPager.getCurrentItem() + i;
}
private void launchHomeScreen() {
prefManager.setFirstTimeLaunch(false);
startActivity(new Intent(WelcomeActivity.this, MainActivity.class));
finish();
}
// viewpager change listener
ViewPager.OnPageChangeListener viewPagerPageChangeListener = new ViewPager.OnPageChangeListener() {
@Override
public void onPageSelected(int position) {
addBottomDots(position);
// changing the next button text 'NEXT' / 'GOT IT'
if (position == layouts.length - 1) {
// last page. make button text to GOT IT
btnNext.setText(getString(R.string.start));
btnSkip.setVisibility(View.GONE);
} else {
// still pages are left
btnNext.setText(getString(R.string.next));
btnSkip.setVisibility(View.VISIBLE);
}
}
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
@Override
public void onPageScrollStateChanged(int arg0) {
}
};
/**
* Making notification bar transparent
*/
private void changeStatusBarColor() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(Color.TRANSPARENT);
}
}
/**
* View pager adapter
*/
public class MyViewPagerAdapter extends PagerAdapter {
private LayoutInflater layoutInflater;
public MyViewPagerAdapter() {
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(layouts[position], container, false);
container.addView(view);
return view;
}
@Override
public int getCount() {
return layouts.length;
}
@Override
public boolean isViewFromObject(View view, Object obj) {
return view == obj;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
View view = (View) object;
container.removeView(view);
}
}
}
我单独创建和保存的共享首选项文件工作正常。主要问题在于WelcomeActivity.java文件。
最后,这是清单文件:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android.smartswitch">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
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>
<activity
android:name=".WelcomeActivity">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.PREFERENCE" />
</intent-filter>
</activity>
<activity
android:name=".temp_screen"
android:label="@string/title_activity_temp_screen"
android:theme="@style/AppTheme.NoActionBar" />
<activity
android:name=".logging_screen"
android:label="@string/title_activity_logging_screen"
android:theme="@style/AppTheme.NoActionBar" />
<activity
android:name=".humidity_settings"
android:label="@string/title_activity_humidity_settings"
android:theme="@style/AppTheme.NoActionBar" />
<activity
android:name=".random_delay"
android:label="@string/title_activity_random_delay"
android:theme="@style/AppTheme.NoActionBar" />
</application>
有人可以告诉我哪里出错了?此外,我不知道如何设置清单,以便在开始时显示IntroSlider,然后MainActivity开始(我也在考虑添加SplashScreen)
非常感谢任何帮助,如果没有这个,我甚至无法测试我的应用并改进它......
答案 0 :(得分:1)
删除两次书面super.onCreate(savedInstanceState);
和setContentView(R.layout.activity_welcome);
:
欢迎活动:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
//removed super.onCreate(savedInstanceState);
//removed setContentView(R.layout.activity_welcome);
答案 1 :(得分:1)
你是
super.onCreate(savedInstanceState);
`setContentView(R.layout.activity_welcome);`
在活动中使用两次请将其删除。
评论这些行
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
// super.onCreate(savedInstanceState);
// Checking for first time launch - before calling setContentView()
prefManager = new slidingScreenLauncher(this);
if (!prefManager.isFirstTimeLaunch()) {
launchHomeScreen();
finish();
}
// Making notification bar transparent
if (Build.VERSION.SDK_INT >= 21) {
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
}
// setContentView(R.layout.activity_welcome);