-2

I have a function. This function worked in Java Project. But I want this function use Android Project. While I was using. Project get "unfortunately .. has stopped. Do you help mi ?

Function

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.";
        }
}

function using

    @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)
Andrew Barber
  • 39,603
  • 20
  • 94
  • 123
Mazlum Ağar
  • 41
  • 11

2 Answers2

1

You should move your code to work in a different thread (in this case Asynctask)

AsyncTask enables proper and easy use of the UI thread.

This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

AsyncTask is designed to be a helper class around Thread and Handler and does not constitute a generic threading framework. AsyncTasks should ideally be used for short operations (a few seconds at the most.) If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent pacakge such as Executor, ThreadPoolExecutor and FutureTask.

An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, called Params, Progress and Result, and 4 steps, called onPreExecute, doInBackground, onProgressUpdate and onPostExecute.

It's how you could write it:

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);
    }
}

then to use it

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

The EditText will be updated when finished.

Asynctask documentation.

onPostExecute and onPreExecute are called in the UI thread, so you can update your UI here.

doInBackground is called in the worker thread, avoid every UI edit from here! If you really need, use runOnUiThread method.

Marco Acierno
  • 14,682
  • 8
  • 43
  • 53
0

I guess you need to put this in your manifest.xml:

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

I am just guessing but it is worth a try. Please provide your logs to get proper help.

Robin Ellerkmann
  • 2,083
  • 4
  • 29
  • 34