当在同一个onClickListener中声明2个意图时,应用程序崩溃

时间:2014-01-07 06:20:25

标签: android eclipse

我正在做一个IQtest应用程序。我需要从一个活动发送2个数据到2个不同的活动。但是当我通过单个onClickListener发送它们时,应用程序崩溃了。我在这里做错了什么?或者我可以发送数据而不用按钮点击?

这是AgeCalculation.java

package com.example.iqtest;
public class AgeCalculation extends Activity implements OnTouchListener
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_age_calculation);
    mDate = (EditText) findViewById(R.id.edDate);
    age = (EditText) findViewById(R.id.edAge);
    calage = (Button) findViewById(R.id.btnCalculateAge);
    go = (Button) findViewById(R.id.button1);
    category=(EditText) findViewById(R.id.category);
    final Calendar c = Calendar.getInstance();
    Year = c.get(Calendar.YEAR);
    Month = c.get(Calendar.MONTH);
    Day = c.get(Calendar.DAY_OF_MONTH);
    mDate.setOnTouchListener(this);


    calage.setOnClickListener(new Button.OnClickListener(){
        public void onClick(View v){
            Intent i = new Intent(AgeCalculation.this,ResultActivity.class);
            i.putExtra("ti",timetotake);
            startActivity(i);
            Calendar now=  Calendar.getInstance();
            Calendar calendar = Calendar.getInstance();

            calendar.set(Year, Month, Day);

            int years = now.get(Calendar.YEAR) - calendar.get(Calendar.YEAR);
            int months = now.get(Calendar.MONTH) - calendar.get(Calendar.MONTH);
            int days = now.get(Calendar.DAY_OF_MONTH) - calendar.get(Calendar.DAY_OF_MONTH);
            if (days < 0){
                months --;
                days +=now.getActualMaximum(Calendar.DAY_OF_MONTH);
            }
            if (months < 0){
                years --;
                months +=12;
            }
            String yearsold = years+" YEARS "+months+ " MONTHS "+days+" DAYS"+" "+"OLD";
            age.setText(yearsold);
            if(years>=0 && years<=10)
            {
                opt=0;
            }else if(years>=11 && years<=15)
            {
                opt=1;
            }else if(years>=16 && years<=30)
            {
                opt=2;
            }
            else if(years>=31 && years<=50)
            {
                opt=3;
            }else if(years>=51 && years<=120)
            {
                opt=4;
            }else
            {
                opt=5;
            }
            switch (opt) {
            case 0:
                start=0;
                temp=" KIDS";
                timetotake=480;
                break;
            case 1:
                start=20;
                temp=" CHILDREN";
                timetotake=480;
                break;
            case 2:
                start=40;
                temp="TEENAGERS";
                timetotake=540;
                break;
            case 3:
                start=60;
                temp="ADULTS";
                timetotake=540;
                break;
            case 4:
                start=80;
                temp="ELDERS";
                timetotake=600;
                break;
            case 5:
                temp="ALIENS!!";
                break;
            default:
                temp="ALIENS!!";
                break;
            }
            category.setText(temp);
            go.setText("GO"+" "+"TO"+" "+temp+" "+"IQTEST");
            }
    });

    go = (Button) findViewById(R.id.buttongo);
    go.setOnClickListener(new View.OnClickListener()        
    {
        public void onClick(View view)
        {
            Intent intent = new  /*Here Iam using two intents to send data to two different activities QuizActivity and result activity*/Intent(AgeCalculation.this,QuizActivity.class);
            intent.putExtra("start", start);
            startActivity(intent);
            Intent i = new Intent(AgeCalculation.this,ResultActivity.class);
            i.putExtra("ti",timetotake);
            startActivity(i);
        }


}); 
}

@Override
protected Dialog onCreateDialog(int id)
{
    switch (id) {

        case DATE_DIALOG_ID:
            return new DatePickerDialog(
                this, DateSetListener, Year, Month, Day);
    }
    return null;
}

private DatePickerDialog.OnDateSetListener DateSetListener =
    new DatePickerDialog.OnDateSetListener()
    {

    @Override
    public void onDateSet(DatePicker view, int year, int monthOfYear,
            int dayOfMonth) {
        Year = year;
        Month = monthOfYear;
        Day = dayOfMonth;
        String sdate = lp(Day + "", "0", 2)+ " " + montharray[Month] + " " + Year;
        mDate.setText(sdate);

    }

};

 private  String lp(String sc, String sp, int len) {
        String sr = sc;
        for (int i = sr.length(); i < len; i++) {
            sr = sp + sr;
        }
        return new String(sr);
    }

@Override
public boolean onTouch(View arg0, MotionEvent arg1) {

    showDialog(DATE_DIALOG_ID);
    return false;
}
}

这是QuizActivity.java

package com.example.iqtest;
public class QuizActivity extends Activity {
List<Question> quesList;
int score,qid,temp;
int secs;
Question currentQ;
TextView txtQuestion;
RadioButton rda, rdb, rdc,rdd,rde;
Button butNext,agecal;
private Button pause;
private TextView timerValue;
private long startTime = 0L;
private Handler customHandler = new Handler();
long timeInMilliseconds = 0L;
long timeSwapBuff = 0L;
long updatedTime = 0L;
@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_quiz);
    timerValue = (TextView) findViewById(R.id.textView2);
    startTime = SystemClock.uptimeMillis();
    customHandler.postDelayed(updateTimerThread, 0);

     pause = (Button) findViewById(R.id.pause);
     pause.setOnClickListener(new View.OnClickListener() {
         public void onClick(View view) {
            timeSwapBuff += timeInMilliseconds;
             customHandler.removeCallbacks(updateTimerThread);
              // or View.INVISIBLE depending on what you want to do
            pause.setVisibility(View.INVISIBLE);
           Intent i = new Intent(QuizActivity.this,Timeplease.class);
           startActivity(i); 
           finish();
         }
     });

    Bundle b = getIntent().getExtras(); 
    qid=b.getInt("start");
    temp=qid;
    agecal = (Button) findViewById(R.id.buttoncalage);
    agecal.setOnClickListener(new View.OnClickListener()        
    {
        public void onClick(View view) 
        {
            Intent i = new Intent(QuizActivity.this,AgeCalculation.class);
            startActivity(i); 
            finish();
        }

}); 
    DbHelper db=new DbHelper(this);
    quesList=db.getAllQuestions();
    currentQ=quesList.get(qid);
    txtQuestion=(TextView)findViewById(R.id.textView1);
    rda=(RadioButton)findViewById(R.id.radio0);
    rdb=(RadioButton)findViewById(R.id.radio1);
    rdc=(RadioButton)findViewById(R.id.radio2);
    rdd=(RadioButton)findViewById(R.id.radio3);
    rde=(RadioButton)findViewById(R.id.radio4);
    butNext=(Button)findViewById(R.id.button1);
    setQuestionView();
    butNext.setOnClickListener(new View.OnClickListener() {     
        @Override
        public void onClick(View v) {
            RadioGroup grp=(RadioGroup)findViewById(R.id.radioGroup1);
            RadioButton answer=(RadioButton)findViewById(grp.getCheckedRadioButtonId());
            if(currentQ.getanswer().equals(answer.getText()))
            {
                score++;
            }
            if(qid<(temp+20)){                  
                currentQ=quesList.get(qid);
                setQuestionView();
            }else{
                Intent intent = new Intent(QuizActivity.this, ResultActivity.class);
                Bundle b = new Bundle();
                b.putInt("score", score);
                b.putInt("time",secs);
                //Your score
                intent.putExtras(b); //Put your score to your next Intent
                startActivity(intent);
                finish();
            }
        }
    });
}
private void setQuestionView()
{
    txtQuestion.setText(currentQ.getquestion());
    rda.setText(currentQ.getopta());
    rdb.setText(currentQ.getoptb());
    rdc.setText(currentQ.getoptc());
    rdd.setText(currentQ.getoptd());
    rde.setText(currentQ.getopte());
    qid++;
}
private Runnable updateTimerThread = new Runnable() {
public void run() {
timeInMilliseconds = SystemClock.uptimeMillis() - startTime;
updatedTime = timeSwapBuff + timeInMilliseconds;
secs = (int) (updatedTime / 1000);
int mins = secs / 60;
secs = secs % 60;
int milliseconds = (int) (updatedTime % 1000);
timerValue.setText("" + mins + ":" + String.format("%02d", secs) + ":"+ String.format("%03d", milliseconds));customHandler.postDelayed(this, 0);
}
};

}

这是ResultActivity.java

package com.example.iqtest;
public class ResultActivity extends Activity {
 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_result);
        //get rating bar object

        //get text view
        TextView t=(TextView)findViewById(R.id.textResult);
        //get score
        Bundle b = getIntent().getExtras();
        int score= b.getInt("score");
        int timetaken= b.getInt("time");
        Bundle a = getIntent().getExtras();
        int timetobetaken= a.getInt("ti");
        int iqscore=score*160/20*timetobetaken/timetaken;
        //display score
       t.setText("YOUR SCORE IS"+ " "+ iqscore);
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.result, menu);
        return true;
    }
}

这是Timeplease.java

package com.example.iqtest;
public class Timeplease extends Activity {
Button back;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    context=this;
    setContentView(R.layout.activity_timeplease);
    addListenerOnButton();
}
public void addListenerOnButton()
{
    back = (Button) findViewById(R.id.buttonback);
    back.setOnClickListener(new View.OnClickListener()      
    {
        public void onClick(View view) 
        {
            Intent i = new Intent(context,QuizActivity.class);
            startActivity(i);
            finish();
        }

}); 
}
}

2 个答案:

答案 0 :(得分:0)

执行此行代码后,

Intent i = new Intent(AgeCalculation.this,ResultActivity.class);
i.putExtra("ti",timetotake);
startActivity(i);

ResultActivity得到渲染。您的AgeCalculation中的其他代码行不会被执行。因此,您在ResultActivity类中期望的值将为null。

这可能是崩溃的原因。

另外,检查logcat,它会告诉你导致崩溃的代码行。

答案 1 :(得分:0)

AgeCalculation活动中,您只传递Intent中的值,因此您只能获得使用Intent intent = getIntent();的值。您无法从Bundle获取值,因为您尚未在Bundle中添加值。

要获取Bundle的值,您可以使用Bundle b = getIntent().getExtras();从捆绑中获取值。

试试如下:

  Bundle b = getIntent().getExtras();
   if(b.containsKey("score") || b.containsKey("time"))
  {
    int score= b.getInt("score");
    int timetaken= b.getInt("time");
   }

     Intent intent = getIntent();
     int timetobetaken=intent.getIntExtra("ti",0);

在您的AgeCalculation课程中,您同时开始按下go按钮上的两项活动,这可能会导致问题,因为您将结果传递给两项活动。

同样在你的QuizActivity课程中,从意图中获取的值不是来自Bundle,如下所示:

  Intent b = getIntent(); 
  qid=b.getIntExtra("start",0);

<强>编辑:

timetotake活动中将public static变量设为AgeCalculation

 public static int timetotake;

然后在ResultActivity中访问它,如下所示:

 int timetobetaken= AgeCalculation.timetotake;