-1

I'm building an app that contains search view autocomplete but when I parse data from JSON and pass it to Autocomplete it crashes. I don't know whether I made a problem or what, please anyone can help me to implement autocomplete from JSON to search view I will be grateful.

MainActivity3.java

AutoCompleteTextView autoCompleteTextView = findViewById(R.id.actv);
        autoCompleteTextView.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                String key = charSequence.toString();
                OkHttpClient client = new OkHttpClient();
                String url = "http://suggestqueries.google.com/complete/search?hl=en&ds=yt&q=" + key + "&client=firefox";
                try {
                    Response response = client.newCall(new Request.Builder().url(url).build()).execute();
                    String r = response.body().string();
                    r = r.replace("[", "");
                    r = r.replace("]", "");
                    r = r.replace("\"", "");
                    r = r.replace("{", "");
                    r = r.replace(":", "");

                    String[] fin = r.split(",");
                    //  myadpter.notifyDataSetChanged();
                    String list1 = r.replace(",,googlesuggestsubtypes512,433,512,433,512,433,131,512,433,512,512,433,512,433,512,512,433,512,433}", "");
                    String list2 = "{" + list1 + "}";
                    String list3 = "[" + list2 + "]";

                    ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity3.this,
                            R.layout.custom_list_tem, R.id.text_view_list_item, Collections.singletonList(list3));
                    editText.setAdapter(adapter);

                } catch (IOException e) {
                    e.printStackTrace();
                }


            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

Error:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.sqldata, PID: 12786
    android.os.NetworkOnMainThreadException
        at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1450)
        at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:102)
        at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:90)
        at java.net.InetAddress.getAllByName(InetAddress.java:787)
        at okhttp3.Dns$1.lookup(Dns.java:39)
        at okhttp3.internal.connection.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:185)
        at okhttp3.internal.connection.RouteSelector.nextProxy(RouteSelector.java:149)
        at okhttp3.internal.connection.RouteSelector.next(RouteSelector.java:84)
        at okhttp3.internal.connection.StreamAllocation.findConnection(StreamAllocation.java:213)
        at okhttp3.internal.connection.StreamAllocation.findHealthyConnection(StreamAllocation.java:134)
        at okhttp3.internal.connection.StreamAllocation.newStream(StreamAllocation.java:113)
        at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:42)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
        at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:93)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
        at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
        at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:125)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
        at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:200)
        at okhttp3.RealCall.execute(RealCall.java:77)
        at com.example.sqldata.MainActivity3.Callforapi(MainActivity3.java:107)
        at com.example.sqldata.MainActivity3.access$000(MainActivity3.java:33)
        at com.example.sqldata.MainActivity3$1.onTextChanged(MainActivity3.java:64)
        at android.widget.TextView.sendOnTextChanged(TextView.java:9512)
        at android.widget.TextView.handleTextChanged(TextView.java:9599)
        at android.widget.TextView$ChangeWatcher.onTextChanged(TextView.java:12161)
        at android.text.SpannableStringBuilder.sendTextChanged(SpannableStringBuilder.java:1252)
        at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:573)
        at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:504)
        at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:502)
        at android.view.inputmethod.BaseInputConnection.replaceText(BaseInputConnection.java:852)
        at android.view.inputmethod.BaseInputConnection.commitText(BaseInputConnection.java:206)
        at com.android.internal.widget.EditableInputConnection.commitText(EditableInputConnection.java:183)
        at com.android.internal.view.IInputConnectionWrapper.executeMessage(IInputConnectionWrapper.java:341)
        at com.android.internal.view.IInputConnectionWrapper$MyHandler.handleMessage(IInputConnectionWrapper.java:85)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:6977)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:528)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:910)

I'm building an app that contains search view autocomplete but when I parse data from JSON and pass it to Autocomplete it crashes. I don't know whether I made a problem or what, please anyone can help me to implement autocomplete from JSON to search view I will be grateful.

2 Answers2

0

your issue as your Exception indicates "NetworkOnMainThreadException" which means your are trying to make a network call in the main thread which is prohibited.

you shouldn't do any heavy work such network call, access database, reading or writing to file system,.... etc in the main thread you should do previously mentioned operations in a separate threads and keep main thread for UI rendering and user interaction only because doing such heavy work in main thread will lag your main thread which will makes your app suffers from ANR (Application not responding) or it will throw running time exception like your case.

because the fact that this is java code, I recommend to use the famous rxjava library to handle multi threading.

please note you don't have to user OkHttp directly except if you are doing this for practice purpose but instead use retrofit which is a simple and powerful library built over OkHttp.

Ramy Ibrahim
  • 656
  • 4
  • 19
0

You have to use AsyncTask to call api you can not perform network operation on mainThread. So, just put your onTextChanged() code into AsyncTask in doInBackground()

Sample:

public class BackgroundClassName extends AsyncTask<String,Void,String>{

    @Override
    protected String doInBackground(String... strings) {
        //put your onTextChanged() here
        return null;
    }
}

then, call BackgroundClassName class into onTextChanged() using new BackgroundClassName().execute();

Vatsal Dholakiya
  • 545
  • 4
  • 19