通过活动反击

时间:2014-01-29 13:51:33

标签: android broadcastreceiver counter

我在开发应用时遇到问题。 我在活动B上有一个按钮,它启动了活动C.我在活动A上有一个textView。我希望每次用户触摸活动B中的按钮时,用一个计数器将活动A的textView增加1。 有人告诉我,我可以使用BroadcastReceiver向活动A发送信息。我试图使用它,但是当我打开活动A时,应用程序崩溃了。 你能帮助我吗?

sendBroadcast(活动B):

public static String BROADCAST_ACTION = "com.example.appquiz.firstimagelogo.COUNTER";

public void sendBroadcast(View v){
        Intent broadcast = new Intent();
        broadcast.setAction(BROADCAST_ACTION);
        sendBroadcast(broadcast);
    }

BroadcastReceiver(活动A):

 //the whole code

package com.example.appquiz;

import android.os.Bundle;
import android.app.ActionBar;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.support.v4.app.NavUtils;
import android.annotation.TargetApi;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;

public class Levels extends Activity  {

     int counter;
    TextView txView ;

    public void sendMessage (View view) {
        Intent intent = new Intent(this, DisplayMessageActivity.class);
        startActivity(intent);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_levels);
        // Show the Up button in the action bar.
        setupActionBar();
        ActionBar actionBar = getActionBar();
        actionBar.setIcon(R.drawable.list);
        actionBar.setTitle("Levels");
        counter=0;
        registerReceiver(mReceive , new IntentFilter(
                FirstImageLogo.BROADCAST_ACTION));
     txView = (TextView)findViewById(R.id.counter1);

}


    private BroadcastReceiver mReceive = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            counter++;
            txView.setText(counter + "");
        }

    };


    @Override
    public void onBackPressed() {
        Intent intent = new Intent (this, MainActivity.class);
        startActivity(intent);
        return;
    }

    @Override
    public void onResume() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(FirstImageLogo.BROADCAST_ACTION);
        registerReceiver(mReceive, filter);
        super.onResume();
    }

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


    /**
     * Set up the {@link android.app.ActionBar}, if the API is available.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    private void setupActionBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            getActionBar().setDisplayHomeAsUpEnabled(true);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.levels, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case android.R.id.home:
            // This ID represents the Home or Up button. In the case of this
            // activity, the Up button is shown. Use NavUtils to allow users
            // to navigate up one level in the application structure. For
            // more details, see the Navigation pattern on Android Design:
            //
            // http://developer.android.com/design/patterns/navigation.html#up-vs-back
            //
            NavUtils.navigateUpFromSameTask(this);
            return true;
        case R.id.action_settings:
            Intent intent = new Intent (this, Settings.class);
            startActivity(intent);
        }
        return super.onOptionsItemSelected(item);
    }


}

清单(活动A):

//codes before
    <intent-filter>
    <action android:name="com.example.appquiz.firstimagelogo.COUNTER"></action>
    </intent-filter>

谢谢:)

编辑:当它崩溃时,这就是日志猫:

01-29 15:26:16.190: D/OpenGLRenderer(22554): Enabling debug mode 0
01-29 15:26:17.210: D/dalvikvm(22554): GC_FOR_ALLOC freed 110K, 1% free 17784K/17932K, paused 10ms, total 10ms
01-29 15:26:18.420: D/AndroidRuntime(22554): Shutting down VM
01-29 15:26:18.420: W/dalvikvm(22554): threadid=1: thread exiting with uncaught exception (group=0x41c22ba8)
01-29 15:26:18.430: E/AndroidRuntime(22554): FATAL EXCEPTION: main
01-29 15:26:18.430: E/AndroidRuntime(22554): Process: com.example.appquiz, PID: 22554
01-29 15:26:18.430: E/AndroidRuntime(22554): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.appquiz/com.example.appquiz.Levels}: java.lang.NullPointerException
01-29 15:26:18.430: E/AndroidRuntime(22554):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2121)
01-29 15:26:18.430: E/AndroidRuntime(22554):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
01-29 15:26:18.430: E/AndroidRuntime(22554):    at android.app.ActivityThread.access$800(ActivityThread.java:135)
01-29 15:26:18.430: E/AndroidRuntime(22554):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
01-29 15:26:18.430: E/AndroidRuntime(22554):    at android.os.Handler.dispatchMessage(Handler.java:102)
01-29 15:26:18.430: E/AndroidRuntime(22554):    at android.os.Looper.loop(Looper.java:136)
01-29 15:26:18.430: E/AndroidRuntime(22554):    at android.app.ActivityThread.main(ActivityThread.java:5017)
01-29 15:26:18.430: E/AndroidRuntime(22554):    at java.lang.reflect.Method.invokeNative(Native Method)
01-29 15:26:18.430: E/AndroidRuntime(22554):    at java.lang.reflect.Method.invoke(Method.java:515)
01-29 15:26:18.430: E/AndroidRuntime(22554):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
01-29 15:26:18.430: E/AndroidRuntime(22554):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
01-29 15:26:18.430: E/AndroidRuntime(22554):    at dalvik.system.NativeStart.main(Native Method)
01-29 15:26:18.430: E/AndroidRuntime(22554): Caused by: java.lang.NullPointerException
01-29 15:26:18.430: E/AndroidRuntime(22554):    at android.app.Activity.findViewById(Activity.java:1884)
01-29 15:26:18.430: E/AndroidRuntime(22554):    at com.example.appquiz.Levels.<init>(Levels.java:21)
01-29 15:26:18.430: E/AndroidRuntime(22554):    at java.lang.Class.newInstanceImpl(Native Method)
01-29 15:26:18.430: E/AndroidRuntime(22554):    at java.lang.Class.newInstance(Class.java:1208)
01-29 15:26:18.430: E/AndroidRuntime(22554):    at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
01-29 15:26:18.430: E/AndroidRuntime(22554):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2112)
01-29 15:26:18.430: E/AndroidRuntime(22554):    ... 11 more

2 个答案:

答案 0 :(得分:2)

好像你没有注册接收器...这是你注册的方式

registerReceiver(mReceive , new IntentFilter(
                ActivityA or whatever the name of the activity is.BROADCAST_ACTION));

答案 1 :(得分:1)

您可以使用SharedPreferences。每次按下按钮,增加计数器并写入首选项,然后在ActivityA中读取该值并设置TextView,例如:

  1. 按下按钮时:

    SharedPreferences prefs = getSharedPreferences("prefs", Context.MODE_PRIVATE);
    SharedPreferenes.Editor editor = prefs.edit();
    
    int counter = prefs.getInt("counter", 0);
    
    counter++;
    
    editor.putInt("counter", counter);
    editor.commit();
    
  2. 在ActivityA中,读取计数器的值并设置TextView:

    SharedPreferences prefs = getSharedPreferences("prefs", Context.MODE_PRIVATE);
    
    int counter = prefs.getInt("counter", 0);
    
    someTextView.setText("Counter is: " + counter);