【问题标题】:change activity codes to fragment codes将活动代码更改为片段代码
【发布时间】:2016-04-04 10:58:04
【问题描述】:

此活动运行良好。但我需要将 Activity 作为一个片段。我试图将活动更改为片段,但它不起作用....那么有人可以帮我改变吗??

import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.ResolveInfo;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.BatteryManager;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.google.analytics.tracking.android.GoogleAnalytics;
import com.google.analytics.tracking.android.Tracker;
import com.mobilemerit.batterychecker.App;
import com.mobilemerit.java.GetBatteryStats;


public class BatteryCheck extends Activity {

    private TextView bLevel, header, health, voltage, tech, temp,
    heath_tag,temp_tag,tech_tag,voltage_tag;
    private ProgressBar bProgress;
    private ImageButton cheakUsage;
    private int level;
    private Intent usageIntent;
    private ResolveInfo resolveInfo;
    private Typeface myTypeface,secondrayTypeFace;
    private Tracker tracker;
    private GoogleAnalytics gTracker;
    private ImageButton batteryTester;

    public static final String LEVEL="level";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.battery_check_new);

        /**
         * feeding the context of thw application 
         * So as to use this at various places
         * 
         * */
        new App(getApplicationContext());

        // Attaching the Font type with the Text Views
                myTypeface = Typeface.createFromAsset(getAssets(), "fonts/Franklin Gothic.otf");
                secondrayTypeFace=Typeface.createFromAsset(getAssets(),"fonts/GOTHIC.TTF" );
        /**
         * Google Analytic code
         */
        gTracker = GoogleAnalytics.getInstance(getApplicationContext());
        tracker = gTracker.getTracker("UA-41735784-1");

        // Finding the XML Views

        bLevel = (TextView) findViewById(R.id.blevel1);
        bProgress = (ProgressBar) findViewById(R.id.progressBar);
        cheakUsage = (ImageButton) findViewById(R.id.usage);
        header = (TextView) findViewById(R.id.header);
        tech = (TextView) findViewById(R.id.technology);
        temp = (TextView) findViewById(R.id.tempreture);
        voltage = (TextView) findViewById(R.id.voltage);
        health = (TextView) findViewById(R.id.health);




        /**find up the tags view(of stats textviews)  as well to set up the typeface */
        heath_tag=(TextView)this.findViewById(R.id.health_tag);
        tech_tag=(TextView)this.findViewById(R.id.technology_tag);
        temp_tag=(TextView)this.findViewById(R.id.temp_tag);
        voltage_tag=(TextView)this.findViewById(R.id.voltage_tag);

        heath_tag.setTypeface(secondrayTypeFace);
        tech_tag.setTypeface(secondrayTypeFace);
        temp_tag.setTypeface(secondrayTypeFace);
        voltage_tag.setTypeface(secondrayTypeFace);
        /** Code for Google Admob */



        bLevel.setTypeface(myTypeface);
        header.setTypeface(myTypeface);
        // register the Broadcast Receiver
        this.registerReceiver(this.batteryInfoReceiver, new IntentFilter(
                Intent.ACTION_BATTERY_CHANGED));
        // Setting up the Intent for the Power Usage details
        usageIntent = new Intent(Intent.ACTION_POWER_USAGE_SUMMARY);
        // Check it for presence
        resolveInfo = getPackageManager().resolveActivity(usageIntent, 0);

        if (resolveInfo == null) {
            Toast.makeText(this, "Not Support!", Toast.LENGTH_LONG).show();
            cheakUsage.setEnabled(false);
        } else {
            cheakUsage.setEnabled(true);
        }

        // Setting up the functionality of the Button Clicks
        cheakUsage.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                startActivity(usageIntent);

            }
        });

    }

    private BroadcastReceiver batteryInfoReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
            setUpStats(intent);
            // Toast.makeText(getBaseContext(),
            // ""+intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE,-1),Toast.LENGTH_SHORT).show();
            new ShowProgressClass().execute();
        }
    };

    public void setUpStats(Intent intent) {
        GetBatteryStats stats = new GetBatteryStats(intent);
        health.setText("" + stats.getBatteryHealth());
        tech.setText("" + stats.getBatteryTechnology());
        temp.setText("" + stats.getBatteryTempreture());
        voltage.setText("" + stats.getBatteryVoltage());
        //Setting up typefaces for the stats 
        health.setTypeface(secondrayTypeFace);
        tech.setTypeface(secondrayTypeFace);
        temp.setTypeface(secondrayTypeFace);
        voltage.setTypeface(secondrayTypeFace);

        /**Save current voltage and level to calculate the Remaining time on Battery*/

        SharedPreferences prefs=this.getSharedPreferences(LEVEL, Context.MODE_PRIVATE);
        prefs.edit().putString("level",""+level);
        prefs.edit().putString("voltage",stats.getBatteryVoltage());


    }


    // For Upadating progress bar After loading
    class ShowProgressClass extends AsyncTask<Void, Integer, Void> {

        @Override
        protected Void doInBackground(Void... params) {

            for (int i = 0; i < level; i++) {
                publishProgress(1);
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            // TODO Auto-generated method stub
            return null;
        }

        @Override
        protected void onPreExecute() {         
            bProgress.setMax(100);
            bProgress.setProgress(0);

            // TODO Auto-generated method stub

        }
        @Override
        protected void onProgressUpdate(Integer... values) {
            bProgress.incrementProgressBy(values[0]);
            bLevel.setText(" " + bProgress.getProgress() + "%");
            // TODO Auto-generated method stub
        }

    }

    @Override
    public boolean onKeyDown(int keycode, KeyEvent event) {
        if (keycode == KeyEvent.KEYCODE_BACK) {

            AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);

            alertDialog.setTitle("Alert");

            // Setting Dialog Message
            alertDialog.setMessage("Are you sure you want to quit?");
            // Setting Positive "Yes" Button
            alertDialog.setPositiveButton("YES",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            onDestroy();
                        }
                    });
            // Setting Negative "NO" Button
            alertDialog.setNegativeButton("NO",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            // Write your code here to invoke NO event
                            dialog.cancel();
                        }
                    });
            // Showing Alert Message
            alertDialog.show();
        }
        return super.onKeyDown(keycode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        android.os.Process.killProcess(android.os.Process.myPid());
    }

}

我尝试自己将代码转换为片段,代码如下: 转换后我得到了什么:

package com.raihanbd.easyrambooster;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.ResolveInfo;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.BatteryManager;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.google.analytics.tracking.android.GoogleAnalytics;
import com.google.analytics.tracking.android.Tracker;
import com.mobilemerit.batterychecker.App;
import com.mobilemerit.java.GetBatteryStats;


public class BatteryCheck extends Fragment implements OnClickListener {

    private TextView bLevel, header, health, voltage, tech, temp,
    heath_tag,temp_tag,tech_tag,voltage_tag;
    private ProgressBar bProgress;
    private ImageButton cheakUsage;
    private int level;
    private Intent usageIntent;
    private ResolveInfo resolveInfo;
    private Typeface myTypeface,secondrayTypeFace;
    private Tracker tracker;
    private GoogleAnalytics gTracker;
    private ImageButton batteryTester;

    public static final String LEVEL="level";



    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.battery_check_new, container, false);



        /**
         * feeding the context of thw application 
         * So as to use this at various places
         * 
         * */
        new App(getActivity().getApplicationContext());

        // Attaching the Font type with the Text Views
            //  myTypeface = Typeface.createFromAsset(getAssets(), "fonts/Franklin Gothic.otf");
            //  secondrayTypeFace=Typeface.createFromAsset(getAssets(),"fonts/GOTHIC.TTF" );
        /**
         * Google Analytic code
         */
        gTracker = GoogleAnalytics.getInstance(getActivity().getApplicationContext());
        tracker = gTracker.getTracker("UA-41735784-1");

        // Finding the XML Views

        bLevel = (TextView) getView().findViewById(R.id.blevel1);
        bProgress = (ProgressBar) getView().findViewById(R.id.progressBar);
        cheakUsage = (ImageButton) getView().findViewById(R.id.usage);
        header = (TextView) getView().findViewById(R.id.header);
        tech = (TextView) getView().findViewById(R.id.technology);
        temp = (TextView) getView().findViewById(R.id.tempreture);
        voltage = (TextView) getView().findViewById(R.id.voltage);
        health = (TextView) getView().findViewById(R.id.health);




        /**find up the tags view(of stats textviews)  as well to set up the typeface */
        heath_tag=(TextView)this.getView().findViewById(R.id.health_tag);
        tech_tag=(TextView)this.getView().findViewById(R.id.technology_tag);
        temp_tag=(TextView)this.getView().findViewById(R.id.temp_tag);
        voltage_tag=(TextView)this.getView().findViewById(R.id.voltage_tag);

        heath_tag.setTypeface(secondrayTypeFace);
        tech_tag.setTypeface(secondrayTypeFace);
        temp_tag.setTypeface(secondrayTypeFace);
        voltage_tag.setTypeface(secondrayTypeFace);
        /** Code for Google Admob */



        bLevel.setTypeface(myTypeface);
        header.setTypeface(myTypeface);
        // register the Broadcast Receiver
        this.getActivity ().registerReceiver(this.batteryInfoReceiver, new IntentFilter(
                Intent.ACTION_BATTERY_CHANGED));
        // Setting up the Intent for the Power Usage details
        usageIntent = new Intent(Intent.ACTION_POWER_USAGE_SUMMARY);
        // Check it for presence
        resolveInfo =  getActivity ().getPackageManager().resolveActivity(usageIntent, 0);

        if (resolveInfo == null) {
            //Toast.makeText.(this, "Not Support!", Toast.LENGTH_LONG).show();
            cheakUsage.setEnabled(false);
        } else {
            cheakUsage.setEnabled(true);
        }

        // Setting up the functionality of the Button Clicks
        cheakUsage.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                startActivity(usageIntent);

            }
        });
        return root;

    }

    private BroadcastReceiver batteryInfoReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
            setUpStats(intent);
            // Toast.makeText(getBaseContext(),
            // ""+intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE,-1),Toast.LENGTH_SHORT).show();
            new ShowProgressClass().execute();
        }
    };

    public void setUpStats(Intent intent) {
        GetBatteryStats stats = new GetBatteryStats(intent);
        health.setText("" + stats.getBatteryHealth());
        tech.setText("" + stats.getBatteryTechnology());
        temp.setText("" + stats.getBatteryTempreture());
        voltage.setText("" + stats.getBatteryVoltage());
        //Setting up typefaces for the stats 
        health.setTypeface(secondrayTypeFace);
        tech.setTypeface(secondrayTypeFace);
        temp.setTypeface(secondrayTypeFace);
        voltage.setTypeface(secondrayTypeFace);

        /**Save current voltage and level to calculate the Remaining time on Battery*/

        SharedPreferences prefs=this.getActivity().getSharedPreferences(LEVEL, Context.MODE_PRIVATE);
        prefs.edit().putString("level",""+level);
        prefs.edit().putString("voltage",stats.getBatteryVoltage());


    }


    // For Upadating progress bar After loading
    class ShowProgressClass extends AsyncTask<Void, Integer, Void> {

        @Override
        protected Void doInBackground(Void... params) {

            for (int i = 0; i < level; i++) {
                publishProgress(1);
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            // TODO Auto-generated method stub
            return null;
        }

        @Override
        protected void onPreExecute() {         
            bProgress.setMax(100);
            bProgress.setProgress(0);

            // TODO Auto-generated method stub

        }
        @Override
        protected void onProgressUpdate(Integer... values) {
            bProgress.incrementProgressBy(values[0]);
            bLevel.setText(" " + bProgress.getProgress() + "%");
            // TODO Auto-generated method stub
        }

    }


    @Override
    public void onClick(View arg0) {
        // TODO Auto-generated method stub

    }
}

但是当我尝试运行它时,我得到以下错误:

    04-04 15:27:26.299: W/dalvikvm(9929): threadid=1: thread exiting with uncaught exception (group=0x40f259a8)
04-04 15:27:26.299: E/test(9929): Exception
04-04 15:27:26.310: E/AndroidRuntime(9929): FATAL EXCEPTION: main
04-04 15:27:26.310: E/AndroidRuntime(9929): java.lang.NullPointerException
04-04 15:27:26.310: E/AndroidRuntime(9929):     at com.raihanbd.easyrambooster.BatteryCheck.onCreateView(BatteryCheck.java:76)
04-04 15:27:26.310: E/AndroidRuntime(9929):     at android.support.v4.app.Fragment.performCreateView(Fragment.java:1500)
04-04 15:27:26.310: E/AndroidRuntime(9929):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:927)
04-04 15:27:26.310: E/AndroidRuntime(9929):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
04-04 15:27:26.310: E/AndroidRuntime(9929):     at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
04-04 15:27:26.310: E/AndroidRuntime(9929):     at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1467)
04-04 15:27:26.310: E/AndroidRuntime(9929):     at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:472)
04-04 15:27:26.310: E/AndroidRuntime(9929):     at android.support.v4.app.FragmentStatePagerAdapter.finishUpdate(FragmentStatePagerAdapter.java:163)
04-04 15:27:26.310: E/AndroidRuntime(9929):     at android.support.v4.view.ViewPager.populate(ViewPager.java:1068)
04-04 15:27:26.310: E/AndroidRuntime(9929):     at android.support.v4.view.ViewPager.populate(ViewPager.java:914)
04-04 15:27:26.310: E/AndroidRuntime(9929):     at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1436)
04-04 15:27:26.310: E/AndroidRuntime(9929):     at android.view.View.measure(View.java:15698)
04-04 15:27:26.310: E/AndroidRuntime(9929):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4918)
04-04 15:27:26.310: E/AndroidRuntime(9929):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
04-04 15:27:26.310: E/AndroidRuntime(9929):     at android.view.View.measure(View.java:15698)
04-04 15:27:26.310: E/AndroidRuntime(9929):     at android.widget.LinearLayout.measureVertical(LinearLayout.java:850)
04-04 15:27:26.310: E/AndroidRuntime(9929):     at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
04-04 15:27:26.310: E/AndroidRuntime(9929):     at android.view.View.measure(View.java:15698)
04-04 15:27:26.310: E/AndroidRuntime(9929):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4918)
04-04 15:27:26.310: E/AndroidRuntime(9929):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
04-04 15:27:26.310: E/AndroidRuntime(9929):     at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2197)
04-04 15:27:26.310: E/AndroidRuntime(9929):     at android.view.View.measure(View.java:15698)
04-04 15:27:26.310: E/AndroidRuntime(9929):     at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2171)
04-04 15:27:26.310: E/AndroidRuntime(9929):     at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1255)
04-04 15:27:26.310: E/AndroidRuntime(9929):     at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1449)
04-04 15:27:26.310: E/AndroidRuntime(9929):     at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1145)
04-04 15:27:26.310: E/AndroidRuntime(9929):     at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4907)
04-04 15:27:26.310: E/AndroidRuntime(9929):     at android.view.Choreographer$CallbackRecord.run(Choreographer.java:776)
04-04 15:27:26.310: E/AndroidRuntime(9929):     at android.view.Choreographer.doCallbacks(Choreographer.java:579)
04-04 15:27:26.310: E/AndroidRuntime(9929):     at android.view.Choreographer.doFrame(Choreographer.java:548)
04-04 15:27:26.310: E/AndroidRuntime(9929):     at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:762)
04-04 15:27:26.310: E/AndroidRuntime(9929):     at android.os.Handler.handleCallback(Handler.java:725)
04-04 15:27:26.310: E/AndroidRuntime(9929):     at android.os.Handler.dispatchMessage(Handler.java:92)
04-04 15:27:26.310: E/AndroidRuntime(9929):     at android.os.Looper.loop(Looper.java:153)
04-04 15:27:26.310: E/AndroidRuntime(9929):     at android.app.ActivityThread.main(ActivityThread.java:5299)
04-04 15:27:26.310: E/AndroidRuntime(9929):     at java.lang.reflect.Method.invokeNative(Native Method)
04-04 15:27:26.310: E/AndroidRuntime(9929):     at java.lang.reflect.Method.invoke(Method.java:511)
04-04 15:27:26.310: E/AndroidRuntime(9929):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
04-04 15:27:26.310: E/AndroidRuntime(9929):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
04-04 15:27:26.310: E/AndroidRuntime(9929):     at dalvik.system.NativeStart.main(Native Method)

这个活动是关于我刚刚找到的手机电池信息... 我要编辑它,但首先我需要它作为片段。

【问题讨论】:

  • 您的错误信息。说在第 76 行有一个空指针 - 你的“getView() 方法是错误的。用“root”替换它,因为这是你的基本视图

标签: android android-activity fragment


【解决方案1】:

两个发布的答案都是正确的,但我认为最好的做法是在onViewCreated() 内调用findViewById

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        bLevel = (TextView) view.findViewById(R.id.blevel1);
        //your other views and stuff
    }

【讨论】:

    【解决方案2】:

    使用root.findViewById() 代替getView().findViewById()。 因为您将 root 定义为 oncreateview() 方法返回的视图。

    【讨论】:

      【解决方案3】:

      在 android.widget 中使用 root 代替 getView()

          bLevel = (TextView) root.findViewById(R.id.blevel1);
          bProgress = (ProgressBar) root.findViewById(R.id.progressBar);
          cheakUsage = (ImageButton) root.findViewById(R.id.usage);
          header = (TextView) root.findViewById(R.id.header);
          tech = (TextView) root.findViewById(R.id.technology);
          temp = (TextView) root.findViewById(R.id.tempreture);
          voltage = (TextView) root.findViewById(R.id.voltage);
          health = (TextView) root.findViewById(R.id.health);
      

      【讨论】:

        【解决方案4】:

        因为你在onCreateView方法中没有将视图返回给fragment,所以在onCreateView方法中运行getView方法时,会引发NullPointerException。 您应该使用 root.findViewById,而不是使用 getView().findViewById。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-09-22
          • 1970-01-01
          • 2023-04-02
          • 2010-12-04
          • 1970-01-01
          相关资源
          最近更新 更多