Android实现模糊查询新闻 简易新闻(十八)
关于
本篇实现内容通过sql语句查询对应mysql数据库中新闻数据实现模糊查询对应新闻,并展示到界面中。
关于查询的新闻来源是本人远程数据库中的内容,是从聚合数据中保存下来的,这个可以再前面博文中找到,关于mysql的连接也可以在前面找到,这里仅仅是按照博文进度进行新增。
新闻数据不做商用。。
效果
实现第一步,修改activity_web.xml布局文件
在原先版本中添加listview来显示查询到的新闻标题数据
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:background="@color/colorbackground"
tools:context=".WebActivity">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar_webview"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
android:background="@color/colorhuise"
app:titleTextColor="@color/black"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<WebView
android:id="@+id/webView"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
</WebView>
<ListView
android:id="@+id/list_view"
android:visibility="gone"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar_webcomment"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
android:background="#ffffff"
app:titleTextColor="@color/black"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
app:elevation="8dp">
<!-- <LinearLayout
android:id="@+id/tab_layout_board"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="right|center_vertical"
>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/tab_imgbt_board"
android:src="@drawable/ic_star_border_favourite"
tools:ignore="VectorDrawableCompat" />
</LinearLayout>-->
</android.support.v7.widget.Toolbar>
</LinearLayout>
</LinearLayout>
</android.support.design.widget.CoordinatorLayout>
第二步,添加listview的子item布局文件
新建item_layout_news.xml文件,先展示一下显示的样式
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="10dp"
android:padding="8dp"
android:background="#FFF"
android:layout_marginBottom="10dp">
<LinearLayout
android:id="@+id/linearlayout_gzlx"
android:layout_width="match_parent"
android:layout_height="45dp"
android:background="@color/colorpanelback"
android:gravity="center"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:tag="jf">
//这里的图片就是上图所显示的蓝色的图片,只是为了让显示的新闻标题页面不那么丑陋添加的。
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/blue" />
<RelativeLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center">
<!--<ScrollView-->
<!--android:layout_width="match_parent"-->
<!--android:layout_height="match_parent"-->
<!--android:background="@null"-->
<!--android:scrollbars="none"-->
<!-->-->
<TextView
android:id="@+id/title_news"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_gravity="center_vertical"
android:layout_marginLeft="10dp"
android:gravity="left"
android:textColor="#282828"
android:textSize="14sp" />
<!--</ScrollView>-->
</RelativeLayout>
</LinearLayout>
<!-- <LinearLayout
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="@color/colorborder" />
<color name="colorborder">#e1e1e1</color>-->
</RelativeLayout>
第三步,对应添加listview的适配器NewslnfoAdapter.java
package com.example.frametest.UserMode;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.example.frametest.R;
import com.example.frametest.json.NewsBean;
import java.util.List;
public class NewsInfoAdapter extends ArrayAdapter<NewsBean.ResultBean.DataBean> {
private int resourceId;
public NewsInfoAdapter(Context context, int textViewResourceId, List<NewsBean.ResultBean.DataBean> objects){
super(context, textViewResourceId, objects);
resourceId = textViewResourceId;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
NewsBean.ResultBean.DataBean dataBean = getItem(position);
View view =null;
if (convertView == null){
view = LayoutInflater.from(getContext()).inflate(resourceId, parent,false);
} else {
view = convertView;
}
TextView newsName = (TextView) view.findViewById(R.id.title_news);
newsName.setText(dataBean.getTitle());
return view;
}
public class ViewHoder{
private TextView newsName;
}
}
第四步,修改WebActivity.java
package com.example.frametest;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBar;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.SslErrorHandler;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.Toast;
import com.example.frametest.UserMode.LoginActivity;
import com.example.frametest.UserMode.NewsInfoAdapter;
import com.example.frametest.UserMode.UserFavoriteActivity;
import com.example.frametest.json.NewsBean;
import com.example.frametest.tools.BasicActivity;
import com.example.frametest.tools.DBOpenHelper;
import com.example.frametest.tools.MyApplication;
import com.example.frametest.tools.ToastUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class WebActivity extends BasicActivity {
private WebView webView;
private Toolbar toolbar,ltoolBar;
private final static int SEARCH_MOHU =1;
String url,user_phonenumber;
private boolean flags=true;
//改动
private List<NewsBean.ResultBean.DataBean> list;
private ListView listView;
@SuppressLint("HandlerLeak")
private Handler searchHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
switch (msg.what){
case SEARCH_MOHU:
list = ((NewsBean) msg.obj).getResult().getData();
NewsInfoAdapter adapter = new NewsInfoAdapter(WebActivity.this,R.layout.item_layout_news,list);
listView.setVisibility(View.VISIBLE);
listView.setAdapter(adapter);
//这句很重要
adapter.notifyDataSetChanged();
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web);
//获取传递的路径
webView = (WebView) findViewById(R.id.webView);
toolbar = (Toolbar) findViewById(R.id.toolbar_webview);
ltoolBar = (Toolbar) findViewById(R.id.toolbar_webcomment);
listView = (ListView) findViewById(R.id.list_view);
//将标题栏放置最上面
findViewById(R.id.toolbar_webcomment).bringToFront();
}
@Override
protected void onStart() {
super.onStart();
url = getIntent().getStringExtra("url");
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
NewsBean.ResultBean.DataBean dataBean = list.get(position);
String url = dataBean.getUrl();
Intent intent = new Intent(getApplicationContext(),WebActivity.class);
intent.putExtra("url",url);
startActivity(intent);
}
});
//显示JavaScript页面
WebSettings settings = webView.getSettings();
webView.setWebViewClient(new WebViewClient(){
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
mDialog = DialogUtil.createLoadingDialog(WebActivity.this,"加载中...");
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view,url );
//去掉查询的数据中的头部广告
view.loadUrl("javascript:function setTop(){document.querySelector('body > div.top-wrap.gg-item.J-gg-item').style.display=\"none\";}setTop();");
webView.setVisibility(View.VISIBLE);
DialogUtil.closeDialog(mDialog);
}
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error){
//handler.cancel(); 默认的处理方式,WebView变成空白页
handler.proceed();
//handleMessage(Message msg); 其他处理
}
});
settings.setJavaScriptEnabled(true);
settings.setSupportZoom(true); //支持缩放,默认为true。是下面那个的前提。
settings.setBuiltInZoomControls(true); //设置内置的缩放控件。若为false,则该WebView不可缩放
settings.setJavaScriptCanOpenWindowsAutomatically(true);
settings.setUseWideViewPort(true);
settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
settings.setLoadWithOverviewMode(true);
/*settings.setDisplayZoomControls(false);*/
webView.loadUrl(url);
webView.setVisibility(View.INVISIBLE);
setSupportActionBar(ltoolBar);
toolbar.setTitle("简易新闻");
setSupportActionBar(toolbar);
ltoolBar.inflateMenu(R.menu.tool_webbottom);
ltoolBar.setTitle("感谢观看");
ltoolBar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem menuItem) {
switch (menuItem.getItemId()){
case R.id.news_share:
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_SUBJECT,url);
intent.setType("text/plain");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(Intent.createChooser(intent,getTitle()));
break;
case R.id.news_shoucang:
//下一步实现点击收藏功能,以及用户查看收藏功能
user_phonenumber = MyApplication.getMoublefhoneUser();
if (user_phonenumber != null){
if (flags){
flags = !flags;
Toast.makeText(WebActivity.this,"收藏成功",Toast.LENGTH_SHORT).show();
new Thread(new Runnable() {
@Override
public void run() {
Connection conn = null;
conn = (Connection) DBOpenHelper.getConn();
String uniquekey = getIntent().getStringExtra("uniquekey");
String sql = "insert into user_collect(user_phone,news_id) values(?,?)";
int i = 0;
PreparedStatement pstmt;
try {
pstmt = (PreparedStatement) conn.prepareStatement(sql);
pstmt.setString(1,user_phonenumber);
pstmt.setString(2,uniquekey);
i = pstmt.executeUpdate();
pstmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}).start();
}else {
ToastUtil.showShortToastCenter(WebActivity.this,"您已经收藏过啦");
}
} else {
Intent exitIntent = new Intent(WebActivity.this,LoginActivity.class);
exitIntent.setFlags(Intent.FLAG_ACTIVITY_NO_USER_ACTION);
startActivity(exitIntent);
}
break;
}
return true;
}
});
ActionBar actionBar = getSupportActionBar();
if (actionBar != null){
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeAsUpIndicator(R.drawable.back);
}
}
@SuppressLint("NewApi")
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.toolbar_webview,menu);
final SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
//使用自带搜索框
SearchView searchView = (SearchView) menu.findItem(R.id.news_search).getActionView();
searchView.setSubmitButtonEnabled(true);
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(final String query) {
//监听点击确定搜索的时候的输入文本是否为空
if (!TextUtils.isEmpty(query)){
new Thread(new Runnable() {
@Override
public void run() {
NewsBean newsBean = new NewsBean();
List<NewsBean.ResultBean.DataBean> dataBeanList = new ArrayList<>();
Connection conn = null;
conn = DBOpenHelper.getConn();
//查询数据库对应模糊搜索,输入大于两个文字的新闻进行模糊查询包括新闻的类别,以及新闻标题含有所输入的内容
String sql ="select title,url from news_info where match(title,category) AGAINST ('"+query+"' IN BOOLEAN MODE )ORDER BY date desc limit 10";
PreparedStatement pst;
try {
pst =(PreparedStatement) conn.prepareStatement(sql);
ResultSet rs = pst.executeQuery();
while (rs.next()){
NewsBean.ResultBean.DataBean dataBean = new NewsBean.ResultBean.DataBean();
dataBean.setTitle(rs.getString(1));
dataBean.setUrl(rs.getString(2));
dataBeanList.add(dataBean);
}
newsBean.setResult(new NewsBean.ResultBean());
newsBean.getResult().setData(dataBeanList);
pst.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
Message msg = searchHandler.obtainMessage();
msg.what = SEARCH_MOHU;
msg.obj = newsBean;
searchHandler.sendMessage(msg);
}
}).start();
}
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case android.R.id.home:
if (listView.getVisibility() ==View.VISIBLE){
listView.setVisibility(View.INVISIBLE);
}else {
Intent returnIntent = new Intent();
WebActivity.this.finish();
}
break;
case R.id.news_setting:
Toast.makeText(this,"夜间模式",Toast.LENGTH_SHORT).show();
break;
case R.id.news_feedback:
break;
default:
break;
}
return true;
}
}
好啦,本篇到此就结束啦,有问题欢迎批评指正!
下一篇Android实现加载中弹出框 简易新闻(十九)