您好我正在处理翻译应用程序。这个应用程序从webview获取string.getText()。toString();我想用yandex api翻译这个选定的单词。我创建了AsyncTask类来从api中获取翻译后的单词。
public class Translate extends AsyncTask<String, String, JSONObject> {
TranslatedWord trWord = new TranslatedWord();
private static final String TAG_RESULTS = "text";
@Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(args[0]);
return json;
}
@Override
protected void onPostExecute(JSONObject json) {
try {
JSONArray result = json.getJSONArray(TAG_RESULTS);
String text = result.getString(0);
trWord.setTrWord(text);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
我应该在同一个表上插入所选单词并将其翻译成数据库。我在下面的代码中这样做。
private static String TRANSLATE_URL = "https://translate.yandex.net/api/v1.5/tr.json/translate?" +
"key=trnsl.1.1.20171218T092308Z.2e90b7fad1cf523b.a2696fb34d9d70f427cad15c9ee664230c048054" +
"&lang=tr&text=" + selectedWord;
final ClipboardManager clipboard = (ClipboardManager) this.getSystemService(Context.CLIPBOARD_SERVICE);
clipboard.addPrimaryClipChangedListener(new ClipboardManager.OnPrimaryClipChangedListener() {
@Override
public void onPrimaryClipChanged() {
selectedWord = clipboard.getText().toString();
translate.execute(TRANSLATE_URL);
translatedWord = trword.getTrWord();
Toast.makeText(getApplicationContext(), "Copy:\n" + selectedWord, Toast.LENGTH_SHORT).show();
WordsDbHelper helper = new WordsDbHelper(getApplicationContext());
SQLiteDatabase db = helper.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT engWord FROM words; ", null);
boolean titlePresent = false;
while (cursor.moveToNext()) {
String recorded_title = cursor.getString(cursor.getColumnIndex("engWord"));
if (recorded_title.equals(selectedWord)) {
titlePresent = true;
Toast.makeText(getApplicationContext(), "There is already same word!",
Toast.LENGTH_LONG).show();
}
}
if (!titlePresent)
helper.createWord(new Words(selectedWord, translatedWord));
}
});
我在翻译单词方面遇到了一些问题。我正在接受这个错误。我需要一些帮助。请帮帮我。
java.lang.NullPointerException:尝试调用虚方法&#39; android.os.AsyncTask com.ermanelm.redler20.Translate.execute(java.lang.Object [])&#39;在空对象引用上
答案 0 :(得分:0)
似乎翻译对象为空,请尝试替换,
translate.execute(TRANSLATE_URL);
与
new Translate().execute(TRANSLATE_URL);