1. 程式人生 > >多條目資料庫展示

多條目資料庫展示

activityXML中的程式碼:

	<ListView
        android:id="@+id/listview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"></ListView>

tt_itemXML中的程式碼:

<TextView
        android:id="@+id/title"
        android:layout_width="150dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:maxLines="2"
        android:text="標題"
        android:layout_marginRight="150dp"
        android:textSize="17sp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/date"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="日期"
        app:layout_constraintTop_toBottomOf="@+id/title"
        tools:layout_editor_absoluteX="0dp"
        tools:ignore="MissingConstraints" />

gg_itemXML中的程式碼:

<TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="16dp"
        android:text="TextView"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/date"
        android:layout_width="wrap_content"
        android:layout_height="17dp"
        android:layout_marginTop="24dp"
        android:text="TextView"
        app:layout_constraintTop_toBottomOf="@+id/title"
        tools:ignore="MissingConstraints"
        tools:layout_editor_absoluteX="8dp" />

    <ImageView
        android:id="@+id/image"
        android:layout_width="70dp"
        android:layout_height="70dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:srcCompat="@tools:sample/avatars" />

Bean中的程式碼:

public Result result;

    public Result getRestult() {
        return result;
    }

    class Result{
        public List<Data> data;

        public List<Data> getData() {
            return data;
        }
    }
    class Data{
    	//判斷的資料
        private final String panduan="頭條";
        public String title;
        public String date;
        public String category;
        public String thumbnail_pic_s;
        public String utl;

        public String getTitle() {
            return title;
        }

        public String getDate() {
            return date;
        }

        public String getCategory() {
            return category;
        }

        public 大String getThumbnail_pic_s() {
            return thumbnail_pic_s;
        }

        public String getUtl() {
            return utl;
        }
        //進行判斷
        public boolean panduan(){
            return category.equals(panduan);
        }
    }

工具類中的程式碼:

	//執行get請求  返回string結果
    public static String zhixing(String lujing){
        String result="";
        try {
            //定義ur地址
            URL url=new URL(lujing);
            //開啟連線
            HttpURLConnection urlConnection= (HttpURLConnection) url.openConnection();
            //請求方法
            urlConnection.setRequestMethod("GET");
            //讀取超時
            urlConnection.setReadTimeout(5000);
            //連線超時
            urlConnection.setConnectTimeout(5000);
            //獲取狀態值
            int responseCode = urlConnection.getResponseCode();
            if (responseCode==200){
                result=zifu(urlConnection.getInputStream());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    //位元組流轉換為字元流
    private static String zifu(InputStream inputStream) throws IOException {
        InputStreamReader inputStreamReader=new InputStreamReader(inputStream);
        BufferedReader buff =new BufferedReader(inputStreamReader);
        StringBuilder builder=new StringBuilder();
        for (String imp=buff.readLine();imp!=null;imp=buff.readLine()){
            builder.append(imp);
        }
        return builder.toString();

    }

介面卡中的程式碼:

private List<Bean.Data> list;
    private Context context;
    private final int VIEW_COUNT=2;
    private final int TT_VIEW=0;
    private final int GN_VIEW=1;
    //v子佈局的型別數量
    @Override
    public int getViewTypeCount() {
        return VIEW_COUNT;
    }
    //判斷使用哪種子佈局
    @Override
    public int getItemViewType(int position) {
        return getItem(position).ispan()? TT_VIEW:GN_VIEW;
    }

    public Mybase(Context context) {
        this.context = context;
        list=new ArrayList<>();
    }

    public void setList(List<Bean.Data> list) {
        this.list = list;
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Bean.Data getItem(int position) {
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        
        if (convertView==null){

            //載入子佈局
            convertView=LayoutInflater.from(context).inflate(
                    getItemViewType(position)==TT_VIEW?R.layout.tt_item:R.layout.gn_item
                    ,parent,false);
            holder=new ViewHolder(convertView);
            convertView.setTag(holder);
        }else{
            holder= (ViewHolder) convertView.getTag();
        }
        holder.ccc(getItem(position));
        return convertView;
    }
    class ViewHolder{
        private TextView title;
        private TextView date;
        private ImageView image;
        //獲取子佈局資源ID
        public ViewHolder(View convertView) {
            title= convertView.findViewById(R.id.title);
            date=convertView.findViewById(R.id.date);
            image=convertView.findViewById(R.id.image);
        }
        //寫入
        public void ccc(Bean.Data item) {
            title.setText(item.getTitle());
            date.setText(item.getDate());
            if (image!=null){
                image.setImageResource(R.mipmap.ic_launcher);
            }
        }
    }

資料庫中的程式碼:

public SqliteHelper(Context context) {
        super(context, "User.db", null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table users (id integer primary key autoincrement," +
                "title text," +
                "date text," +
                "category text)");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

dao層的程式碼:

	private SqliteHelper helper;
    private SQLiteDatabase sb;
    public Dao(Context context){
        helper=new SqliteHelper(context);
        sb=helper.getReadableDatabase();
    }
    public void zeng(Bean.Data data){
        ContentValues values=new ContentValues();
        values.put("title",data.getTitle());
        values.put("date",data.getDate());
        values.put("category",data.getCategory());
        sb.insert("users",null,values);
    }
    public List<Bean.Data> cha(){
        List<Bean.Data> list=new ArrayList<>();
        Cursor query = sb.query("users", null, null, null, null, null, null);
        while(query.moveToNext()){
            String title = query.getString(query.getColumnIndex("title"));
            String date = query.getString(query.getColumnIndex("date"));
            String category = query.getString(query.getColumnIndex("category"));
            Bean.Data data=new Bean.Data(title,date,category);
            list.add(data);
        }
        return list;
    }
    public  void shan(){
        sb.delete("users",null,null);
    }

Activity中的程式碼:

	private ListView listView;
    private Dao dao;
    private Mybase mybase;
    private String lujing1="http://result.eolinker.com/k2BaduF2a6caa275f395919a66ab1dfe4b584cc60685573?uri=tt";
    private String lujing2="http://result.eolinker.com/k2BaduF2a6caa275f395919a66ab1dfe4b584cc60685573?uri=gn";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView = findViewById(R.id.listview);
        dao=new Dao(this);
        mybase=new Mybase(this);
        listView.setAdapter(mybase);
        getdata();
    }

    private void getdata() {
        @SuppressLint("StaticFieldLeak") AsyncTask<String,Void,List<Bean.Data>> asyncTask=new AsyncTask<String, Void, List<Bean.Data>>() {
            @Override
            protected List<Bean.Data> doInBackground(String... strings) {
                List<Bean.Data> list=new ArrayList<>();
                dao.shan();
                for(String url : strings){
                    String jieguo = NetUtil.zhixing(url);
                    Bean bean = new Gson().fromJson(jieguo, Bean.class);
                    List<Bean.Data> data = bean.getResult().getData();

                    for (int i=0;i<data.size();i++){
                        String title = data.get(i).getTitle();
                        String date = data.get(i).getDate();
                        String category = data.get(i).getCategory();
                        Bean.Data dd=new Bean.Data(title,date,category);
                        dao.zeng(dd);

                    }
            }
                List<Bean.Data> cha = dao.cha();
                //使集合裡的資料亂序
                Collections.shuffle(cha);
                return cha;
            }

            @Override
            protected void onPostExecute(List<Bean.Data> data) {
                mybase.setList(data);
            }
        }.execute(lujing1,lujing2);
    }