2017-03-17 78 views
-1

我试图在主屏幕上使用五个按钮构建应用程序。按下每个按钮时会弹出一个新的活动。无法启动活动(java.lang.IllegalStateException:已连接)

当我打第二个按钮会显示错误:

**java.lang.RuntimeException: Unable to start activity ComponentInfo{debuggers.os_project/debuggers.os_project.SJF}: java.lang.IllegalStateException: Already attached** 

第一个按钮是工作的罚款。直到我只编码了两个按钮。

我main_activity.java是:

package debuggers.os_project; 

import android.content.Intent; 
import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.view.View; 
import android.widget.Button; 

public class MainActivity extends AppCompatActivity { 

private static Button fcfs; 
private static Button sjf; 

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

    fcfs = (Button)findViewById(R.id.fcfs); 
    sjf = (Button) findViewById(R.id.sjf); 
    fcfs.setOnClickListener(
      new Button.OnClickListener(){ 
       @Override 
       public void onClick(View v) { 
        Intent intent = new Intent(v.getContext(), FCFS.class); 
        startActivity(intent); 
       } 
      } 
    ); 
} 

public void onSJF(View view){ 
    Intent intent = new Intent(view.getContext(),SJF.class); 
    startActivity(intent); 
} 
} 
+0

为您的变量提供有意义的名称将极大地帮助您阅读代码... –

+0

分享SJF活动的代码。我认为问题在于此。这可能有所帮助:http://stackoverflow.com/questions/35384888/java-lang-illegalstateexception-already-attached –

+0

@PavanPatil你是对的,问题出在SJF的活动。谢谢你的帮助。 –

回答

0

这里:

public void onSJF(View view){ 
    Intent intent = new Intent(MainActivity.this, SJF.class); 
    startActivity(intent); 
} 

要开始一个新的活动,传递当前活动类作为第一个参数,接下来的活动课作为第二Intent新实例的参数!

请尝试看看这是否工作;

0

上点击监听器应该是这样的:

fcfs = (Button)findViewById(R.id.fcfs); 
fcfs.setOnClickListener(new View.OnClickListener() { 
    @Override 
    public void onClick(View v) { 
     Intent intent = new Intent(MainActivity.this, FCFS.class); 
     startActivity(intent); 
}); 

而且你没有使用你的方法。 你可以建立一个方法,并且可以使用所有的按钮:

public void method_for_intent (Class your_class){ 
    Intent intent = new Intent(MainActivity.this, your_class); 
    startActivity(intent); 
} 

而在你的onCreate,应该是这样的最后:

Button fcfs = (Button)findViewById(R.id.fcfs); 
Button sjf = (Button) findViewById(R.id.sjf); 
fcfs.setOnClickListener(new View.OnClickListener() { 
    @Override 
    public void onClick(View v) { 
     method_for_intent(FCFS.class) 
    }); 
sjf.setOnClickListener(new View.OnClickListener() { 
    @Override 
    public void onClick(View v) { 
     method_for_intent(SJF.class) 
    }); 

你可以称之为oncreate多次在新活动。 IllegalStateException (Already attached) when opening NFC reader app

(你可以把你的点击收听到方法太) 还没有测试代码。 如果我有什么不对,会让我感到高兴。