2017-04-26 519 views
0

如何在android studio中使用Yandex翻譯api。我試過在https://github.com/vbauer/yandex-translate-api上使用這個api,但我在下面得到錯誤如何在android studio中使用Yandex翻譯api

這是我的gradle文件。建設項目

Information:Gradle tasks [:app:generateDebugSources, :app:mockableAndroidJar, :app:prepareDebugUnitTestDependencies, :app:generateDebugAndroidTestSources] 
Warning:WARNING: Dependency org.apache.httpcomponents:httpclient:4.5.2 is ignored for debug as it may be conflicting with the internal version provided by Android. 
Warning:WARNING: Dependency commons-logging:commons-logging:1.2 is ignored for debug as it may be conflicting with the internal version provided by Android. 
Warning:WARNING: Dependency org.apache.httpcomponents:httpclient:4.5.2 is ignored for debug as it may be conflicting with the internal version provided by Android. 
Warning:WARNING: Dependency org.json:json:20160212 is ignored for debug as it may be conflicting with the internal version provided by Android. 
Warning:WARNING: Dependency org.apache.httpcomponents:httpclient:4.5.2 is ignored for debug as it may be conflicting with the internal version provided by Android. 
Warning:WARNING: Dependency commons-logging:commons-logging:1.2 is ignored for debug as it may be conflicting with the internal version provided by Android. 
Warning:WARNING: Dependency org.apache.httpcomponents:httpclient:4.5.2 is ignored for debug as it may be conflicting with the internal version provided by Android. 
Warning:WARNING: Dependency org.json:json:20160212 is ignored for debug as it may be conflicting with the internal version provided by Android. 
Warning:WARNING: Dependency org.apache.httpcomponents:httpclient:4.5.2 is ignored for release as it may be conflicting with the internal version provided by Android. 
Warning:WARNING: Dependency commons-logging:commons-logging:1.2 is ignored for release as it may be conflicting with the internal version provided by Android. 
Warning:WARNING: Dependency org.apache.httpcomponents:httpclient:4.5.2 is ignored for release as it may be conflicting with the internal version provided by Android. 
Warning:WARNING: Dependency org.json:json:20160212 is ignored for release as it may be conflicting with the internal version provided by Android. 
Warning:WARNING: Dependency org.apache.httpcomponents:httpclient:4.5.2 is ignored for release as it may be conflicting with the internal version provided by Android. 
Warning:WARNING: Dependency commons-logging:commons-logging:1.2 is ignored for release as it may be conflicting with the internal version provided by Android. 
Warning:WARNING: Dependency org.apache.httpcomponents:httpclient:4.5.2 is ignored for release as it may be conflicting with the internal version provided by Android. 
Warning:WARNING: Dependency org.json:json:20160212 is ignored for release as it may be conflicting with the internal version provided by Android. 
Warning:Conflict with dependency 'com.google.code.findbugs:jsr305'. Resolved versions for app (3.0.1) and test app (2.0.1) differ. See http://g.co/androidstudio/app-test-app-conflict for details. 
Error:Execution failed for task ':app:prepareDebugAndroidTestDependencies'. 
> Dependency Error. See console for details. 
Information:BUILD FAILED 
Information:Total time: 7.412 secs 
Information:1 error 
Information:17 warnings 
Information:See complete output in console 
期間

apply plugin: 'com.android.application' 


android { 
    compileSdkVersion 25 
    buildToolsVersion "25.0.2" 

    defaultConfig { 
     applicationId "com.lecode.chatranslator" 
     minSdkVersion 10 
     targetSdkVersion 25 
     versionCode 1 
     versionName "1.0" 
     testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" 

    } 


    buildTypes { 
     release { 
      minifyEnabled false 
      proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 
     } 
    } 
} 
repositories { 
    maven { 
     url "https://jitpack.io" 
    } 
} 

dependencies { 
    compile ('com.github.vbauer:yandex-translate-api:1.2.5'){ 

    } 
    compile fileTree(include: ['*.jar'], dir: 'libs') 
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { 
     exclude group: 'com.android.support', module: 'support-annotations' 
    }) 
    compile 'com.android.support:appcompat-v7:25.1.0' 
    compile 'com.android.support:design:25.1.0' 
    testCompile 'junit:junit:4.12' 
    compile files('libs/json_simple-1.1.jar') 
} 

錯誤

+0

我這樣做,但在運行應用程序時我仍然得到錯誤。 'compile('com.github.vbauer:yandex-translate-api:1.2.5'){ exclude group:'org.apache.httpcomponents' exclude group:'com.google.code.findbugs',module:' jsr305' 排除組:'org.json',模塊:'json' }' – Jjingo

+0

[如何將Yandex翻譯API放在android應用程序中?](https://stackoverflow.com/questions/ 40659022 /如何對放功能於Yandex的翻譯-API功能於一個功能的Android應用程序) –

回答

0

您可以檢查此API:如下圖所示 https://github.com/DoguD/Yandex-Translate-Android-API

只需導入TranslatorBackgroundTask.java文件到您的應用程序,然後執行:

import co.oriens.yandex_translate_android_api.TranslatorBackgroundTask; 
import android.util.Log; 

public class MainActivity extends Activity{ 
//Set context 
Context context=this; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    //Default variables for translation 
    String textToBeTranslated = "Hello world, yeah I know it is stereotye."; 
    String languagePair = "en-fr"; //English to French ("<source_language>-<target_language>") 
    //Executing the translation function 
    Translate(textToBeTranslated,languagePair); 
} 

//Function for calling executing the Translator Background Task 
void Translate(String textToBeTranslated,String languagePair){ 
    TranslatorBackgroundTask translatorBackgroundTask= new TranslatorBackgroundTask(context); 
    String translationResult = translatorBackgroundTask.execute(textToBeTranslated,languagePair); // Returns the translated text as a String 
    Log.d("Translation Result",translationResult); // Logs the result in Android Monitor 
} 
} 

For more det ailed解釋你可以閱讀github中的README。

0

您可以將該類添加到您的項目並使用它:

public class YandexTranslation { 

    public static String ERROR_MESSAGE = "Can't translate!"; 
    private String mKey; 

    public YandexTranslation setKey(String key) { 
     mKey = key; 
     return this; 
    } 

    public Translation getTranslation(String sourceText, String sourceLang, String destinationLang) throws Throwable { 

     String yandexUrl = "https://translate.yandex.net/api/v1.5/tr.json/translate?key=" + mKey 
       + "&text=" + sourceText + "&lang=" + sourceLang + "-" + destinationLang; 
     URL url = new URL(yandexUrl); 
     HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 

     InputStream inputStream = conn.getInputStream(); 

     String result = convertInputStreamToString(inputStream); 

     inputStream.close(); 
     conn.disconnect(); 

     return Translation.fromJson(result); 
    } 

    public Observable<Translation> getTranslationObservable(final String sourceText, final String sourceLang, final String destinationLang) { 
     return Observable.create(new Observable.OnSubscribe<Translation>() { 
      @Override 
      public void call(Subscriber<? super Translation> subscriber) { 
       try { 
        if (!subscriber.isUnsubscribed()) { 

         Translation translation = getTranslation(sourceText, sourceLang, destinationLang); 
         subscriber.onNext(translation); 
         subscriber.onCompleted(); 
        } 
       } catch (Throwable e) { 
        subscriber.onError(e); 
       } 
      } 
     }); 
    } 

    public Observable<String> getTextObservable(final String sourceText, final String sourceLang, final String destinationLang) { 
     return getTranslationObservable(sourceText, sourceLang, destinationLang) 
       .map(new Func1<Translation, String>() { 
        @Override 
        public String call(Translation translation) { 
         if (Translation.hasTranslation(translation)){ 
          return translation.translations.get(0); 
         } 
         return ERROR_MESSAGE; 
        } 
       }); 
    } 

     public static class Translation { 
     public int code; 
     public String lang; 
     public List<String> translations; 

     public static Translation fromJson(String json) throws JSONException { 
      Translation translation = new Translation(); 
      JSONObject jsonObj = new JSONObject(json); 
      translation.code = jsonObj.getInt("code"); 
      translation.lang = jsonObj.getString("lang"); 
      JSONArray text = jsonObj.getJSONArray("text"); 
      translation.translations = fromJsonArray(text); 
      return translation; 
     } 

     public static boolean hasTranslation(Translation t){ 
      return t != null && t.translations != null && t.translations.size() != 0; 
     } 
    } 

    private static String convertInputStreamToString(InputStream inputStream) throws IOException { 
     BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); 
     String line = ""; 
     String result = ""; 
     while ((line = bufferedReader.readLine()) != null) 
      result += line; 

     inputStream.close(); 
     return result; 

    } 

    private static List<String> fromJsonArray(JSONArray jsonArray) throws JSONException { 
     List<String> list = new ArrayList<>(); 
     if (jsonArray != null && jsonArray.length() != 0) { 
      for (int i = 0; i < jsonArray.length(); i++) { 
       String text = jsonArray.getString(i); 
       list.add(text); 
      } 
     } 
     return list; 
    } 
} 

更多細節: https://github.com/OlegTarashkevich/YandexTranslation