在Android中搜索无效;应用程序崩溃

时间:2017-04-15 08:31:33

标签: java android android-fragments okhttp

我正在尝试在我的应用上实现一个从在线数据库获取数据的搜索选项。我的libs文件夹中有okhhtp3.jar和okio.jar。每当我在搜索字段中输入文本时,应用程序就会崩溃并关闭。这是我的搜索代码:
`

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.URLUtil;
import android.widget.SearchView;


import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


`public class Search extends Fragment {

    private SearchView searchField;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.search, container, false);
        this.searchField = (SearchView) rootView.findViewById(R.id.searchView);


        // perform set on query text listener event
        this.searchField.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                String url = "https://api.themoviedb.org/3/search/movie?api_key&language=en-US&query="+query+"&page=1&include_adult=false";
                //URLUtil.isValidUrl(query);
                if (URLUtil.isValidUrl(url) == true) {

                    OkHttpClient client = new OkHttpClient();

                    MediaType mediaType = MediaType.parse("application/octet-stream");
                    RequestBody body = RequestBody.create(mediaType, "{}");
                    Request request = new Request.Builder().url(url).get().build();

                    try {
                        Response response = client.newCall(request).execute();
                        //System.out.println(response.message());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                }

                System.out.println(query);
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                // do something when text changes
                return false;
            }
        });

        this.searchField.getQuery();
        return rootView;
    }




}

我得到的例外:

04-15 08:33:18 E/InputEventSender: Exception dispatching finished signal.
04-15 08:33:18 E/MessageQueue-JNI: Exception in MessageQueue callback: handleReceiveCallback
04-15 08:33:18 E/MessageQueue-JNI: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1303)
at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:86)
at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:74)
at java.net.InetAddress.getAllByName(InetAddress.java:752)
at okhttp3.Dns$1.lookup(Dns.java:39)
at okhttp3.internal.connection.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:170)
at okhttp3.internal.connection.RouteSelector.nextProxy(RouteSelector.java:136)
at okhttp3.internal.connection.RouteSelector.next(RouteSelector.java:81)
at okhttp3.internal.connection.StreamAllocation.findConnection(StreamAllocation.java:171)
at okhttp3.internal.connection.StreamAllocation.findHealthyConnection(StreamAllocation.java:121)
at okhttp3.internal.connection.StreamAllocation.newStream(StreamAllocation.java:100)
at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:42)                                                                                    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:67)
at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:93)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:67)
at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93)                                                                                    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:120)                                                                                   at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:67)
at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:179)
at okhttp3.RealCall.execute(RealCall.java:63)                                                                                    at Search$1.onQueryTextSubmit(Search.java:46)                                                                                    at android.widget.SearchView.onSubmitQuery(SearchView.java:1285)                                                                                    at android.widget.SearchView.-wrap8(SearchView.java)                                                                                    at android.widget.SearchView$6.onEditorAction(SearchView.java:1262)                                                                                    at android.widget.TextView.doKeyDown(TextView.java:6193)                                                                                    at android.widget.TextView.onKeyDown(TextView.java:6075)                                                                                    at android.widget.AutoCompleteTextView.onKeyDown(AutoCompleteTextView.java:829)                                                                                    at android.view.KeyEvent.dispatch(KeyEvent.java:2688)                                                                                    at android.view.View.dispatchKeyEvent(View.java:9960)                                                                                    at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1630)                                                                                    at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1630)                                                                                    at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1630)                                                                                    at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1630)                                                                                 at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1630)                                                                                    at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1630)                                                                                   at android.support.v4.view.ViewPager.dispatchKeyEvent(ViewPager.java:2761)                                                                                   at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1630)                                                                                    at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1630)                                                                                    at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1630)                                                                                    at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1630)                                                                                    at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1630)                                                                                    at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1630)                                                                                    at com.android.internal.policy.DecorView.superDispatchKeyEvent(DecorView.java:405)                                                                                   at com.android.internal.policy.PhoneWindow.superDispatchKeyEvent(PhoneWindow.java:1798)                                                                                    at android.app.Activity.dispatchKeyEvent(Activity.java:3021)                                                                                    at android.support.v7.app.AppCompatActivity.dispatchKeyEvent(AppCompatActivity.java:547)                                                                                   at android.support.v7.view.WindowCallbackWrapper.dispatchKeyEvent(WindowCallbackWrapper.java:59)                                                                                    at android.support.v7.app.AppCompatDelegateImplBase$AppCompatWindowCallbackBase.dispatchKeyEvent(AppCompatDelegateImplBase.java:319)                                                                                    at android.support.v7.view.WindowCallbackWrapper.dispatchKeyEvent(WindowCallbackWrapper.java:59)
at com.a
04-15 08:33:18 D/AndroidRuntime: Shutting down VM
04-15 08:33:18 E/AndroidRuntime: FATAL EXCEPTION: main
Process: PID: 4675
android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1303)
at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:86)
at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:74)                                                                                  at java.net.InetAddress.getAllByName(InetAddress.java:752)                                                                                 at okhttp3.Dns$1.lookup(Dns.java:39)

我很感激任何帮助!

2 个答案:

答案 0 :(得分:0)

替换此

Response response = client.newCall(request).execute();

With an async call

client.newCall(request).enqueue(new Callback() {
    // TODO: Learn to implement this correctly
});
  

我的libs文件夹中有okhhtp3.jar和okio.jar

尝试使用Gradle而不是jar文件。

compile 'com.squareup.okhttp3:okhttp:(insert latest version)' 

答案 1 :(得分:0)

这看起来(根据堆栈跟踪)就像尝试在主线程上调用网络调用一样:

android.os.NetworkOnMainThreadException

这意味着您必须在异步线程上运行任何网络工件:

//Change String, Void, String with whatever you want it to take as input and return
private class DownloadTask extends AsyncTask<String, Void, String> {


    @Override
    protected void onPreExecute() {}

    @Override
    protected String doInBackground(String... urls) {
        //What you do here: Add your network tasks. 
        return result;
    }


    @Override
    protected void onPostExecute(String result) {
    }

}