有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java文本到语音功能在我的Listview中不起作用

在我的listview中,我有文本和一个按钮作为文本到语音按钮。单击按钮后,音频不会出现。SSS单击“文字到语音转换”按钮后,音频不工作

我的活动。爪哇

  @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list_item); 

        mDbHelper=new GinfyDbAdapter(MainActivity.this);
        mDbHelper.open();
         Cursor projectsCursor = mDbHelper.fetchAllProjects();
         if(projectsCursor.getCount()>0)
           {
           fillData(projectsCursor);

           Log.i("filling", "...");
           }
           else
           {
                new GetDataAsyncTask().execute();
           }


        btnGetSelected = (Button) findViewById(R.id.btnget);
        btnGetSelected.setOnClickListener(this);

        //praycount.setOnClickListener(this);
        //initView();

}





    /*private void initView(){
        // show progress dialog
        dialog = ProgressDialog.show(this, "", "Loading...");
        String url = "http://www.ginfy.com/api/v1/posts.json";
        FetchDataTask task = new FetchDataTask(this);
        task.execute(url);


    }   */



    private class GetDataAsyncTask extends AsyncTask<Void, Void, Void> {
        private ProgressDialog Dialog = new ProgressDialog(MainActivity.this);

        protected void onPreExecute() {
            Dialog.setMessage("Loading.....");
            Dialog.show();
        }
        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);

            /*mDbHelper=new GinfyDbAdapter(MainActivity.this); // initialize mDbHelper before.
            mDbHelper.open();
            Cursor projectsCursor = mDbHelper.fetchAllProjects();
            if(projectsCursor.getCount()>0)
            {
            fillData(projectsCursor);
            }*/
            for(int i=0; i<ID.size(); i++){
                mDbHelper=new GinfyDbAdapter(MainActivity.this);
                 mDbHelper.open();
                 mDbHelper.saveCategoryRecord(new Category(ID.get(i),TITLE.get(i),CONTENT.get(i),COUNT.get(i)));
                 }
            Dialog.dismiss();
        }

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

            getData();
            return null;
        }

    }

    public void getData() {
          try
          {
      HttpClient httpclient = new DefaultHttpClient();
      httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
      HttpGet request = new HttpGet("http://ginfynetwork-s9k4z6piks.elasticbeanstalk.com/api/v1/posts.json");
      // HttpGet request = new HttpGet("http://gdata.youtube.com/feeds/api/users/mbbangalore/uploads?v=2&alt=jsonc");     

      HttpResponse response = httpclient.execute(request);
      HttpEntity resEntity = response.getEntity();
      String _response=EntityUtils.toString(resEntity); // content will be consume only once
       Log.i("................",_response);
      httpclient.getConnectionManager().shutdown();
      JSONObject jsonObject = new JSONObject(_response);
      JSONArray contacts = jsonObject.getJSONArray("post");//(url);
          for(int i = 0; i < contacts.length(); i++){
              JSONObject c = contacts.getJSONObject(i);
              String id = c.getString("id");
              String title = c.getString("title");
              String  content = c.getString("content");
              String  count = c.getString("count");
              //mDbHelper=new GinfyDbAdapter(MainActivity.this);
              //mDbHelper.open();
              //mDbHelper.saveCategoryRecord(new Category(id,title,content,count));
              ID.add(id);
              TITLE.add(title);
              CONTENT.add(content);
              COUNT.add(count);
      }
  } catch (Exception e) {
      e.printStackTrace();
  }
    }

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

           if(projectsCursor!=null)
           {
           String[] from = new String[]{GinfyDbAdapter.CATEGORY_COLUMN_TITLE, GinfyDbAdapter.CATEGORY_COLUMN_CONTENT, GinfyDbAdapter.CATEGORY_COLUMN_COUNT};
           int[] to = new int[]{R.id.text2, R.id.text1, R.id.count};
            dataAdapter  = new SimpleCursorAdapter(
             this, R.layout.activity_row, 
             projectsCursor, 
             from, 
             to,
             0);
            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();
            lv.setTextFilterEnabled(true); 
            lv.setOnItemClickListener(new OnItemClickListener() {
               public void onItemClick(AdapterView<?> parent, View arg1, int position, long id) {                    
                   if(arg1.getId()== R.id.btnaudioprayer && arg1.isClickable() ){


                         btnaudioprayer = (ImageButton) findViewById(R.id.btnaudioprayer);

                               txtText = (EditText) findViewById(R.id.text1);
                               Toast.makeText(MainActivity.this,txtText .getText().toString(),Toast.LENGTH_SHORT).show();
                       speakOut();

                    }    
                }        
            }); 




           }else
           {
               Log.i("...........","null");
           }

       }

    @Override
    public void onDestroy() {
        // Don't forget to shutdown tts!
        if (tts != null) {
            tts.stop();
            tts.shutdown();
        }
        super.onDestroy();
    }
    @Override
   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!");
        }

    }

    private void speakOut() {

        String text = txtText.getText().toString();

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

这是我的listview的文本到语音功能代码

Logcat错误显示如下

07-16 09:51:08.731: E/AndroidRuntime(905): FATAL EXCEPTION: main
07-16 09:51:08.731: E/AndroidRuntime(905): java.lang.NullPointerException
07-16 09:51:08.731: E/AndroidRuntime(905):  at com.example.json安卓.MainActivity.onInit(MainActivity.java:289)
07-16 09:51:08.731: E/AndroidRuntime(905):  at 安卓.speech.tts.TextToSpeech.dispatchOnInit(TextToSpeech.java:640)
07-16 09:51:08.731: E/AndroidRuntime(905):  at 安卓.speech.tts.TextToSpeech.access$1000(TextToSpeech.java:52)
07-16 09:51:08.731: E/AndroidRuntime(905):  at 安卓.speech.tts.TextToSpeech$Connection.onServiceConnected(TextToSpeech.java:1297)
07-16 09:51:08.731: E/AndroidRuntime(905):  at 安卓.app.LoadedApk$ServiceDispatcher.doConnected(LoadedApk.java:1101)
07-16 09:51:08.731: E/AndroidRuntime(905):  at 安卓.app.LoadedApk$ServiceDispatcher$RunConnection.run(LoadedApk.java:1118)
07-16 09:51:08.731: E/AndroidRuntime(905):  at 安卓.os.Handler.handleCallback(Handler.java:725)
07-16 09:51:08.731: E/AndroidRuntime(905):  at 安卓.os.Handler.dispatchMessage(Handler.java:92)
07-16 09:51:08.731: E/AndroidRuntime(905):  at 安卓.os.Looper.loop(Looper.java:137)
07-16 09:51:08.731: E/AndroidRuntime(905):  at 安卓.app.ActivityThread.main(ActivityThread.java:5039)
07-16 09:51:08.731: E/AndroidRuntime(905):  at java.lang.reflect.Method.invokeNative(Native Method)
07-16 09:51:08.731: E/AndroidRuntime(905):  at java.lang.reflect.Method.invoke(Method.java:511)
07-16 09:51:08.731: E/AndroidRuntime(905):  at com.安卓.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
07-16 09:51:08.731: E/AndroidRuntime(905):  at com.安卓.internal.os.ZygoteInit.main(ZygoteInit.java:560)
07-16 09:51:08.731: E/AndroidRuntime(905):  at dalvik.system.NativeStart.main(Native Method)

共 (2) 个答案

  1. # 1 楼答案

    你得到了NPE

    下面有这个

    lv.setOnItemClickListener(new OnItemClickListener()
    
    public void onItemClick(AdapterView<?> parent, View arg1, int position, long id) {  
        if(arg1.getId()== R.id.btnaudioprayer && arg1.isClickable() ){
            btnaudioprayer = (ImageButton) findViewById(R.id.btnaudioprayer); // initialized on list item click.
    

    你有这个吗

    btnaudioprayer.setEnabled(true); // inside init
    

    在单击列表项之前,btnaudioprayer不会初始化

    当您在listview的每一行中单击按钮时,它会导致NPE导致您实际单击按钮而不是listview行项目

    使用自定义SimpleCursorAdapter

    class CustomAdapter extends SimpleCursorAdapter {
    
        @SuppressWarnings("deprecation")
        public CustomAdapter(Context context, int layout, Cursor c, String[] from, int[] to) {
            super(context, layout, c, from, to);
            // TODO Auto-generated constructor stub
            inflater = LayoutInflater.from(context);
        }
    
        @Override
        public void bindView(View view, Context context, Cursor cursor){
            int row_id = cursor.getColumnIndex("_id");  //Your row id (might need to replace)
            TextView tv = (TextView) view.findViewById(R.id.text1);
            final TextView tv1 = (TextView) view.findViewById(R.id.text2);
            int col1 = cursor.getColumnIndex("title");
            String title = cursor.getString(col1 );
            int col2 = cursor.getColumnIndex("content");
            final String content = cursor.getString(col2 );
            //  TextView tv2 = (TextView) view.findViewById(R.id.text3);
            // cursor.getColumnName(1)
            tv.setText( title);
            tv1.setText( content);
            // 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.btnaudioprayer);
            button.setOnClickListener(new OnClickListener(){
                @Override
                public void onClick(View v){
                    //ADD STUFF HERE you know which row is clicked. and which button
                    typed = content;
                    speakOut();
                }
            });
        }
    
        @Override
        public View newView(Context context, Cursor cursor, ViewGroup parent){
            LayoutInflater inflater = LayoutInflater.from(context);
            View v = inflater.inflate(R.layout.activity_row, parent, false);
    
            bindView(v,context,cursor);
            return v;
        }
    
    }
    

    filldata方法中

    String[] from = new String[]{GinfyDbAdapter.CATEGORY_COLUMN_TITLE, GinfyDbAdapter.CATEGORY_COLUMN_CONTENT, GinfyDbAdapter.CATEGORY_COLUMN_COUNT};
    int[] to = new int[]{R.id.text2, R.id.text1, R.id.count};
    dataAdapter = new CustomAdapter (MainActivity.this, pct, projectsCursor, from, to);
    setListAdapter(dataAdapter);
    

    说出

    private void speakOut() { 
        tts.speak(typed, TextToSpeech.QUEUE_FLUSH, null);
    }
    

    您的类实现了TextToSpeech.OnInitListener

    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!");
        }
    }
    
  2. # 2 楼答案

    这是因为您没有调用TextToSpeech.OnInitListener的重写方法

    @Override
        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 {
                    btnSpeak.setEnabled(true);
                    speakOut();
                }
    
            } else {
                Log.e("TTS", "Initilization Failed!");
            }
    
        } 
    

    解决问题的步骤:——

    • 确保已实现TextToSpeech。OnInitListener

    • 重写onInit()方法,如上所示你的onInit1方法不起作用

    希望这有助于。。。另请参阅here for sample