记录安卓开发,常用的功能

一、首先是我们安卓开发常用到的SQLite,存个本地,这里直接上代码,简单快捷

1、先建一个库、建个表

package com.example.myapplication.util;

import android.content.Context;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

public class DBOpenHelp extends SQLiteOpenHelper {
    //定义数据库名字
    private static final String name = "android.db";
    public DBOpenHelp(@Nullable Context context) {
        super(context, name, null, 1);

    }


    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        //创建数据表(没有就新建,有就不建)
        sqLiteDatabase.execSQL("CREATE TABLE IF NOT EXISTS cart_tb(id integer primary key autoincrement,name char(10),price float,num int ,img int)");

    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

    }
}

2、具体应用(简单实现对单表的操作)

package com.example.myapplication.util;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.example.myapplication.domain.Goods;

import java.util.ArrayList;
import java.util.List;

/*
* 操作购物车数据表
* */
public class CartDBService {
    private DBOpenHelp dbOpenHelp;
    private static final String TABLE_NAME="cart_tb";
    public CartDBService(Context context){
        dbOpenHelp = new DBOpenHelp(context);
    }

    //添加商品到购物车表
    public void addGoods(Goods goods){
        //打开数据库
        SQLiteDatabase sqLiteDatabase = dbOpenHelp.getWritableDatabase();
        //将商品信息添加到SQLite购物车表中
        ContentValues contentValues = new ContentValues();
        contentValues.put("name",goods.getName());
        contentValues.put("price",goods.getPrice());
        contentValues.put("num",goods.getNum());
        contentValues.put("img",goods.getImg());
        //存入数据
        sqLiteDatabase.insert(TABLE_NAME,null,contentValues);
        //关闭数据库
        sqLiteDatabase.close();
    }

    //获取商品到购物车列表
    @SuppressLint("Range")
    public List<Goods> getGoods(){
        List<Goods> goodsList = new ArrayList<>();
        //打开数据库
        SQLiteDatabase sqLiteDatabase = dbOpenHelp.getWritableDatabase();
        String sql = " select * from cart_tb";
        Cursor cursor = sqLiteDatabase.rawQuery(sql, null);
        while(cursor.moveToNext()){
            Goods goods = new Goods();
            int id = Integer.parseInt(cursor.getString(cursor.getColumnIndex("id")));
            String name = cursor.getString(cursor.getColumnIndex("name"));
            float price = Float.parseFloat(cursor.getString(cursor.getColumnIndex("price")));
            int num = Integer.parseInt(cursor.getString(cursor.getColumnIndex("num")));
            int img = Integer.parseInt(cursor.getString(cursor.getColumnIndex("img")));
            goods.setId(id);
            goods.setNum(num);
            goods.setName(name);
            goods.setPrice(price);
            goods.setImg(img);
            goodsList.add(goods);
        }

        //关闭数据库
        sqLiteDatabase.close();
        return goodsList;
    }

    public void delete(String id){
        //打开数据库
        SQLiteDatabase sqLiteDatabase = dbOpenHelp.getWritableDatabase();


        sqLiteDatabase.delete("cart_tb", " id = ? ", new String[]{id});
    }
}

二、远程调用接口

1、直接放个轮子,返回数据一般都是json格式的字符串。

package com.example.myapplication.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.io.IOException;
import java.util.Map;

import okhttp3.*;

public class NetworkUtil {
    /*
     * @Description:
     * @param method 访问方式
     * @param url   访问url地址
     * @param json_parameter 传递的参数
     * @param json_header  设置的请求头
     * @return: java.lang.String  返回值
     * @Author: mengke
     * @Date: 2022/9/23 14:03
     */
    public static String UseNetWork(String method, String url, String json_parameter, String json_header) {
        //返回数据
        String Data = "";


        //添加需要传输的数据=======开始=======
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody requestBody = null;
        if (json_parameter != null && !(json_parameter.isEmpty())) {
            requestBody = RequestBody.create(mediaType, String.valueOf(json_parameter));
        }
        //添加需要传输的数据=======结束=======
        //添加请求头数据=======开始=======
        Headers headers = null;
        if (json_header != null && !(json_header.isEmpty())) {
            headers = setHeaderParams_json(json_header);
        }
        //添加请求头数据=======结束=======

        //发送请求=========
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .headers(headers)
                .url(url)
                .method(method, requestBody)
                .build();
        Response response = null;
        try {
            response = client.newCall(request).execute();
            Data = response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Data;
    }
    /**
     * @param headerParams   批量设置请求头参数     数组格式
     * @return
     */
    private static Headers setHeaderParams_Array(String[] headerParams) {
        Headers headers = null;
        Headers.Builder headersbuilder = new Headers.Builder();
        if (headerParams != null && headerParams.length > 0) {
            for (int i = 0; i < headerParams.length; i++) {
                if ((headerParams[i].split(":")[0]) != null && !(headerParams[i].split(":")[0]).isEmpty()) {
                    //如果参数不是null并且不是"",就拼接起来
                    headersbuilder.add(headerParams[i].split(":")[0], headerParams[i].split(":")[1]);
                }
            }
        }
        headers = headersbuilder.build();
        return headers;
    }
    //批量设置请求头参数     json格式
    //例子:String headerParams="{\"Name\":\"strinrrgggggg\",\"Images\":\"737472696e67626565656565656565656572\"}";
    private static Headers setHeaderParams_json(String headerParams){
        Headers headers = null;
        Headers.Builder headersbuilder = new Headers.Builder();
        if (headerParams != null && !(headerParams.isEmpty())) {
            JSONObject jsonObject = JSON.parseObject(headerParams);
            for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
                Object o = entry.getValue();
                if (o instanceof String) {
                    System.out.println("key:" + entry.getKey() + ",value:" + entry.getValue());
                    if ((entry.getKey()) != null && !((entry.getKey()).isEmpty())) {
                        //如果参数不是null并且不是"",就拼接起来
                        headersbuilder.add(entry.getKey().toString(), entry.getValue().toString());
                    }
                } else {
                    System.out.println("输出错误==============");
                }
            }
        }
        headers = headersbuilder.build();
        return headers;
    }
}

2、轮子的使用方法

new Thread(){
    @Override
    public void run(){
        //查询数据库封装数据
        //把要联网的代码放在这里
        Log.i("123","http://"+ip+"/goods/selectByType?type="+i+"");
        String data = NetworkUtil.UseNetWork("get","http://"+ip+"/goods/selectByType?type="+i+"","","{}");
        Log.i("123",data.toString());
        List<Goods1> list = new ArrayList<Goods1>();
        List<Goods1> goods1List = parseArray(data,Goods1.class);
        Log.i("123",goods1List.toString());
        goods = new String[goods1List.size()];
        price = new String[goods1List.size()];
        info = new String[goods1List.size()];
        images = new String[goods1List.size()];
        for(int i=0;i<goods1List.size();i++){
            goods[i] = goods1List.get(i).getTitle();
            price[i] = goods1List.get(i).getPrivice();
            info[i] = goods1List.get(i).getContent();
            images[i] = goods1List.get(i).getPictureid();
        }
        //定义数据
    }
}.start();
try {
    Thread.currentThread().sleep(1000);
} catch (InterruptedException e) {
    e.printStackTrace();
}

 

三、Gson的使用

package com.hsun.json;
    /**
     * Person 实体类
     * @author hsun
     *
     */
    public class Person {
        private int id;
        private String name;
        private int age;

        public int getId() {
            return id;
        }
        public void setId(int id) {
            this.id = id;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public int getAge() {
            return age;
        }
        public void setAge(int age) {
            this.age = age;
        }

        @Override
        public String toString() {
            return "Person [id=" + id + ", 姓名=" + name + ", 年龄=" + age + "]";
        }
    }

1、将对象转换未json格式字符串      

 Gson gs = new Gson();

        Person person = new Person();
        person.setId(1);
        person.setName("我是酱油");
        person.setAge(24);

        String objectStr = gs.toJson(person);//把对象转为JSON格式的字符串
        System.out.println("把对象转为JSON格式的字符串///  "+objectStr);

2、把List转为JSON格式的字符串

        Gson gs = new Gson();

        List<Person> persons = new ArrayList<Person>();
        for (int i = 0; i < 10; i++) {//初始化测试数据
            Person ps = new Person();
            ps.setId(i);
            ps.setName("我是第"+i+"个");
            ps.setAge(i+10);
            persons.add(ps);
        }

        String listStr = gs.toJson(persons);//把List转为JSON格式的字符串
        System.out.println("把list转为JSON格式的字符串///  "+listStr);

3、json字符串转对象

成员变量

private Gson gson = new GsonBuilder()
            .registerTypeAdapter(Date.class, (JsonDeserializer<Date>) (json, typeOfT, context) -> new Date(json.getAsJsonPrimitive().getAsLong()))
            .registerTypeAdapter(Date.class, (JsonSerializer<Date>) (date, type, jsonSerializationContext) -> new JsonPrimitive(date.getTime()))
            .create();

 

json串转实体类对象

//jsonStr 为json字符串
Pessoais pessoais = gson.fromJson(jsonStr, Pessoais.class);
 

引导页面

装载需要滑动的图片的ViewPager

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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=".MainActivity">

    <!--在我们的android中引导界面的制作的话就是会用到我们的viewpager控件
     现在的话使用我们的界面布局的方式来实现我们的引导界面
    -->

    <androidx.viewpager.widget.ViewPager
        android:id="@+id/Viewpager"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />

</RelativeLayout>

这是需要展示的引导页的Activity

package com.example.myapplication;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;

import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;


import com.example.myapplication.activity.HomeActivity;
import com.example.myapplication.fragment.Fragment1;
import com.example.myapplication.fragment.Fragment2;
import com.example.myapplication.fragment.Fragment3;
import com.example.myapplication.fragment.Fragment4;
import com.example.myapplication.fragment.Fragment5;

import java.util.ArrayList;
import java.util.List;


public class MainActivity extends AppCompatActivity {

    private List<Fragment> fragments;
    private Button tiyan;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //我们的fragment的话主要是我们的碎片使用我们的碎片化的管理方式
        /*
         * 第一步的话就是找到我们的viewpager控件
         * */
        //创建一个容器这个容器的话就是我们的Arraylist将我们的所有的图片都添加进去,然后的话转化成我们的成员变量
        fragments = new ArrayList<>();
        fragments.add(new Fragment1());
        fragments.add(new Fragment2());
        fragments.add(new Fragment3());
        fragments.add(new Fragment4());
        fragments.add(new Fragment5());
        ViewPager viewPager = (ViewPager) findViewById(R.id.Viewpager);
        /*
         * 第二步就是添加我们的适配器
         * */
        FragAdapter adapter = new FragAdapter(getSupportFragmentManager());
        //设定我们的适配器
        viewPager.setAdapter(adapter);


    }
    public class FragAdapter extends FragmentPagerAdapter{

        public FragAdapter(@NonNull FragmentManager fm) {
            super(fm);
        }

        @NonNull
        @Override
        public Fragment getItem(int position) {
            //通过我们的一个position到我们的集合当中获取对应的数据
            return fragments.get(position);
        }

        @Override
        public int getCount() {
            //返回数据集合中的fragment的size
            return fragments.size();
        }
    }
}


下面fragment2依次类推

package com.example.myapplication.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.example.myapplication.R;


public class Fragment1 extends Fragment {
    //在我们的fragment碎片化管理的话就是会经常的使用到我们的一个方法就是我们的oncrreatview方法

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment1,container,false);
        return view;
    }
}

fragement1的xml页面

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:background="@drawable/yindao1"
    android:layout_height="match_parent">
    <!--在这个位置的话由于我们的引导界面是一张图片所以的话就是将我们的图片作为我们的背景放进去-->
</LinearLayout>
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值