应用程序在使用动态选项卡时崩溃

时间:2014-03-04 13:47:09

标签: java android

我正在尝试创建和使用动态标签但是如果我使用切换,添加或删除标签ONCE应用程序正常工作,但一旦我尝试选择第二个操作应用程序崩溃。我知道问题在于标签代码,因为应用程序在标签部分

之前工作正常

这是我的MainActivity.java:

package com.example.notepadxl;

import java.io.*;


import android.os.*;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.*;
import android.app.ActionBar.Tab;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
//import android.content.pm.PackageManager;
import android.graphics.Typeface;
import android.view.*;
import android.widget.*;

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@SuppressLint("WorldReadableFiles")
public class MainActivity extends Activity {

    Typeface tf=Typeface.SERIF;
    int sty=Typeface.NORMAL;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }


     public void onAddTab() {
            final ActionBar bar = getActionBar();
            final int tabCount = bar.getTabCount();
            final String text = "Tab " + tabCount;
            bar.addTab(bar.newTab()
                    .setText(text)
                    .setTabListener(new TabListener(new TabContentFragment(text))));
        }
     public void onRemoveTab() {
            final ActionBar bar = getActionBar();
            if(bar.getTabCount() > 0)
                bar.removeTabAt(bar.getTabCount() - 1);
        }
     public void onToggleTabs() {
            final ActionBar bar = getActionBar();
            if (bar.getNavigationMode() == ActionBar.NAVIGATION_MODE_TABS) {
                bar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
                bar.setDisplayOptions(ActionBar.DISPLAY_SHOW_TITLE, ActionBar.DISPLAY_SHOW_TITLE);
            } else {
                bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
                bar.setDisplayOptions(0, ActionBar.DISPLAY_SHOW_TITLE);
            }
        }
     public void onRemoveAllTabs(View v) {
            getActionBar().removeAllTabs();
        }
     private class TabListener implements ActionBar.TabListener {
            private TabContentFragment mFragment;
            public TabListener(TabContentFragment fragment) {
                mFragment = fragment;
            }
            public void onTabSelected(Tab tab, FragmentTransaction ft) {

                ft.add(R.id.fragment_content, mFragment, mFragment.getText());
            }
            public void onTabUnselected(Tab tab, FragmentTransaction ft) {
                ft.remove(mFragment);
            }
            public void onTabReselected(Tab tab, FragmentTransaction ft) {
                Toast.makeText(MainActivity.this, "Reselected!", Toast.LENGTH_SHORT).show();
            }
        }
        @SuppressLint("ValidFragment")
        private class TabContentFragment extends Fragment {
            private String mText;
            public TabContentFragment(String text) {
                mText = text;
            }
            public String getText() {
                return mText;
            }
            @Override
            public View onCreateView(LayoutInflater inflater, ViewGroup container,
                    Bundle savedInstanceState) {
                View fragView = inflater.inflate(R.layout.activity_main, container, false);
                TextView text = (TextView) fragView.findViewById(R.id.text);
                text.setText(mText);
                return fragView;
            }
        }


    public void ChangeFont(View view) {
        Button b = (Button) findViewById(R.id.Font);
        PopupMenu popupMenu = new PopupMenu(MainActivity.this, b);
        popupMenu.getMenuInflater().inflate(R.menu.popupmenu,
                popupMenu.getMenu());

        popupMenu
                .setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    EditText text = (EditText) findViewById(R.id.TextBox);

                    @Override
                    public boolean onMenuItemClick(MenuItem item) {
                        switch (item.getItemId()) {
                        case R.id.menu1: {
                            tf=Typeface.SANS_SERIF;
                            text.setTypeface(tf,sty);
                            break;
                        }
                        case R.id.menu2: {
                            tf=Typeface.SERIF;
                            text.setTypeface(tf,sty);
                            break;
                        }
                        case R.id.menu3: {
                            tf=Typeface.MONOSPACE;
                            text.setTypeface(tf,sty);
                            break;
                        }
                        case R.id.menu4: {
                            tf = Typeface.createFromAsset(getAssets(),
                                    "Fonts/HandmadeTypewriter.ttf");
                            text.setTypeface(tf,sty);
                            break;
                        }
                        case R.id.menu5: {
                            tf = Typeface.createFromAsset(getAssets(),
                                    "Fonts/verdana.ttf");
                            text.setTypeface(tf,sty);
                            break;
                        }
                        case R.id.menu6: {
                            tf = Typeface.createFromAsset(getAssets(),
                                    "Fonts/times.ttf");
                            text.setTypeface(tf,sty);
                            break;
                        }
                        case R.id.menu7: {
                            tf = Typeface.createFromAsset(getAssets(),
                                    "Fonts/babe bamboo.ttf");
                            text.setTypeface(tf,sty);
                            break;
                        }
                        case R.id.menu8: {
                            tf = Typeface.createFromAsset(getAssets(),
                                    "Fonts/O_Connor.ttf");
                            text.setTypeface(tf,sty);
                            break;
                        }
                        case R.id.menu9: {
                            tf = Typeface.createFromAsset(getAssets(),
                                    "Fonts/OBLIVIOUSFONT.TTF");
                            text.setTypeface(tf,sty);
                            break;
                        }
                        default: {
                            break;
                        }
                        }
                        return true;
                    }
                });

        popupMenu.show();
    }

    public void ChangeStyle(View view) {
        Button b = (Button) findViewById(R.id.Style);
        PopupMenu popupMenu = new PopupMenu(MainActivity.this, b);
        popupMenu.getMenuInflater().inflate(R.menu.stylemenu,
                popupMenu.getMenu());

        popupMenu
                .setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    EditText text = (EditText) findViewById(R.id.TextBox);

                    @Override
                    public boolean onMenuItemClick(MenuItem item) {
                        switch (item.getItemId()) {
                        case R.id.type1: {
                            sty=Typeface.ITALIC;
                            text.setTypeface(tf, sty);
                            break;
                        }
                        case R.id.type2: {
                            sty=Typeface.BOLD;
                            text.setTypeface(tf, sty);
                            break;
                        }
                        case R.id.type3: {
                            sty=Typeface.BOLD_ITALIC;
                            text.setTypeface(tf, sty);
                            break;
                        }
                        case R.id.type4: {
                            sty=Typeface.NORMAL;
                            text.setTypeface(tf, sty);
                            break;
                        }
                        default: {
                            break;
                        }
                        }
                        return true;
                    }
                });

        popupMenu.show();
    }

    public void ChangeSize(View view) {
        Button b = (Button) findViewById(R.id.Size);
        PopupMenu popupMenu = new PopupMenu(MainActivity.this, b);
        popupMenu.getMenuInflater().inflate(R.menu.sizemenu,
                popupMenu.getMenu());

        popupMenu
                .setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    EditText text = (EditText) findViewById(R.id.TextBox);

                    @Override
                    public boolean onMenuItemClick(MenuItem item) {
                        switch (item.getItemId()) {
                        case R.id.size1: {
                            text.setTextSize(14);
                            break;
                        }
                        case R.id.size2: {
                            text.setTextSize(16);
                            break;
                        }
                        case R.id.size3: {
                            text.setTextSize(18);
                            break;
                        }
                        case R.id.size4: {
                            text.setTextSize(20);
                            break;
                        }
                        case R.id.size5: {
                            text.setTextSize(22);
                            break;
                        }
                        case R.id.size6: {
                            text.setTextSize(24);
                            break;
                        }
                        case R.id.size7: {
                            text.setTextSize(26);
                            break;
                        }
                        case R.id.size8: {
                            text.setTextSize(28);
                            break;
                        }
                        default: {
                            break;
                        }
                        }
                        return true;
                    }
                });

        popupMenu.show();
    }

    public synchronized void onActivityResult(final int requestCode,
            int resultCode, final Intent data) {
        EditText text = (EditText) findViewById(R.id.TextBox);
        if (resultCode == Activity.RESULT_OK) {
            if(requestCode==0){
            String filePath = data.getStringExtra(FileDialog.RESULT_PATH);
            File file = new File(filePath);
            StringBuilder info = new StringBuilder();
            try {
                BufferedReader br = new BufferedReader(new FileReader(file));
                String line;
                while ((line = br.readLine()) != null) {
                    info.append(line);
                    info.append('\n');
                }
                text.setText(info);
                br.close();

            } catch (IOException e) {
                // You'll need to add proper error handling here
            }
            }
            else if(requestCode==1){
                String filePath = data.getStringExtra(FileDialog.RESULT_PATH);
                File file = new File(filePath);

                FileOutputStream fos;


                byte[] data1 = text.getText().toString().getBytes();


                try {

                    fos = new FileOutputStream(file);
                    fos.write(data1);
                    fos.flush();
                    fos.close();
                } catch (FileNotFoundException e) {
                    // handle exception
                } catch (IOException e) {

                    // handle exception

                }
            }
        } else if (resultCode == Activity.RESULT_CANCELED) {
            text.setText("file not selected");
        }

    }

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

    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {

        case R.id.item1:
            Intent intent = new Intent(getBaseContext(), FileDialog.class);
            intent.putExtra(FileDialog.START_PATH, "/sdcard");
            intent.putExtra(FileDialog.CAN_SELECT_DIR, true);
            startActivityForResult(intent, 0);
            break;
        case R.id.item2:
            Intent intent1 = new Intent(getBaseContext(), FileDialog.class);
            intent1.putExtra(FileDialog.START_PATH, "/sdcard");
            intent1.putExtra(FileDialog.CAN_SELECT_DIR, true);
            startActivityForResult(intent1, 1);
            break;
        case R.id.item3:
            Context context = this;
            AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
            alertDialog.setTitle("NEW");
            alertDialog.setMessage("Do you wish to save the file");
            alertDialog.setPositiveButton("OK",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            Intent intent = new Intent(getBaseContext(),
                                    FileDialog.class);
                            intent.putExtra(FileDialog.START_PATH, "/sdcard");
                            intent.putExtra(FileDialog.CAN_SELECT_DIR, true);
                            startActivityForResult(intent, 1);
                            EditText text = (EditText) findViewById(R.id.TextBox);
                            text.setText("");
                        }
                    });
            alertDialog.setNegativeButton("No",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            EditText text = (EditText) findViewById(R.id.TextBox);
                            text.setText("");
                        }
                    });
            alertDialog.show();

            Toast.makeText(getApplicationContext(), "New file",
                    Toast.LENGTH_SHORT).show();
            break;
        case R.id.item4:
            onAddTab();
            break;
        case R.id.item5:
            onRemoveTab();
            break;
        case R.id.item6:
            onToggleTabs();
            break;
        default:
            break;
        }
        return super.onOptionsItemSelected(item);
    }
}

这是logcat:

03-04 18:55:19.229: E/AndroidRuntime(20619): FATAL EXCEPTION: main
03-04 18:55:19.229: E/AndroidRuntime(20619): java.lang.NullPointerException
03-04 18:55:19.229: E/AndroidRuntime(20619):    at com.example.notepadxl.MainActivity$TabContentFragment.onCreateView(MainActivity.java:178)
03-04 18:55:19.229: E/AndroidRuntime(20619):    at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:828)
03-04 18:55:19.229: E/AndroidRuntime(20619):    at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1032)
03-04 18:55:19.229: E/AndroidRuntime(20619):    at android.app.BackStackRecord.run(BackStackRecord.java:622)
03-04 18:55:19.229: E/AndroidRuntime(20619):    at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1382)
03-04 18:55:19.229: E/AndroidRuntime(20619):    at android.app.FragmentManagerImpl$1.run(FragmentManager.java:426)
03-04 18:55:19.229: E/AndroidRuntime(20619):    at android.os.Handler.handleCallback(Handler.java:605)
03-04 18:55:19.229: E/AndroidRuntime(20619):    at android.os.Handler.dispatchMessage(Handler.java:92)
03-04 18:55:19.229: E/AndroidRuntime(20619):    at android.os.Looper.loop(Looper.java:137)
03-04 18:55:19.229: E/AndroidRuntime(20619):    at android.app.ActivityThread.main(ActivityThread.java:4441)
03-04 18:55:19.229: E/AndroidRuntime(20619):    at java.lang.reflect.Method.invokeNative(Native Method)
03-04 18:55:19.229: E/AndroidRuntime(20619):    at java.lang.reflect.Method.invoke(Method.java:511)
03-04 18:55:19.229: E/AndroidRuntime(20619):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
03-04 18:55:19.229: E/AndroidRuntime(20619):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
03-04 18:55:19.229: E/AndroidRuntime(20619):    at dalvik.system.NativeStart.main(Native Method)

2 个答案:

答案 0 :(得分:0)

堆栈跟踪说onCreateView()中有一个NPE:

public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View fragView = inflater.inflate(R.layout.activity_main, container, false);
    TextView text = (TextView) fragView.findViewById(R.id.text);
    text.setText(mText);
    return fragView;
}

您的activity_main布局似乎不包含ID为text的视图。

答案 1 :(得分:0)

请检查activity_main是否包含ID为text的元素。 显然它不存在。