开发者

Runtime error while switching between activities in Android

I got a开发者_运维知识库 runtime error when I press the button that should change the activity:

package com.example.LocationTracker;

import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button;

public class LocationTracker extends Activity{ /** Called when the activity is first created. */

Button btn_Tracker;
Button btn_Display_Map;
Context context;


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    context = getApplicationContext();
    btn_Tracker = (Button)findViewById(R.id.btn_Tracker);


    btn_Tracker.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
        //setContentView(R.layout.trackeractivity);
        Intent myIntent1 = new Intent(view.getContext(),   TrackerActivity.class);
        context.startActivity(myIntent1);
        }});
}

class TrackerActivity extends Activity {

//Your member variable declaration here

// Called when the activity is first created.
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.trackeractivity);
}
}

I added everything right in the maniefest file

<activity android:name=".TrackerActivity" android:label="@string/app_name"/>

<activity android:name=".DisplayMapActivity" android:label="@string/app_name"/>

</application>

Any idea?


I think TrackerActivity needs to be public, which means it will need to be in its own file as well.


You shouldn't be using getApplicationContext() to start activities. Every activity is a context, so having a member instance of Context should not be necessary. Try re-writing the onClick method of your OnClickListener like this

public void onClick(View view) {
    Intent myIntent1 = new Intent(LocationTracker.this, TrackerActivity.class);
    LocationTracker.this.startActivity(myIntent1);
    }});

Also, refer to this documentation for when to use the application context.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜