java - 使用 Android 2.2 时 TTS 抛出 NPE,但在 4.0 版本上运行良好

标签 java android text-to-speech

我的应用程序在 4.0 版本中运行良好,但如果我在 2.2 版本中使用,它会显示我的应用程序强制关闭。 在检查 logcat 时,它显示 tts 函数中的错误,TTS 抛出 NPE。我也初始化了 TTS 初始化。较低版本只会出现问题。

这是 myactivity.java

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list_item2);

        mDbHelper = new GinfyDbAdapter(this);
        share = (Button)findViewById(R.id.btnget);
        btnadd1 = (Button)findViewById(R.id.btnadd);
        lv = getListView();
        share.setOnClickListener(new OnClickListener()
        {

            @Override
            public void onClick(View v) {

                StringBuilder result = new StringBuilder();
                if(count>0)
                {
                for(int i=0;i<count;i++)

                {Log.i("checked content Inside on click of share ",""+aa.get(i));
                    if(mCheckStates.get(i)==true)
                    {
                         result.append("Title:");
                         result.append(bb.get(i));

                         result.append("\n");
                         result.append("Content:");
                         result.append(aa.get(i));
                         result.append("\n");

                    }

                }
                }
               // }
                Log.i("result is",""+result);
                if(result!=null)
                {
                 showAlertView(result.toString());
                }
                else
                {
                    Log.i("result is","null");
                }

            }

        });

        btnadd1.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                createProject();


            }

        });

        mDbHelper.open();
        fillData();
        registerForContextMenu(getListView());


    }


    @SuppressLint("NewApi")
    @SuppressWarnings("deprecation")
    private void fillData() {
        mDbHelper.open();      
        Cursor projectsCursor = mDbHelper.fetchAllProjects();

      count = projectsCursor.getCount();

        Log.i(".......fill data method logging now ......",""+count);
        if (projectsCursor.moveToFirst()) {
              do {

                  int col1 = projectsCursor.getColumnIndex("title");
                  String title = projectsCursor.getString(col1 );         
                  bb.add(title);              

                  int col2 = projectsCursor.getColumnIndex("content");
                  String content = projectsCursor.getString(col2 );         
                  aa.add(content);
                  Log.i("...........................All COntent",content);
              } while (projectsCursor.moveToNext());

        }
        //startManagingCursor(projectsCursor);


        // Create an array to specify the fields we want to display in the list (only TITLE)
        String[] from = new String[]{GinfyDbAdapter.CATEGORY_COLUMN_TITLE,GinfyDbAdapter.CATEGORY_COLUMN_CONTENT,GinfyDbAdapter.CATEGORY_COLUMN_DATE};

        int[] to = new int[]{R.id.text22,R.id.text11,R.id.date};
        dataAdapter = new CustomAdapter (YourPrayerActivity .this, R.layout.row2, projectsCursor, from, to);
        setListAdapter(dataAdapter);



        EditText myFilter = (EditText) findViewById(R.id.myFilter);
        myFilter.addTextChangedListener(new TextWatcher() {

            public void afterTextChanged(Editable s) {
            }

            public void beforeTextChanged(CharSequence s, int start,
                    int count, int after) {
            }

            public void onTextChanged(CharSequence s, int start,
                    int before, int count) {
                dataAdapter.getFilter().filter(s.toString());
            }
        });

        dataAdapter.setFilterQueryProvider(new FilterQueryProvider() {
            public Cursor runQuery(CharSequence constraint) {
                return mDbHelper.fetchProjectByName(constraint.toString());
            }
        });



        tts = new TextToSpeech(this, this);
        final ListView lv = getListView();
        txtText = (TextView) findViewById(R.id.text11);
        lv.setTextFilterEnabled(true);



    }

    @Override
    public void onDestroy() {
        // Don't forget to shutdown tts!
        if (tts != null) {
            tts.stop();
            tts.shutdown();
        }
        super.onDestroy();
    }

    public void onInit(int status) {

        if (status == TextToSpeech.SUCCESS) {

            int result = tts.setLanguage(Locale.US);

            if (result == TextToSpeech.LANG_MISSING_DATA
                    || result == TextToSpeech.LANG_NOT_SUPPORTED) {
                Log.e("TTS", "This Language is not supported");
            } else {
                //btnaudioprayer.setEnabled(true);
                speakOut();
            }

        } else {
            Log.e("TTS", "Initilization Failed!");
        }

    }



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

    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        Intent newActivity = new Intent(YourPrayerActivity.this,AndroidTabLayoutActivity1.class);
        startActivity(newActivity);
        return super.onMenuItemSelected(featureId, item);
    }*/


    private void createProject() {
        Intent i = new Intent(this, AddyourprayerActivity.class);
        startActivityForResult(i, ACTIVITY_CREATE);  
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        fillData();
    }


    private void speakOut() {

        // String text = txtText.getText().toString();
        // String text = "Android speech";

        tts.speak(typed, TextToSpeech.QUEUE_FLUSH, null);
    }

    class CustomAdapter extends SimpleCursorAdapter implements CompoundButton.OnCheckedChangeListener {

        private LayoutInflater mInflater;
        private ListView lv;




        @SuppressWarnings("deprecation")
        public CustomAdapter(Context context, int layout, Cursor c, String[] from, int[] to)
                 {
            super(context, layout, c, from, to);
            mInflater= LayoutInflater.from(context);
            mCheckStates = new SparseBooleanArray(c.getCount());



            // TODO Auto-generated constructor stub
        }


         @Override
            public void bindView(View view, Context context, final Cursor cursor){
                int row_id = cursor.getColumnIndex("_id");  //Your row id (might need to replace)
                TextView tv = (TextView) view.findViewById(R.id.text22);
                final TextView tv1 = (TextView) view.findViewById(R.id.text11);
                TextView tv2 = (TextView) view.findViewById(R.id.date);
                CheckBox cb = (CheckBox) view.findViewById(R.id.checkbox);
                int col1 = cursor.getColumnIndex("title");
                final String title = cursor.getString(col1 );
                int col2 = cursor.getColumnIndex("content");
                final String content = cursor.getString(col2 );
                int col3 = cursor.getColumnIndex("date");
                final String date = cursor.getString(col3);
                cb.setTag(cursor.getPosition());
                cb.setChecked(mCheckStates.get(cursor.getPosition(), false));
                cb.setOnCheckedChangeListener(this);
              //  TextView tv2 = (TextView) view.findViewById(R.id.text3);
                //cursor.getColumnName(1)
                tv.setText( title);
                tv1.setText( content);
                tv2.setText(date);
                //tv2.setText( ""+cursor.getColumnIndex(GinfyDbAdapter.CATEGORY_COLUMN_COUNT));
             //   String[] from = new String[]{GinfyDbAdapter.CATEGORY_COLUMN_TITLE, GinfyDbAdapter.CATEGORY_COLUMN_CONTENT, GinfyDbAdapter.CATEGORY_COLUMN_COUNT}
                ImageButton button = (ImageButton) view.findViewById(R.id.sms1);
                button.setOnClickListener(new OnClickListener(){
                    @Override
                    public void onClick(View v){
                        StringBuffer sb2 = new StringBuffer();
                    sb2.append("Title:");
                        sb2.append(Html.fromHtml(title));
                        sb2.append(",Content:");
                        sb2.append(Html.fromHtml(content));
                        sb2.append("\n");
                        String strContactList1 = (sb2.toString().trim());
                        sendsmsdata(strContactList1);
                    }
                });

                ImageButton button1 = (ImageButton) view.findViewById(R.id.mail1);
                button1.setOnClickListener(new OnClickListener(){
                    @Override
                    public void onClick(View v){
                        StringBuffer sb3 = new StringBuffer();
                    sb3.append("Title:");
                        sb3.append(Html.fromHtml(title));
                        sb3.append(",Content:");
                        sb3.append(Html.fromHtml(content));
                        sb3.append("\n");
                        String strContactList2 = (sb3.toString().trim());
                        sendmaildata(strContactList2);
                    }
                });

                ImageButton button2 = (ImageButton) view.findViewById(R.id.btnaudioprayer1);
                button2.setOnClickListener(new OnClickListener(){
                    @Override
                    public void onClick(View v){
                        //ADD STUFF HERE you know which row is clicked. and which button
                        typed = content;
                        speakOut();
                    }
                });



            }

这里我粘贴了使用 android 2.2 时的 logcat 错误

09-24 12:51:45.074: E/AndroidRuntime(324): FATAL EXCEPTION: main
09-24 12:51:45.074: E/AndroidRuntime(324): java.lang.NullPointerException: println needs a message
09-24 12:51:45.074: E/AndroidRuntime(324):  at android.util.Log.println_native(Native Method)
09-24 12:51:45.074: E/AndroidRuntime(324):  at android.util.Log.i(Log.java:143)
09-24 12:51:45.074: E/AndroidRuntime(324):  at android.speech.tts.TextToSpeech.speak(TextToSpeech.java:720)
09-24 12:51:45.074: E/AndroidRuntime(324):  at com.example.tesing.YourPrayerActivity.speakOut(YourPrayerActivity.java:258)
09-24 12:51:45.074: E/AndroidRuntime(324):  at com.example.tesing.YourPrayerActivity.onInit(YourPrayerActivity.java:212)
09-24 12:51:45.074: E/AndroidRuntime(324):  at android.speech.tts.TextToSpeech$1.onServiceConnected(TextToSpeech.java:451)
09-24 12:51:45.074: E/AndroidRuntime(324):  at android.app.ActivityThread$PackageInfo$ServiceDispatcher.doConnected(ActivityThread.java:1247)
09-24 12:51:45.074: E/AndroidRuntime(324):  at android.app.ActivityThread$PackageInfo$ServiceDispatcher$RunConnection.run(ActivityThread.java:1264)
09-24 12:51:45.074: E/AndroidRuntime(324):  at android.os.Handler.handleCallback(Handler.java:587)
09-24 12:51:45.074: E/AndroidRuntime(324):  at android.os.Handler.dispatchMessage(Handler.java:92)
09-24 12:51:45.074: E/AndroidRuntime(324):  at android.os.Looper.loop(Looper.java:123)
09-24 12:51:45.074: E/AndroidRuntime(324):  at android.app.ActivityThread.main(ActivityThread.java:4627)
09-24 12:51:45.074: E/AndroidRuntime(324):  at java.lang.reflect.Method.invokeNative(Native Method)
09-24 12:51:45.074: E/AndroidRuntime(324):  at java.lang.reflect.Method.invoke(Method.java:521)
09-24 12:51:45.074: E/AndroidRuntime(324):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
09-24 12:51:45.074: E/AndroidRuntime(324):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
09-24 12:51:45.074: E/AndroidRuntime(324):  at dalvik.system.NativeStart.main(Native Method)

它显示这些行中的错误 说出();

最佳答案

尝试初始化字符串变量。

我认为在你的情况下typed是变量。

无论你在哪里初始化它,都以这种方式初始化:

public String typed = "" ;

它会起作用的。试一试。

关于java - 使用 Android 2.2 时 TTS 抛出 NPE,但在 4.0 版本上运行良好,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18975372/

相关文章:

java - 在Java中对3维数组进行排序

Java 无法解析的日期

java - Android Searchview 使用 ListView 过滤项目点击错误

android - 如何隐藏标题 Android

flutter - 询问 android 的麦克风权限

java - switch 的替代方案——替换字符

java - Android 纹理映射 - PNG 文件的映射不正确

android - 如何处理BackupHelper和SQLites附加文件

delphi - 在哪里可以找到delphi的“文字转语音”组件?

c# - System.speech 在数字上说 "area code"