在我的列表视图中,我有文字和一个按钮作为文字转语音按钮。单击按钮后音频不会出现。单击按钮音频后,文本到语音的转换不起作用。
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);
}
这是我的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)
答案 0 :(得分:2)
你正在获得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
未初始化
当您单击列表视图的每一行中的按钮时,它会导致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);
SPEAKOUT
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!");
}
}
答案 1 :(得分:1)
这是因为您没有调用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