1

In my listview I have text and one button as text to speech button.After clicking the button audio is not coming.ssssafter clicking the button audio of text to speech conversion is not working.

Myactivity.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);
    }

This is my text to speech function code for my listview.

Logcat error showing like this

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)
4

2 回答 2

2

You are getting NPE

You have this below

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.

And you have this

btnaudioprayer.setEnabled(true); // inside init

Your btnaudioprayer is not initialized until list item click

When you click button in each row of listview it causes NPE cause your actually clicking button and not listview row items.

Use a Custom 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;
    }

}

In your filldata method

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);

speakOut

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

Your class implements 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!");
    }
}
于 2013-07-17T05:43:05.743 回答
1

This is because you are not calling overridden method of 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!");
        }

    } 

Steps to solve the problem.. :-

  • Make sure you have implemented TextToSpeech.OnInitListener

  • override onInit() method as show above... Your onInit1 method wont work

Hope this helps... Also refer here for sample

于 2013-07-16T09:26:05.350 回答