应用中的Android运行时错误

时间:2014-05-31 12:40:28

标签: java android

所以我试图获取实时板球得分,但我在启动文件中收到以下错误。请有人帮帮我

05-31 08:35:56.833: D/AndroidRuntime(1089): Shutting down VM
    05-31 08:35:56.833: W/dalvikvm(1089): threadid=1: thread exiting with uncaught exception (group=0x414c4700)
    05-31 08:35:56.843: E/AndroidRuntime(1089): FATAL EXCEPTION: main
    05-31 08:35:56.843: E/AndroidRuntime(1089): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.cricketscores/com.example.cricketscores.Launching}: java.lang.NullPointerException
    05-31 08:35:56.843: E/AndroidRuntime(1089):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
    05-31 08:35:56.843: E/AndroidRuntime(1089):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
    05-31 08:35:56.843: E/AndroidRuntime(1089):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
    05-31 08:35:56.843: E/AndroidRuntime(1089):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
    05-31 08:35:56.843: E/AndroidRuntime(1089):     at android.os.Handler.dispatchMessage(Handler.java:99)
    05-31 08:35:56.843: E/AndroidRuntime(1089):     at android.os.Looper.loop(Looper.java:137)
    05-31 08:35:56.843: E/AndroidRuntime(1089):     at android.app.ActivityThread.main(ActivityThread.java:5103)
    05-31 08:35:56.843: E/AndroidRuntime(1089):     at java.lang.reflect.Method.invokeNative(Native Method)
    05-31 08:35:56.843: E/AndroidRuntime(1089):     at java.lang.reflect.Method.invoke(Method.java:525)
    05-31 08:35:56.843: E/AndroidRuntime(1089):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
    05-31 08:35:56.843: E/AndroidRuntime(1089):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
    05-31 08:35:56.843: E/AndroidRuntime(1089):     at dalvik.system.NativeStart.main(Native Method)
    05-31 08:35:56.843: E/AndroidRuntime(1089): Caused by: java.lang.NullPointerException
    05-31 08:35:56.843: E/AndroidRuntime(1089):     at com.example.cricketscores.Launching.onCreate(Launching.java:52)
    05-31 08:35:56.843: E/AndroidRuntime(1089):     at android.app.Activity.performCreate(Activity.java:5133)
    05-31 08:35:56.843: E/AndroidRuntime(1089):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
    05-31 08:35:56.843: E/AndroidRuntime(1089):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
    05-31 08:35:56.843: E/AndroidRuntime(1089):     ... 11 more

这是代码

public class Launching extends Activity {

        private List<Match> matches = new ArrayList<Match>();
        private MatchesReceiver receiver;
        private IntentFilter filter;
        private MatchListState oldState;
        private MatchAdapter matchAdapter;
        private long lastUpdate;

        @Override
        public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                CricScoreApplication.getInstance().setMatchListState(MatchListState.LOADING);
                startService(new Intent(this, MatchUpdateService.class));
                this.receiver = new MatchesReceiver();
                this.filter = new IntentFilter(GenericProperties.INTENT_ML_UPDATE);
                this.matchAdapter = new MatchAdapter(this);
                this.oldState = MatchListState.LOADING;
                RunningInfo.clearSession(getApplicationContext());
        }

        @Override
        public void onStart() {
                super.onStart();
        }

        @Override
        public void onResume() {
                super.onResume();
                updateScreen();
                registerReceiver(receiver, filter);
        }

        private void updateScreen() {
                Log.i(GenericProperties.TAG, "updating screen");

                MatchListState state = CricScoreApplication.getInstance()
                                .getMatchListState();

                Resources resources = getResources(); 

                if (MatchListState.LOADING.equals(state)) {
                        setContentView(R.layout.launching_loading);
                        Log.i(GenericProperties.TAG, "updating screen - loading");
                } else if (MatchListState.LOADED.equals(state)) { 
                        showMatches();
                        Log.i(GenericProperties.TAG, "updating screen - show matches");
                } else if (MatchListState.NODATA.equals(state)) {
                        showErrorScreen(resources.getString(R.string.error_title_nodata), resources.getString(R.string.error_msg_nodata));
                        Log.i(GenericProperties.TAG, "updating screen - show error - nodata");
                } else if (MatchListState.NOMATCH.equals(state)) {
                        showErrorScreen(resources.getString(R.string.error_title_nomatch), resources.getString(R.string.error_msg_nomatch));
                        Log.i(GenericProperties.TAG, "updating screen - show error - nomatch");
                } else if (MatchListState.NOTSUPPORTED.equals(state)) {
                        showErrorScreen(resources.getString(R.string.error_title_nosupport), resources.getString(R.string.error_msg_nosupport));
                        Log.i(GenericProperties.TAG, "updating screen - show error - nosupport");
                } else if (MatchListState.APPERROR.equals(state)){
                        showErrorScreen(resources.getString(R.string.error_title_apperror), resources.getString(R.string.error_msg_apperror));
                        Log.i(GenericProperties.TAG, "updating screen - show error - apperror");
                }
                oldState = state;
                Log.i(GenericProperties.TAG, "updating screen ended");

        }

        @Override
        public void onPause() {
                super.onPause();
                unregisterReceiver(receiver);
        }

        @Override
        public void onStop() {
                super.onStop();

        }

        @Override
        public void onDestroy() {
                super.onDestroy();
                stopService(new Intent(this, ScoreUpdateService.class));
        }

        private class MatchesReceiver extends BroadcastReceiver {
                @Override
                public void onReceive(Context context, Intent intent) {
                        long start = System.currentTimeMillis();
                        if(GenericProperties.INTENT_ML_UPDATE.equals(intent.getAction())){
                                updateScreen();
                        }
                        long time = System.currentTimeMillis() - start;
                        Log.i(GenericProperties.TAG, "On Receive Time Taken : " + time
                                        + " ms");
                }
        }

        private void showErrorScreen(String title, String message) {
                if(MatchListState.LOADING.equals(oldState) || MatchListState.LOADED.equals(oldState)){
                        setContentView(R.layout.launching_error);
                }
                Log.v(GenericProperties.TAG, title + " "+ message);
                TextView tilteTextView = (TextView)findViewById(R.id.title);
                tilteTextView.setText(title);
                TextView messageTextView = (TextView)findViewById(R.id.message_body);
                messageTextView.setText(message);

                Log.v(GenericProperties.TAG, " "+ messageTextView.getText());
                Log.v(GenericProperties.TAG, " "+ messageTextView.getTextSize());

        }

        private void showMatches() {

                if(!oldState.equals(MatchListState.LOADED)){
                        setContentView(R.layout.matchlist);
                        final ListView l1 = (ListView) findViewById(R.id.ListMatches);
                        //l1.set
                        l1.setAdapter(matchAdapter);
                        l1.setOnItemClickListener(new OnItemClickListener() {
                                public void onItemClick(AdapterView<?> arg0, View view,
                                                int position, long id) {
                                        int mid = ((Match) l1.getItemAtPosition(position)).getMatchId();
                                        openLiveScore(mid);
                                        openScoreUpdateService(mid);

                                }
                        });     
                }

                long newUpdateTime = CricScoreApplication.getInstance().getMatchListUpdateTime();
                if(newUpdateTime != this.lastUpdate){
                        CricScoreDBAdapter adapter = new CricScoreDBAdapter(
                                        getApplicationContext());
                        adapter.open();
                        this.matches =  adapter.getMatches(); 
                        adapter.close();
                        this.matchAdapter.notifyDataSetChanged();
                        if(this.lastUpdate!=0){
                                Toast.makeText(getApplicationContext(), R.string.toast_update, Toast.LENGTH_SHORT).show();      
                        }

                        this.lastUpdate = newUpdateTime; 

                }

        }

        private void openScoreUpdateService(int mid) {
                Intent serviceIntent = new Intent(
                                GenericProperties.INTENT_START_UPDATE);
                serviceIntent.putExtra("matchId", mid);
                startService(serviceIntent);
        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
                MenuInflater inflater = getMenuInflater();
                inflater.inflate(R.menu.launching_menu, menu);
                return true;
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
                switch (item.getItemId()) {
                case R.id.hide:
                        moveTaskToBack(false);
                        return true;
                case R.id.exit:
                        //alertAndClose();
                        Launching.this.finish();
                        return true;
                case R.id.feedback:
                        Launching.this.feedback();
                        return true;
                default:
                        return super.onOptionsItemSelected(item);
                }
        }

        private void feedback() {
                Intent i = new Intent(Intent.ACTION_SEND);
                i.setType("text/plain");
                i.putExtra(Intent.EXTRA_EMAIL  , new String[]{"spriyan@mychoize.com"});
                i.putExtra(Intent.EXTRA_SUBJECT, "MyChoize CricScore: Feedback");
                i.putExtra(Intent.EXTRA_TEXT   , "Please provide your feedback for improvement of CricScore app here.");
                i.setType("message/rfc822");
                startActivity(Intent.createChooser(i, "Send Feedback"));
        }

        private void openLiveScore(int id) {
                Intent myIntent = new Intent(this, LiveScore.class);
                myIntent.putExtra(GenericProperties.EXTRA_MATCHID, id);
                startActivity(myIntent);
        }

        public void alertAndClose() {
                Resources resources = getResources();
                String str = resources.getString(R.string.confirm_exit);
                String exit = resources.getString(R.string.exit);
                String cancel = resources.getString(R.string.cancel);
                String hide = resources.getString(R.string.hide);
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setMessage(str);
                builder.setCancelable(true);
                builder.setNeutralButton(cancel, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                                dialog.cancel();
                        }
                });
                builder.setPositiveButton(exit, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                                Launching.this.finish();
                        }
                });
                builder.setNegativeButton(hide, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                                moveTaskToBack(false);
                        }
                });
                AlertDialog alert = builder.create();
                alert.show();
        }

        @Override
        public void onBackPressed() {
                alertAndClose();
                return;
        }

        private class MatchAdapter extends BaseAdapter {
                private LayoutInflater mInflater;

                public MatchAdapter(Context context) {
                        mInflater = LayoutInflater.from(context);

                }

                public int getCount() {
                        return Launching.this.matches.size();
                }

                public Object getItem(int position) {
                        return matches.get(position);
                }

                public long getItemId(int position) {
                        return position;
                }

                public View getView(int position, View convertView, ViewGroup parent) {
                        ViewHolder holder;
                        if (convertView == null) {
                                convertView = mInflater.inflate(R.layout.matchview, null);
                                holder = new ViewHolder();
                                holder.text = (TextView) convertView.findViewById(R.id.TeamOne);
                                holder.text2 = (TextView) convertView
                                                .findViewById(R.id.TeamTwo);
                                convertView.setTag(holder);
                        } else {
                                holder = (ViewHolder) convertView.getTag();
                        }
                        try {
                                Match match = matches.get(position);
                                holder.text.setText(match.getTeamOne());
                                holder.text2.setText(match.getTeamTwo());
                        } catch (ArrayIndexOutOfBoundsException e) {

                        }

                        return convertView;
                }

                class ViewHolder {
                        TextView text;
                        TextView text2;
                }
        }
}

*更新*

CricScoreApplication.java

public class CricScoreApplication extends Application {

        private static CricScoreApplication singleton;

        private MatchListState matchListState;
        private long matchListUpdateTime;

        private ScoreUpdateState scoreUpdateState;
        private long scoreUpdateTime;

        private boolean liveOn;

        public static CricScoreApplication getInstance(){
                return singleton;
        }

        @Override
        public void onCreate() {
                super.onCreate();
                singleton = this;
                this.matchListState = MatchListState.LOADING;
                this.matchListUpdateTime = 0;
        }

        public MatchListState getMatchListState() {
                return matchListState;
        }

        public void setMatchListState(MatchListState matchListState) {
                this.matchListState = matchListState;
        }

        public long getMatchListUpdateTime() {
                return matchListUpdateTime;
        }

        public void setMatchListUpdateTime(long matchListUpdateTime) {
                this.matchListUpdateTime = matchListUpdateTime;
        }

        public ScoreUpdateState getScoreUpdateState() {
                return scoreUpdateState;
        }

        public void setScoreUpdateState(ScoreUpdateState scoreUpdateState) {
                this.scoreUpdateState = scoreUpdateState;
                this.scoreUpdateTime = System.currentTimeMillis();
        }

        public long getScoreUpdateTime() {
                return scoreUpdateTime;
        }

        public void clearScoreUpdateState(){
                this.scoreUpdateState = null;
                this.scoreUpdateTime = 0L;
        }

        public boolean isLiveOn() {
                //System.out.println("getting value "+liveOn);
                return liveOn;
        }

        public void setLiveOn(boolean liveOn) {
                //System.out.println("setting value " +liveOn);
                this.liveOn = liveOn;
        }



}

清单

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.cricketscores"

    android:versionCode="7"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="7"
        android:targetSdkVersion="16" />
        <uses-permission android:name="android.permission.INTERNET" />
        <uses-permission android:name="android.permission.SEND_SMS" />
        <uses-permission android:name="android.permission.READ_CONTACTS" />



        <application android:icon="@drawable/icon" android:label="@string/app_name" android:allowBackup="true" >
                        <activity android:name=".Launching" android:multiprocess="false"  android:launchMode="singleTask">
                        <intent-filter>
                                <action android:name="android.intent.action.MAIN" />
                                <category android:name="android.intent.category.LAUNCHER" />
                        </intent-filter>
                </activity>

                 <activity android:name=".Info" android:label="@string/title_info"></activity>
        <activity android:name=".activity.SmsFeature" android:label="@string/title_sms_feature"></activity>
        <activity android:name=".LiveScore" android:label="@string/title_live_score" android:launchMode="singleTask"></activity>
        <activity android:name=".activity.UserPreference" android:label="@string/title_user_preference"></activity>

        <service android:name=".MatchUpdateService" android:enabled="true"></service>
        <service android:name=".ScoreUpdateService" android:enabled="true">
                <intent-filter>
               <action android:name="com.example.cricketscores.START_UPDATE" />
                <action android:name="com.example.cricketscores.STOP_UPDATE" />
                <action android:name="com.example.cricketscores.UPDATE_VALUES" />
            </intent-filter>
        </service>
        </application>



</manifest>

感谢您的帮助

1 个答案:

答案 0 :(得分:2)

扩展Application类时,不需要使用经典的单例方法。相反,如果您的清单设置正确,您可以:

@Override
        public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                //notice the change
                CricScoreApplication app = (CricScoreApplication)getApplication();
                app.setMatchListState(MatchListState.LOADING);

                startService(new Intent(this, MatchUpdateService.class));
                this.receiver = new MatchesReceiver();
                this.filter = new IntentFilter(GenericProperties.INTENT_ML_UPDATE);
                this.matchAdapter = new MatchAdapter(this);
                this.oldState = MatchListState.LOADING;
                RunningInfo.clearSession(getApplicationContext());
        }

为此,您需要将此类指向要在基础Application类上使用的类。这在清单中完成:

<application ... android:name="com.example.cricketscores.CricScoreApplication" >

P.S :如果您真的想使用getInstance()方法,它应该如下所示:

public static CricScoreApplication getInstance(Context ctx){
                return (CricScoreApplication)(ctx.getApplication());
        }