1. 程式人生 > >Android studio結合資料庫簡單的進行展示刪除

Android studio結合資料庫簡單的進行展示刪除

在這裡插入圖片描述
xml裡面的程式碼在這裡插入程式碼片
main裡面的程式碼

<Button android:id="@+id/get_Btn" 
android:layout_width="match_parent" 
android:layout_height="wrap_content" 
android:text="獲取資料" /> 
<ListView android:id="@+id/listView" 
android:layout_width="match_parent" 
android:layout_height="match_parent"> </ListView>

介面卡中的程式碼在這裡插入item

<TextView
    android:id="@+id/list_tv"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

主頁面中的程式碼

 import android.content.DialogInterface; 
 import android.os.AsyncTask;
 import android.os.Bundle; 
 import android.support.v7.app.AlertDialog;
 import android.support.v7.app.AppCompatActivity;
 import android.view.View;
 import android.widget.AdapterView; 
 import android.widget.Button; 
 import android.widget.ListView; 
 import com.example.adapter.MyAdapter;
 import com.example.bean.MyData; 
 import com.example.dao.MyDao; 
 import com.example.utils.MyUtils;
 import com.google.gson.Gson; 
 import java.util.ArrayList; 
 import java.util.List; 
 public class MainActivity extends AppCompatActivity implements View.OnClickListener { 
 private Button get_Btn;
 private ListView listView;
 //將網址寫入
  private String mUrl = "http://api.expoon.com/AppNews/getNewsList/type/1/p/1"; 
  private List<MyData.DataBean> lists = new ArrayList<>();
  private MyAdapter adapter;
  private MyDao dao; 
 @Override protected void onCreate(Bundle savedInstanceState) { 
 super.onCreate(savedInstanceState); 
 setContentView(R.layout.activity_main); 
 dao = new MyDao(this); initView(); 
 adapter = new MyAdapter(this, lists); 
 listView.setAdapter(adapter); 
 listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
 @Override 
 public void onItemClick(AdapterView<?> parent, View view, final int position, long id) { 
 AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); 
 builder.setTitle("刪除"); builder.setMessage("確定刪除嗎?"); 
 builder.setPositiveButton("確定", new DialogInterface.OnClickListener() {
  @Override 
  public void onClick(DialogInterface dialog, int which) { 
  String title = adapter.getDatas().get(position).getNews_title(); 
  int dele = dao.dele(title); 
  //進行判斷刪除
   if (dele>0){ 
   adapter.setDatas(dao.show());
    } } 
    });
     builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
      @Override 
      public void onClick(DialogInterface dialog, int which) {
       dialog.dismiss(); 
       } }
       );
        AlertDialog dialog = builder.create();
         dialog.show(); 
         } }
         );
          } 
   private void initView() { 
   get_Btn = (Button) findViewById(R.id.get_Btn); 
   listView = (ListView) findViewById(R.id.listView); 
   get_Btn.setOnClickListener(this); 
   }
    @Override
   public void onClick(View v) {
    switch (v.getId()) { 
    case R.id.get_Btn:
     List<MyData.DataBean> dataBeanList = dao.show();
      //進行判斷
       if (dataBeanList.size() > 0) { 
       adapter.setDatas(dataBeanList);
        } else {
         new MyTask().execute(mUrl);
          } 
          break; 
          } } 
      class MyTask extends AsyncTask<String, Void, List<MyData.DataBean>> { 
      @Override
    protected List<MyData.DataBean> doInBackground(String... strings) { 
    //建立uri 
    String json = MyUtils.getMyStrig(strings[0]); 
    Gson gson = new Gson(); 
    MyData myData = gson.fromJson(json, MyData.class); 
    return myData.getData();
     } 
     @Override
 protected void onPostExecute(List<MyData.DataBean> dataBeans) { 
      super.onPostExecute(dataBeans);
     adapter.setDatas(dataBeans);
     dao.add(dataBeans); 
        } }
         } 

封裝的介面卡

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.example.bean.MyData;
import com.example.zhoukaolianxi1.R;
import java.util.List;
public class MyAdapter extends BaseAdapter {
    private Context mContext;
    private List<MyData.DataBean> datas;
public MyAdapter(Context mContext, List<MyData.DataBean> datas) {
        this.mContext = mContext;
        this.datas = datas;
    }
 public void setDatas(List<MyData.DataBean> datas) {
        this.datas = datas;
        //重新整理介面卡
        notifyDataSetChanged();
    }
public List<MyData.DataBean> getDatas() {
        return datas;
    }
 @Override
   public int getCount() {
        return datas.size();
    }
  @Override
    public Object getItem(int position) {
        return null;
    }
  @Override
    public long getItemId(int position) {
        return 0;
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        //宣告一個holder類 
        ViewHolder holder = null;
        //進行判斷 
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = View.inflate(mContext, R.layout.item, null);
            holder.tv_list = convertView.findViewById(R.id.list_tv);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        holder.tv_list.setText(datas.get(position).getNews_title());
        return convertView;
    }
  //holder類 
    class ViewHolder {
        TextView tv_list;
    }    }    }

這裡是bean包

import java.util.List;
public class MyData {
    private int status;
    private String info;
    private List<DataBean> data;
public int getStatus() {
        return status;
    }
public void setStatus(int status) {
        this.status = status;
    }
 public String getInfo() {
        return info;
    }
  public void setInfo(String info) {
        this.info = info;
    }
 public List<DataBean> getData() {
        return data;
    }
public void setData(List<DataBean> data) {
        this.data = data;
    }
  public static class DataBean {
        private String news_id;
        private String news_title;
        private String news_summary;
        private String pic_url;
public String getNews_id() {
            return news_id;
        }
 public void setNews_id(String news_id) {
            this.news_id = news_id;
        }
public String getNews_title() {
            return news_title;
        }
 public void setNews_title(String news_title) {
            this.news_title = news_title;
        }
public String getNews_summary() {
            return news_summary;
        }
 public void setNews_summary(String news_summary) {
            this.news_summary = news_summary;
        }
public String getPic_url() {
            return pic_url;
        }
  public void setPic_url(String pic_url) {
            this.pic_url = pic_url;
        }  }
}

helper類

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class MyHelper extends SQLiteOpenHelper {
    public MyHelper(Context context) {
        super(context, "mydb", null, 1);
    }
 @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table news (title text)");
    }
 @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }
}

dao層

mport android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.example.bean.MyData;
import java.util.ArrayList;
import java.util.List;

public class MyDao {
    private SQLiteDatabase database;
 public MyDao(Context mContext) {
        MyHelper helper = new MyHelper(mContext);
        database = helper.getWritableDatabase();
    }
 public List<MyData.DataBean> show() {
        //建立一個集合 
        List<MyData.DataBean> datas = new ArrayList<MyData.DataBean>();
        Cursor qu = database.query("news", null, null, null, null, null, null, null);
        while (qu.moveToNext()) {
            String title = qu.getString(qu.getColumnIndex("title"));
            //建立一個bean包類
            MyData.DataBean dataBean = new MyData.DataBean();
            dataBean.setNews_title(title);
            datas.add(dataBean);
        }
        return datas;
    }
public void add(List<MyData.DataBean> datas) {
        //迴圈新增 
        for (int i = 0; i < datas.size(); i++) {
            ContentValues values = new ContentValues();
            values.put("title", datas.get(i).getNews_title());
            database.insert("news", null, values);
        }
    }
public int dele(String title) {
        int i = database.delete("news", "title = ? ", new String[]{title});
        return i;
    }
} 

我自己將解析資料的方法抽出來單獨封裝了一個工具類

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class MyUtils {
    public static String getMyStrig(String mUrl) {
        try {
            URL url = new URL(mUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            InputStream stream = connection.getInputStream();
            String sb = getStr(stream);
            return sb;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String getStr(InputStream stream) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
        StringBuffer sb = new StringBuffer();
        String con = "";
        while ((con = reader.readLine()) != null) {
            sb.append(con);
        }
        reader.close();
        return sb.toString();
    }
}