Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/224.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 从mainactivity访问searchview查询文本_Java_Android_Android Intent_Searchview - Fatal编程技术网

Java 从mainactivity访问searchview查询文本

Java 从mainactivity访问searchview查询文本,java,android,android-intent,searchview,Java,Android,Android Intent,Searchview,我计划制作一个新闻应用程序。我在我的应用程序的操作栏中创建了一个简单的搜索视图 这是主要的活动 package com.example.hp.simplenews; import android.app.Activity; import android.app.LoaderManager; import android.app.SearchManager; import android.content.Context; import android.content.Intent; import

我计划制作一个新闻应用程序。我在我的应用程序的操作栏中创建了一个简单的搜索视图

这是主要的活动

package com.example.hp.simplenews;

import android.app.Activity;
import android.app.LoaderManager;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.content.Loader;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SearchView;

import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<List<News>> {
    private int Newsloaderid = 1;
    private Newsadapter newslistadapter;
    private String search_query_input = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ListView newslistview = findViewById(R.id.list);
        newslistadapter = new Newsadapter(this, new ArrayList<News>());
        newslistview.setAdapter(newslistadapter);
        LoaderManager loaderManager = getLoaderManager();
        loaderManager.initLoader(Newsloaderid, null, MainActivity.this);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the options menu from XML
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.options_menu, menu);

        // Get the SearchView and set the searchable configuration
        SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
        SearchView searchView = (SearchView) menu.findItem(R.id.search).getActionView();
        // Assumes current activity is the searchable activity
        searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
        searchView.setIconifiedByDefault(false); // Do not iconify the widget; expand it by default
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String newtext) {
                search_query_input = newtext;
                return true;
            }
            @Override
            public boolean onQueryTextChange(String query) {
                return true;
            }
        });
        return true;
    }

    @Override
    public Loader<List<News>> onCreateLoader(int i, Bundle bundle) {
        return new NewsLoader(this, search_query_input);
    }

    @Override
    public void onLoadFinished(Loader<List<News>> loader, List<News> news) {
        newslistadapter.clear();
        if (news != null && !news.isEmpty()) {
            newslistadapter.addAll(news);
        }
    }

    @Override
    public void onLoaderReset(Loader loader) {
        newslistadapter.clear();
    }
}
package com.example.hp.simplenews;
导入android.app.Activity;
导入android.app.LoaderManager;
导入android.app.SearchManager;
导入android.content.Context;
导入android.content.Intent;
导入android.content.Loader;
导入android.support.v7.app.AppActivity;
导入android.os.Bundle;
导入android.view.Menu;
导入android.view.MenuInflater;
导入android.view.view;
导入android.widget.ListAdapter;
导入android.widget.ListView;
导入android.widget.SearchView;
导入java.net.MalformedURLException;
导入java.util.ArrayList;
导入java.util.List;
公共类MainActivity扩展AppCompatActivity实现LoaderManager.LoaderCallbacks{
private int Newsloaderid=1;
私有新闻适配器新闻列表适配器;
私有字符串搜索\查询\输入=”;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView newslistview=findViewById(R.id.list);
newslistadapter=新的Newsadapter(这是新的ArrayList());
setAdapter(newslistadapter);
LoaderManager LoaderManager=getLoaderManager();
initLoader(Newsloaderid,null,MainActivity.this);
}
@凌驾
公共布尔onCreateOptions菜单(菜单){
//从XML中展开“选项”菜单
MenuInflater充气机=getMenuInflater();
充气机。充气(右菜单。选项菜单,菜单);
//获取SearchView并设置可搜索配置
SearchManager SearchManager=(SearchManager)getSystemService(Context.SEARCH\u服务);
SearchView SearchView=(SearchView)菜单.findItem(R.id.search).getActionView();
//假设当前活动是可搜索的活动
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName());
searchView.setIconifiedByDefault(false);//不要将小部件图标化;默认情况下展开它
searchView.setOnQueryTextListener(新的searchView.OnQueryTextListener(){
@凌驾
公共布尔值onQueryTextSubmit(字符串newtext){
搜索\查询\输入=newtext;
返回true;
}
@凌驾
公共布尔onQueryTextChange(字符串查询){
返回true;
}
});
返回true;
}
@凌驾
公共加载器onCreateLoader(inti,Bundle){
返回新的新闻加载器(此,搜索\查询\输入);
}
@凌驾
public void onLoadFinished(加载程序,列表新闻){
newslistadapter.clear();
if(news!=null&&!news.isEmpty()){
newslistadapter.addAll(新闻);
}
}
@凌驾
公共void onLoaderReset(加载器){
newslistadapter.clear();
}
}
SearchResultsActivity处理HTTP请求和JSON解析

这是SearchResultsActivity

    package com.example.hp.simplenews;

import android.app.Activity;
import android.app.LoaderManager;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.content.Loader;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

public class SearchResultsActivity extends Activity{
    String query_string = "";

    private static final String LOG_TAG = SearchResultsActivity.class.getName();

    public static URL createUrl(String query_url) throws MalformedURLException {
        URL url = null;
        String APIKey = "apiKey";
        String query = "q";
        try {
            final String base_url = "https://newsapi.org/v2/everything?";
            Uri final_url = Uri.parse(base_url).buildUpon()
                    .appendQueryParameter(query, query_url)
                    .appendQueryParameter(APIKey, "48f67c1e66994aa8a92f92a48b5f6581")
                    .build();
            url = new URL(final_url.toString());
            Log.i(LOG_TAG, "THE FINAL URL IS" + final_url);
        } catch (MalformedURLException e) {
            e.printStackTrace();
            Log.e(LOG_TAG, "the url couldn't be made");
        }

        return url;
    }

    private static final String HTTPREQUEST(URL url) throws IOException {
        String jsonresponse = "";
        if (jsonresponse == null) {
            return null;
        }
        HttpURLConnection httpURLConnection = null;
        InputStream inputStream = null;
        try {
            httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("GET");
            httpURLConnection.setReadTimeout(10000);
            httpURLConnection.setConnectTimeout(150000);
            httpURLConnection.connect();
            if (httpURLConnection.getResponseCode() == 200) {
                inputStream = httpURLConnection.getInputStream();
                jsonresponse = readfromstream(inputStream);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
            if (httpURLConnection != null) {
                httpURLConnection.disconnect();
            }
        }
        return jsonresponse;
    }

    private static final String readfromstream(InputStream inputStream) throws IOException {
        StringBuilder output = new StringBuilder();
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        String urlline = bufferedReader.readLine();
        while (urlline != null) {
            output.append(urlline);
            urlline = bufferedReader.readLine();
        }
        return output.toString();
    }

    private static List<News> JSONParser(String NewsJSON) throws JSONException {
        if (TextUtils.isEmpty(NewsJSON)) {
            return null;
        }
        List<News> news = new ArrayList<>();
        try {
            JSONObject basejson = new JSONObject(NewsJSON);
            JSONArray articles = basejson.getJSONArray("articles");
            for (int i = 0; i < articles.length(); i++) {
                News newss = new News();
                JSONObject c = articles.getJSONObject(i);
                JSONObject source = c.getJSONObject("source");
                newss.setMsource(source.getString("name"));
                newss.setMtitle(c.getString("title"));
                newss.setMdescription(c.getString("description"));
                newss.setMtime(c.getString("publishedAt"));
                String image = c.getString("urlToImage");
                if (image != null) {
                    newss.setmImage(c.getString("urlToImage"));
                }
                newss.setNewsURL(c.getString("url"));
                news.add(newss);
            }
        } catch (JSONException j) {
            Log.e(LOG_TAG, "couldn't parse jSON");
        }
        return news;
    }

    public static List<News> fetchnews(String search_query) throws IOException, JSONException {
        URL url = createUrl(search_query);
        String JSONRESPONSE = null;
        try {
            JSONRESPONSE = HTTPREQUEST(url);
        } catch (IOException j) {
            j.printStackTrace();
        }
        List<News> news = JSONParser(JSONRESPONSE);
        return news;
    }

    @Override
    protected void onNewIntent(Intent intent) {
        setIntent(intent);
        try {
            handleIntent(intent);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }

    private void handleIntent(Intent intent) throws MalformedURLException {
        if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
            query_string = intent.getStringExtra(SearchManager.QUERY);
            Log.i(LOG_TAG, "The querytext is" + query_string);
        }

    }
}
package com.example.hp.simplenews;
导入android.app.Activity;
导入android.app.LoaderManager;
导入android.app.SearchManager;
导入android.content.Context;
导入android.content.Intent;
导入android.content.Loader;
导入android.net.Uri;
导入android.os.Bundle;
导入android.support.v4.app.NavUtils;
导入android.text.TextUtils;
导入android.util.Log;
导入android.view.Menu;
导入android.view.MenuInflater;
导入android.widget.SearchView;
导入android.widget.TextView;
导入android.widget.Toast;
导入org.json.JSONArray;
导入org.json.JSONException;
导入org.json.JSONObject;
导入java.io.BufferedReader;
导入java.io.IOException;
导入java.io.InputStream;
导入java.io.InputStreamReader;
导入java.net.HttpURLConnection;
导入java.net.MalformedURLException;
导入java.net.URL;
导入java.nio.charset.charset;
导入java.util.ArrayList;
导入java.util.List;
公共类SearchResultsActivity扩展活动{
字符串查询_String=“”;
私有静态最终字符串LOG_TAG=SearchResultsActivity.class.getName();
公共静态URL createUrl(字符串查询\u URL)引发错误的URL异常{
URL=null;
字符串APIKey=“APIKey”;
字符串query=“q”;
试一试{
最终字符串base_url=”https://newsapi.org/v2/everything?";
Uri final\u url=Uri.parse(base\u url.buildon())
.appendQueryParameter(查询,查询url)
.附录参数(APIKey,“48f67c1e66994aa8a92f92a48b5f6581”)
.build();
url=新url(final_url.toString());
Log.i(Log_标签,“最终URL为”+最终URL);
}捕获(格式错误){
e、 printStackTrace();
Log.e(Log_标记,“无法创建url”);
}
返回url;
}
私有静态最终字符串HTTPREQUEST(URL)引发IOException{
字符串jsonresponse=“”;
if(jsonresponse==null){
返回null;
}
HttpURLConnection HttpURLConnection=null;
InputStream InputStream=null;
试一试{
httpURLConnection=(httpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod(“GET”);
httpURLConnection.setReadTimeout(10000);
httpURLConnection.setConnectTimeout(150000);
httpURLConnection.connect();
if(httpURLConnection.getResponseCode()==200){
inputStream=httpURLConnection.getInputStream();
jsonresponse=readfromstream(inputStream);
}
}捕获(IOE异常){
e、 printStackTrace();
}最后{
如果(inputStream!=null){
inputStream.close();
}
如果(ht
public class NewsLoader extends AsyncTaskLoader<List<News>> {
    private String mUrl;
    private static String LOG_TAG = NewsLoader.class.getName();

    public NewsLoader(Context context, String url) {
        super(context);
        mUrl = url;
    }

    @Override
    protected void onStartLoading() {
        forceLoad();
    }

    @Override
    public List<News> loadInBackground() {
        if (mUrl == null) {
            return null;
        }
        List<News> news = null;
        try {
            news = SearchResultsActivity.fetchnews(mUrl);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return news;
    }
}
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener(){
    onQueryTextChange(String newText){
      //when user type in searchview get string as newText parameter
      asynTaskMethod(newText);
    }
   onQueryTextSubmit(String query){
     //when user press submit button in searchview get string as query parameter
   asynTaskMethod(query);
   }

});