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

标签 java android text-to-speech

在我的 ListView 中,我有文本和一个按钮作为文本到语音按钮。单击按钮后音频没有出现。ssss单击按钮后文本到语音转换的音频不起作用。

我的activity.java

  @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.jsonandroid.MainActivity.onInit(MainActivity.java:289)
07-16 09:51:08.731: E/AndroidRuntime(905):  at android.speech.tts.TextToSpeech.dispatchOnInit(TextToSpeech.java:640)
07-16 09:51:08.731: E/AndroidRuntime(905):  at android.speech.tts.TextToSpeech.access$1000(TextToSpeech.java:52)
07-16 09:51:08.731: E/AndroidRuntime(905):  at android.speech.tts.TextToSpeech$Connection.onServiceConnected(TextToSpeech.java:1297)
07-16 09:51:08.731: E/AndroidRuntime(905):  at android.app.LoadedApk$ServiceDispatcher.doConnected(LoadedApk.java:1101)
07-16 09:51:08.731: E/AndroidRuntime(905):  at android.app.LoadedApk$ServiceDispatcher$RunConnection.run(LoadedApk.java:1118)
07-16 09:51:08.731: E/AndroidRuntime(905):  at android.os.Handler.handleCallback(Handler.java:725)
07-16 09:51:08.731: E/AndroidRuntime(905):  at android.os.Handler.dispatchMessage(Handler.java:92)
07-16 09:51:08.731: E/AndroidRuntime(905):  at android.os.Looper.loop(Looper.java:137)
07-16 09:51:08.731: E/AndroidRuntime(905):  at android.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.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
07-16 09:51:08.731: E/AndroidRuntime(905):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
07-16 09:51:08.731: E/AndroidRuntime(905):  at dalvik.system.NativeStart.main(Native Method)

最佳答案

你得到了 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!");
    }
}

关于java - 文本到语音功能在我的 ListView 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17672539/

相关文章:

java - 如何在editText中显示交替的图标?

java - 在 Eclipse 中调试 Java 代码时出现 "Source not found"

java - 如何在byte-buddy中创建参数化类?

android - 是什么导致我的 Android EditText 消失

ios - iphone 版 flite tts 中的完美音高、方差和速度值是多少

python - 如何在 'gTTS' 中使用多语言输入单行?

java - libgdx - 如何在舞台上添加背景图片?

android - 我自己的自定义SeekBar Android

android - 对 lon\lat 点列表进行排序,从最近的开始

javascript - meSpeak.js - 使用回调方法时不播放第二个单词