我想在Android Project中使用Java Function

时间:2014-04-06 18:57:53

标签: java android function

我有一个功能。此功能在Java Project中有效。但是我希望这个功能使用Android Project。我正在使用。项目得到“不幸......已经停止了。你帮助mi吗?

功能

public String yandex_translate(String yandex_lang,String yandex_text) throws IOException, ParseException{

    String yandex_key = "****";


    String yandex_url = "https://translate.yandex.net/api/v1.5/tr.json/translate?key="+yandex_key+"&lang="+yandex_lang+"&text="+yandex_text;


    URL url = new URL(yandex_url);

        URLConnection httpUrlConnection = url.openConnection();

        InputStream inputStream = httpUrlConnection.getInputStream();

        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));


        String line=bufferedReader.readLine();


        JSONParser parser = new JSONParser();


        JSONObject jsonObject = (JSONObject) parser.parse(line);;


        JSONArray msg = (JSONArray)jsonObject.get("text");

        if(jsonObject.get("code").toString().equals("200")){
            return msg.get(0).toString();
        }else{
            return "Çeviri yapılırken bir hata oluştu.";
        }
}

使用

功能
    @Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    String a;
    try {
         a = yandex_translate("en-tr","book");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        a = e.getMessage();
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        a = e.getMessage();
    }
    tvKelime.setText(a);
}

04-06 19:14:25.128: E/AndroidRuntime(2220): FATAL EXCEPTION: main
04-06 19:14:25.128: E/AndroidRuntime(2220): android.os.NetworkOnMainThreadException
04-06 19:14:25.128: E/AndroidRuntime(2220):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
04-06 19:14:25.128: E/AndroidRuntime(2220):     at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
04-06 19:14:25.128: E/AndroidRuntime(2220):     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
04-06 19:14:25.128: E/AndroidRuntime(2220):     at java.net.InetAddress.getAllByName(InetAddress.java:214)
04-06 19:14:25.128: E/AndroidRuntime(2220):     at libcore.net.http.HttpConnection.<init>(HttpConnection.java:70)
04-06 19:14:25.128: E/AndroidRuntime(2220):     at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
04-06 19:14:25.128: E/AndroidRuntime(2220):     at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:340)
04-06 19:14:25.128: E/AndroidRuntime(2220):     at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87)
04-06 19:14:25.128: E/AndroidRuntime(2220):     at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
04-06 19:14:25.128: E/AndroidRuntime(2220):     at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:316)
04-06 19:14:25.128: E/AndroidRuntime(2220):     at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.makeSslConnection(HttpsURLConnectionImpl.java:461)
04-06 19:14:25.128: E/AndroidRuntime(2220):     at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.connect(HttpsURLConnectionImpl.java:433)
04-06 19:14:25.128: E/AndroidRuntime(2220):     at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:290)
04-06 19:14:25.128: E/AndroidRuntime(2220):     at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:240)
04-06 19:14:25.128: E/AndroidRuntime(2220):     at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:282)
04-06 19:14:25.128: E/AndroidRuntime(2220):     at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:177)
04-06 19:14:25.128: E/AndroidRuntime(2220):     at libcore.net.http.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:271)
04-06 19:14:25.128: E/AndroidRuntime(2220):     at com.example.deneme.MainActivity.yandex_translate(MainActivity.java:113)
04-06 19:14:25.128: E/AndroidRuntime(2220):     at com.example.deneme.MainActivity.onClick(MainActivity.java:92)
04-06 19:14:25.128: E/AndroidRuntime(2220):     at android.view.View.performClick(View.java:4204)
04-06 19:14:25.128: E/AndroidRuntime(2220):     at android.view.View$PerformClick.run(View.java:17355)
04-06 19:14:25.128: E/AndroidRuntime(2220):     at android.os.Handler.handleCallback(Handler.java:725)
04-06 19:14:25.128: E/AndroidRuntime(2220):     at android.os.Handler.dispatchMessage(Handler.java:92)
04-06 19:14:25.128: E/AndroidRuntime(2220):     at android.os.Looper.loop(Looper.java:137)
04-06 19:14:25.128: E/AndroidRuntime(2220):     at android.app.ActivityThread.main(ActivityThread.java:5041)
04-06 19:14:25.128: E/AndroidRuntime(2220):     at java.lang.reflect.Method.invokeNative(Native Method)
04-06 19:14:25.128: E/AndroidRuntime(2220):     at java.lang.reflect.Method.invoke(Method.java:511)
04-06 19:14:25.128: E/AndroidRuntime(2220):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
04-06 19:14:25.128: E/AndroidRuntime(2220):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
04-06 19:14:25.128: E/AndroidRuntime(2220):     at dalvik.system.NativeStart.main(Native Method)

2 个答案:

答案 0 :(得分:1)

您应该将代码移动到另一个线程(在本例中为Asynctask)

  

AsyncTask可以正确,轻松地使用UI线程。

     

此类允许在UI上执行后台操作和发布结果   线程,而不必操纵线程和/或处理程序。

     

AsyncTask旨在成为Thread和Handler的辅助类   并不构成通用的线程框架。 AsyncTasks   理想情况下应该用于短期操作(几秒钟的时间)   大多数。)如果你需要保持线程长时间运行,   强烈建议您使用提供的各种API   java.util.concurrent pacakge如Executor,ThreadPoolExecutor和   FutureTask。

     

异步任务由在a上运行的计算定义   后台线程,其结果发布在UI线程上。一个   异步任务由3种泛型类型定义,称为Params,   进度和结果,以及4个步骤,称为onPreExecute,doInBackground,   onProgressUpdate和onPostExecute。

你怎么写它:

private class AsyncRequest extends AsyncTask<String, Void, String>
{
    // private because if someone calls this method without the syntax i said the exception will appear again
    private String yandex_translate(String yandex_lang,String yandex_text) throws IOException, ParseException
    {

        String yandex_key = "****";


        String yandex_url = "https://translate.yandex.net/api/v1.5/tr.json/translate?key="+yandex_key+"&lang="+yandex_lang+"&text="+yandex_text;


        URL url = new URL(yandex_url);

        URLConnection httpUrlConnection = url.openConnection();

        InputStream inputStream = httpUrlConnection.getInputStream();

        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));


        String line=bufferedReader.readLine();


        JSONParser parser = new JSONParser();


        JSONObject jsonObject = (JSONObject) parser.parse(line);;


        JSONArray msg = (JSONArray)jsonObject.get("text");

        if(jsonObject.get("code").toString().equals("200")){
            return msg.get(0).toString();
        }else{
            return "Çeviri yapılırken bir hata oluştu.";
        }
    }

    @Override
    protected String doInBackground(String... params)
    {
        return yandex_translate(params[0], params[1]);
    }

    @Override
    protected void onPostExecute(String s)
    {
        super.onPostExecute(s);
        tvKelime.setText(s);
    }
}

然后使用它

public void onClick(View v) {
    // TODO Auto-generated method stub
    new AsyncRequest("en-tr","book").execute();
}

EditText完成后会更新。

Asynctask documentation

在UI线程中调用了

onPostExecuteonPreExecute,因此您可以在此处更新您的UI。

在工作线程中调用

doInBackground,从这里避免每个UI编辑!如果确实需要,请使用runOnUiThread方法。

答案 1 :(得分:0)

我想你需要把它放在manifest.xml中:

<manifest xlmns:android...>
 ...
 <uses-permission android:name="android.permission.INTERNET"></uses-permission>
</manifest>

我只是猜测,但值得一试。请提供您的日志以获得适当的帮助。