前面功能的补充修改
修改退出账号功能
突然想起前面写的代码,发现如果自动登录后,便无法退出这个账号,在退出账号后跳转到登录界面,但是 SharedPreferences 里面的自动登录没删掉,所以又直接跳转到主页面,所以解决方法要在退出账号跳转到登录页面前把 SharedPreferences 里面的自动登录删去。
在跳转页面前加入下面这些代码
SharedPreferences sp;
SharedPreferences.Editor editor = sp.edit();
editor.remove("autologin");
editor.commit();
Intent intent = new Intent();
intent.setClass(getActivity(), login.class);
startActivity(intent);
getActivity().finish();
可以与 垃圾分类APP(二)对比一下。
增加搜索完结果
感觉搜索完展示的有点少东西,加多一个“了解更多”按钮跳转到百度网页
哈哈哈!!!
自行在布局增加一个按钮位置,然后记得在JAVA代码前面找到这个控件,然后设置点击跳转页面代码如下。
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String path = "https://www.baidu.com";
Uri uri = Uri.parse(path);
Intent intent=new Intent(Intent.ACTION_VIEW,uri);
startActivity(intent);
}
});
实现历史记录功能
存储搜索历史
本来想用数据库存的,但是本人太菜了,感觉好难,加上前面用了 SharedPreferences ,所以还是用 sp 来搞。
先加入依赖可以让字符串数组变成 Json 存储到 sp 里面
implementation 'com.google.code.gson:gson:2.8.4'
在细节界面的 Java 里面的插入物品名字的位置修改为以下代码
try {
//读取到搜索物品的名字
String name = make_the_String("name");
//讲名字放入布局中
garbage_name.setText(name);
List<String> list = new ArrayList<String>();
//从 sp 中读取数据
String tjson = sp.getString("key_hirsty",null);
if(tjson!=null){
//如果 sp 中有数据,转化为数组
Gson gson = new Gson();
list = gson.fromJson(tjson, new TypeToken<List<String>>(){}.getType());
}
//将名字存入数组然后转化存进 sp
list.add(name);
Gson gson = new Gson();
String jsonstr = gson.toJson(list);
SharedPreferences.Editor editor = sp.edit();
editor.putString("key_hirsty",jsonstr);
editor.commit();
} catch (JSONException e) {
e.printStackTrace();
}
新建一个历史记录布局
很丑勿喷,自己美化,能写出功能我就满足了
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".History"
android:orientation="vertical">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="删除历史记录"
android:id="@+id/bt_delete"
android:layout_marginLeft="280dp"
android:textColor="@color/black"
android:backgroundTint="#CCFFCC"/>
<ListView
android:layout_marginTop="20sp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/listview"/>
</LinearLayout>
建个适配器的布局 命名history_item
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/garbage_title"
android:layout_width="match_parent"
android:layout_height="80dp"
android:layout_gravity="center"
android:gravity="center"
android:text="名字"
android:textSize="25dp"
android:textColor="@color/black"
android:textStyle="bold"/>
</LinearLayout>
</LinearLayout>
建个历史布局适配器
命名为 history_adapter
package com.example.goodrubish.Garbage;
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.goodrubish.R;
import java.util.List;
public class History_adapter extends ArrayAdapter {
private int resourceId;
public History_adapter(Context context, int textViewResourceId, List<String> objects){
super(context,textViewResourceId,objects);
resourceId=textViewResourceId;
}
@Override
public View getView(int position, View convertView, ViewGroup parent){
String news_list= (String) getItem(position);
View view= LayoutInflater.from(getContext()).inflate(resourceId, parent,false);
TextView garbageTitle=(TextView)view.findViewById(R.id.history_name);
garbageTitle.setText(news_list);
return view;
}
}
历史Java代码
package com.example.goodrubish;
import androidx.appcompat.app.AppCompatActivity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import com.example.goodrubish.Garbage.History_adapter;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.util.ArrayList;
import java.util.List;
public class History extends AppCompatActivity {
private List<String> newsList=new ArrayList<>();
SharedPreferences sp;
TextView textView;
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_history);
button = findViewById(R.id.bt_delete);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//建弹窗确认用户操作
AlertDialog alertDialog = new AlertDialog.Builder(History.this).setTitle("删除历史记录")
.setMessage("是否确定删除所有历史记录:")
.setNeutralButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
SharedPreferences.Editor editor = sp.edit();
editor.remove("key_history");
editor.commit();
//假装刷新
Intent intent=new Intent();
intent.setClass(History.this, History.class);
startActivity(intent);
finish();
}
})
.setPositiveButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
}
}).create();
alertDialog.show();
}
});
init_list();
History_adapter adapter=new History_adapter(History.this, R.layout.history_item, newsList);
ListView listView=findViewById(R.id.listview);
listView.setAdapter(adapter);
}
private void init_list() {
sp = getSharedPreferences("history", Context.MODE_PRIVATE);
String tjson = sp.getString("key_history",null);
if(tjson!=null){
Gson gson = new Gson();
//将记录从尾到头倒一下顺序,这样后面搜索的记录在上面显示
List<String> newsList1=new ArrayList<>();
newsList1 = gson.fromJson(tjson, new TypeToken<List<String>>(){}.getType());
for(int i=newsList1.size()-1;i>=0;i--){
newsList.add(newsList1.get(i));
}
}else{
newsList.add("无历史记录");
}
}
}
别忘记到 我的 界面加入历史记录的按钮跳转功能
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setClass(getActivity(), History.class);
startActivity(intent);
}
});
美好的一天,收工睡觉!!!
补充
起床想了想,简单加个历史记录列表点击功能,可以直接跳转到细节页面
在 onCreate 类里面添加列表点击代码
ListView history_View=findViewById(R.id.listview);
history_View.setOnItemClickListener(new AdapterView.OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
historyname = newsList.get(i);
init_search();
}
});
再加上之前的搜索代码,然后直接跳转到细节页面,就不具体讲了,直接放全部代码
package com.example.goodrubish;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.goodrubish.API.Okhttp_work;
import com.example.goodrubish.Fragment.SearchFragment;
import com.example.goodrubish.Garbage.History_adapter;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
public class History extends AppCompatActivity {
private List<String> newsList=new ArrayList<>();
SharedPreferences sp,sp1;
TextView textView;
private Button button;
String historyname;
String url_garbage="http://api.tianapi.com/txapi/lajifenlei/index?key=8edca382d393d0c5f84996d0e8946b96&word=";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_history);
button = findViewById(R.id.bt_delete);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
AlertDialog alertDialog = new AlertDialog.Builder(History.this).setTitle("删除历史记录")
.setMessage("是否确定删除所有历史记录:")
.setNeutralButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
SharedPreferences.Editor editor = sp.edit();
editor.remove("key_history");
editor.commit();
Intent intent=new Intent();
intent.setClass(History.this, History.class);
startActivity(intent);
finish();
}
})
.setPositiveButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
}
}).create();
alertDialog.show();
}
});
init_list();
History_adapter adapter=new History_adapter(History.this, R.layout.history_item, newsList);
ListView listView=findViewById(R.id.listview);
listView.setAdapter(adapter);
ListView history_View=findViewById(R.id.listview);
history_View.setOnItemClickListener(new AdapterView.OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
historyname = newsList.get(i);
init_search();
}
});
}
private void init_list() {
sp1 = getSharedPreferences("config",Context.MODE_PRIVATE);
String name1 = sp1.getString("name",null);
sp = getSharedPreferences(name1, Context.MODE_PRIVATE);
String tjson = sp.getString("key_history",null);
if(tjson!=null){
Gson gson = new Gson();
List<String> newsList1=new ArrayList<>();
newsList1 = gson.fromJson(tjson, new TypeToken<List<String>>(){}.getType());
for(int i=newsList1.size()-1;i>=0;i--){
newsList.add(newsList1.get(i));
}
}else{
newsList.add("无历史记录");
}
}
public void init_search() {
View view = getWindow().peekDecorView();
if (view != null) {//这里是网络访问的代码,获取服务
InputMethodManager inputmanger = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputmanger.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
initData_search();
}
Handler handler_search=new Handler(new Handler.Callback() {//首先通过handler发送信息
@Override
public boolean handleMessage(@NonNull Message msg) {
switch (msg.what){
case 0:
Toast.makeText(History.this,"网络错误",Toast.LENGTH_LONG).show();
break;
case 1:
String json=(String)msg.obj;
try{
SearchFragment.Search_JSON=new JSONObject(json);
Intent intent=new Intent();
intent.setClass(History.this, Detail.class);
startActivity(intent); //进行页面跳转
finish();
break;
}catch (JSONException e){
e.printStackTrace();
}
default:
throw new IllegalStateException("Unexpected value: " + msg.what);
}
return false;
}
});
private void initData_search(){
if(TextUtils.isEmpty(historyname)){//如果内容为空,弹出toast消息,不为空则执行164行以后的代码
Toast.makeText(History.this,"跳转失败",Toast.LENGTH_SHORT).show();
}
else{
Okhttp_work.OkHttpGet(url_garbage+historyname, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String content=response.body().string();
Message message=new Message();
message.what=1;
message.obj=content;
handler_search.sendMessageDelayed(message,1000);
}
});
}
}
}
收工!!!