我正在开发Marathi聊天机器人,为此,我正在使用Google Translator API和Speech to text。 直到昨天,应用程序都可以正常工作,但是在重新启动Android Studio之后,发生了此错误。
我的应用程序正在AVD中运行,并且只有一个植根设备。我在其他10 15台设备中尝试过,应用程序显示错误“不幸的是,应用程序已停止”
in.indekode.hrushi E/AndroidRuntime: FATAL EXCEPTION: main
Process: in.indekode.hrushi, PID: 7073
java.lang.NoSuchMethodError: No static method decodeBase64(Ljava/lang/String;)[B in class Lorg/apache/commons/codec/binary/Base64; or its super classes (declaration of 'org.apache.commons.codec.binary.Base64' appears in /system/framework/org.apache.http.legacy.boot.jar)
at com.google.api.client.util.Base64.decodeBase64(Base64.java:101)
at com.google.api.client.util.PemReader.readNextSection(PemReader.java:106)
at com.google.api.client.util.PemReader.readFirstSectionAndClose(PemReader.java:135)
at com.google.auth.oauth2.ServiceAccountCredentials.privateKeyFromPkcs8(ServiceAccountCredentials.java:296)
at com.google.auth.oauth2.ServiceAccountCredentials.fromPkcs8(ServiceAccountCredentials.java:286)
at com.google.auth.oauth2.ServiceAccountCredentials.fromJson(ServiceAccountCredentials.java:210)
at com.google.auth.oauth2.GoogleCredentials.fromStream(GoogleCredentials.java:174)
at com.google.auth.oauth2.GoogleCredentials.fromStream(GoogleCredentials.java:141)
at in.indekode.hrushi.MainActivity.initV2Chatbot(MainActivity.java:89)
at in.indekode.hrushi.MainActivity.onCreate(MainActivity.java:80)
at android.app.Activity.performCreate(Activity.java:6857)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2676)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2784)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1523)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:163)
at android.app.ActivityThread.main(ActivityThread.java:6238)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
这些行显示错误
initV2Chatbot();
和
GoogleCredentials credentials = GoogleCredentials.fromStream(stream);
我的主要活动是
private static final String TAG = MainActivity.class.getSimpleName();
private static final int USER = 10001;
private static final int BOT = 10002;
private static final String API_KEY = "AIzaSyDoR8abbyu_4BKomJClKA2y1_Sn_M9PJ3A";
private String uuid = UUID.randomUUID().toString();
private LinearLayout chatLayout;
ImageButton voice_ibtn;
public String v_msg;
// TTS
final int RESULT_SPEECH = 100;
TextToSpeech mTextToSpeech;
// Java V2
private SessionsClient sessionsClient;
private SessionName session;
final Handler th = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ScrollView scrollview = findViewById(R.id.chatScrollView);
scrollview.post(() -> scrollview.fullScroll(ScrollView.FOCUS_DOWN));
voice_ibtn = findViewById(R.id.img_btn_voice);
chatLayout = findViewById(R.id.chatLayout);
initV2Chatbot();
showTextView("नमस्कार, मी तुमची मदत कशी करू शकतो?", BOT);
voice_ibtn.setOnClickListener(this::getVoiceInput);
}
private void initV2Chatbot() {
try {
InputStream stream = getResources().openRawResource(R.raw.test_agent_credentials);
GoogleCredentials credentials = GoogleCredentials.fromStream(stream);
String projectId = ((ServiceAccountCredentials)credentials).getProjectId();
SessionsSettings.Builder settingsBuilder = SessionsSettings.newBuilder();
SessionsSettings sessionsSettings = settingsBuilder.setCredentialsProvider(FixedCredentialsProvider.create(credentials)).build();
sessionsClient = SessionsClient.create(sessionsSettings);
session = SessionName.of(projectId, uuid);
} catch (Exception e) {
e.printStackTrace();
}
}
private void getVoiceInput(View view) {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "कृपया बाबाजीशी बोला...\n");
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
try{
startActivityForResult(intent, RESULT_SPEECH);
}
catch (ActivityNotFoundException e){
Toast.makeText(getApplicationContext(),"अरेरे! तुमचा मोबाइल मायक्रोफोनला समर्थन देत नाही..", Toast.LENGTH_SHORT).show();
}
}
@SuppressLint("StaticFieldLeak")
@Override
protected void onActivityResult(int requestCode, int resultcode, Intent data){
super.onActivityResult(requestCode, resultcode, data);
switch (requestCode) {
case RESULT_SPEECH: {
if (resultcode == RESULT_OK && null != data) {
ArrayList<String> text = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
v_msg = text.get(0);
if (v_msg.trim().isEmpty()) {
Toast.makeText(MainActivity.this, "Please enter your query!", Toast.LENGTH_LONG).show();
} else {
final AsyncTask<Void, Void, Void> de = new AsyncTask<Void, Void, Void>() {
@SuppressLint("WrongThread")
@Override
protected Void doInBackground(Void... voids) {
TranslateOptions options = TranslateOptions.newBuilder().setApiKey(API_KEY).build();
final Translate translate = options.getService();
final Translation translation = translate.translate(v_msg, Translate.TranslateOption.targetLanguage("en"));
th.post(new Runnable() {
@Override
public void run() {
String MrUserReply = translation.getTranslatedText();
showTextView(v_msg, USER);
// Java V2
QueryInput queryInput = QueryInput.newBuilder().setText(TextInput.newBuilder().setText(MrUserReply).setLanguageCode("en-US")).build();
new RequestJavaV2Task(MainActivity.this, session, sessionsClient, queryInput).execute();
}
});
return null;
}
}.execute();
}
}
break;
}
}
mTextToSpeech=new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if(status != TextToSpeech.ERROR) {
mTextToSpeech.setLanguage(new Locale("mr","IND"));
}
}
});
}
@SuppressLint("StaticFieldLeak")
public void callbackV2(DetectIntentResponse response) {
if (response != null) {
// process aiResponse here
String botReply = response.getQueryResult().getFulfillmentText();
final AsyncTask<Void, Void, Void> de = new AsyncTask<Void, Void, Void>() {
@SuppressLint("WrongThread")
@Override
protected Void doInBackground(Void... voids) {
TranslateOptions options = TranslateOptions.newBuilder().setApiKey(API_KEY).build();
final Translate translate = options.getService();
final Translation translation = translate.translate(botReply, Translate.TranslateOption.targetLanguage("mr"));
th.post(new Runnable() {
@Override
public void run() {
String mrbotReply = translation.getTranslatedText();
Log.d(TAG, "Bot Reply: " + mrbotReply);
showTextView(mrbotReply, BOT);
}
});
return null;
}
}.execute();
} else {
Log.d(TAG, "Bot Reply: Null");
showTextView("There was some communication issue. Please Try again!", BOT);
}
}
private void showTextView(String message, int type) {
FrameLayout layout;
switch (type) {
case USER:
layout = getUserLayout();
break;
case BOT:
layout = getBotLayout();
break;
default:
layout = getBotLayout();
break;
}
layout.setFocusableInTouchMode(true);
chatLayout.addView(layout); // move focus to text view to automatically make it scroll up if softfocus
TextView tv = layout.findViewById(R.id.chatMsg);
tv.setText(message);
layout.requestFocus();
// queryEditText.requestFocus(); // change focus back to edit text to continue typing
}
FrameLayout getUserLayout() {
LayoutInflater inflater = LayoutInflater.from(MainActivity.this);
return (FrameLayout) inflater.inflate(R.layout.user_msg_layout, null);
}
FrameLayout getBotLayout() {
LayoutInflater inflater = LayoutInflater.from(MainActivity.this);
return (FrameLayout) inflater.inflate(R.layout.bot_msg_layout, null);
}
渐变文件
android {
compileSdkVersion 28
defaultConfig {
applicationId "in.indekode.hrushi"
minSdkVersion 21
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
multiDexEnabled true
}
buildTypes {
release {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
buildConfigField 'String', "ClientAccessToken", CLIENT_ACCESS_TOKEN
resValue 'string', "ClientAccessToken", CLIENT_ACCESS_TOKEN
}
debug {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
buildConfigField 'String', "ClientAccessToken", CLIENT_ACCESS_TOKEN
resValue 'string', "ClientAccessToken", CLIENT_ACCESS_TOKEN
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
// Java V2
packagingOptions {
exclude 'META-INF/LICENSE'
exclude 'META-INF/DEPENDENCIES'
exclude 'META-INF/INDEX.LIST'
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
// Dialogflow SDK dependencies
implementation 'ai.api:sdk:2.0.7@aar'
implementation 'ai.api:libai:1.6.12'
// Java V2
implementation 'com.google.cloud:google-cloud-dialogflow:0.67.0-alpha'
// for Remote Procedure Call to avoid "No functional channel service provider found" error while creating SessionsClient
implementation 'io.grpc:grpc-okhttp:1.15.1'
implementation('com.google.cloud:google-cloud-translate:1.62.0') {
exclude group: 'org.apache.httpcomponents'
exclude group: 'org.json', module: 'json'
}
annotationProcessor 'com.google.cloud:google-cloud-translate:1.62.0'
testImplementation 'junit:junit:4.12'
implementation 'com.android.support:support-annotations:28.0.0'
}
gradle.properties文件
org.gradle.jvmargs=-Xmx1536m
CLIENT_ACCESS_TOKEN="--my token no--"
答案 0 :(得分:1)
我认为问题出在您的Google凭据上 只是看看它们是否已更改???? 只是去寻找...
答案 1 :(得分:0)
创建方法encodeBase64
private String decodeBase64(String coded){
byte[] valueDecoded= new byte[0];
try {
valueDecoded = Base64.decode(coded.getBytes("UTF-8"), Base64.DEFAULT);
} catch (UnsupportedEncodingException e) {
}
return new String(valueDecoded);
}
答案 2 :(得分:0)
我不确定,但我认为您已在gradle中排除了json。因此,请尝试仅实施com.google.cloud:google-cloud-translate
implementation('com.google.cloud:google-cloud-translate:1.62.0')
annotationProcessor 'com.google.cloud:google-cloud-translate:1.62.0'
答案 3 :(得分:0)
实现'commons-codec:commons-codec:1.10'
private String decodeBase64(String data) {
byte[] bytes = new org.apache.commons.codec.binary.Base64().decode(StringUtils.getBytesUtf8(data));
return new String(bytes);
}