安卓一些实用的小功能 比如侧滑 轮播 数据库

本文详细介绍了一个Android应用的开发过程,包括基类Activity的设计、HTTP请求处理、数据库操作、图片加载及适配器编写等关键环节,并实现了轮播图和列表刷新功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//常用的基类

public abstract class BaseActivity extends AppCompatActivity {
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getTolayout());
        init();
        getdata();
    }
    //获取主视图
  protected abstract  int getTolayout();
    //获取控件
    protected  abstract void init();
    //操作
    protected abstract  void getdata();
}

//常用的HttpUtilist封装

public class HttpUtils {
    private static HttpUtils httpUtils;
    private GetToJosn getToJosn;
    public static  HttpUtils getInstance(){
        if (httpUtils==null){
            httpUtils = new HttpUtils();
        }
        return httpUtils;
    }
    public void GetUrl(String url){
            Asy asy = new Asy();
            asy.execute(url);
    }
    public class Asy extends AsyncTask<String ,Void,String>{

        @Override
        protected String doInBackground(String... strings) {
            try {
                URL url = new URL(strings[0]);
             HttpURLConnection connection= (HttpURLConnection) url.openConnection();
             connection.setConnectTimeout(5000);
             connection.setReadTimeout(5000);
             if (connection.getResponseCode()==200){
                 String s = ToString(connection.getInputStream());
                 return s;
             }
            } catch (Exception e) {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            getToJosn.getjson(s);
        }
    }
    private String ToString(InputStream inputStream) {

        try {
            InputStreamReader in = new InputStreamReader(inputStream);
            BufferedReader reader = new BufferedReader(in);
            String s = "";
            StringBuilder builder = new StringBuilder();
            while((s=reader.readLine())!=null){
                builder.append(s);
            }
            return builder.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
    public interface GetToJosn{
        void getjson(String json);
    }
    public void SetTojson(GetToJosn getToJosn){
        this.getToJosn=getToJosn;
    }
}

////数据库的帮助类

public class Helper extends SQLiteOpenHelper {
    public Helper(Context context) {
        super(context, "data.db", null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table json (id Integer primary key autoincrement , title varchar(200),json TEXT)");
    }

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

    }
}

//数据库的Dao包

public class Dao  {

    private final Helper helper;
    private final SQLiteDatabase sqLiteDatabase;

    public Dao(Context context) {
        helper = new Helper(context);
        sqLiteDatabase = helper.getWritableDatabase();

    }
    public void insert(Beans beans) {
        ContentValues values = new ContentValues();
        values.put("title", beans.title);
        values.put("json", beans.json);
        sqLiteDatabase.replace("json", null, values);
    }
    public Beans select(String url){
        Beans beans =null;
        Cursor cursor = sqLiteDatabase.rawQuery("select * from json where title =?", new String[]{url});
        if (cursor.moveToNext()){
            String title = cursor.getString(cursor.getColumnIndex("title"));
            String json = cursor.getString(cursor.getColumnIndex("json"));
            beans = new Beans(title,json);
        }
        return beans;
    }
    public void delete(){

    }
    public void update(){

    }
}

//配置Application

public class Application extends android.app.Application {
    @Override
    public void onCreate() {
        super.onCreate();
        ImageLoaderConfiguration configuration = ImageLoaderUtils.getConfiguration(this);
        ImageLoader.getInstance().init(configuration);

    }
}

//轮播的适配器

public class MyImageAdapter extends PagerAdapter{
    private Context context;
    private List<ImageView> list;

    public MyImageAdapter(Context context, List<ImageView> list) {
        this.context = context;
        this.list = list;
    }

    @Override
    public int getCount() {
        return Integer.MAX_VALUE;
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view==object;
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
       ImageView imageView= list.get(position%list.size());
       imageView.setScaleType(ImageView.ScaleType.FIT_XY);
       container.addView(imageView);
        return imageView;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((View)object);
    }
}

//json适配器

public class MyJsonAdapter extends BaseAdapter{
    private Context context;
    private List<JsonBean.DataBean>list;

    public MyJsonAdapter(Context context, List<JsonBean.DataBean> list) {
        this.context = context;
        this.list = list;
    }

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

    @Override
    public Object 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) {
        Holder holder =null;
        if (convertView==null){
          convertView=  View.inflate(context, R.layout.layout,null);
          holder = new Holder();
          holder.text1=convertView.findViewById(R.id.text1);
          holder.image1=convertView.findViewById(R.id.image1);
          convertView.setTag(holder);
        }{
            holder= (Holder) convertView.getTag();
        }
        holder.text1.setText(list.get(position).getBrief());
        DisplayImageOptions options = ImageLoaderUtils.getOptions();
        ImageLoader.getInstance().displayImage(list.get(position).getMiniimg().get(0).getSrc(),holder.image1,options);
        return convertView;
    }
    public class Holder{
        private ImageView image1;
        private TextView text1;
    }
}

//撤回页面的配置

public class Frag1  extends Fragment{

    private ViewPager image_view;
    private XListView x_list;
    private int page = 5010;
    private String urls ="http://ttpc.dftoutiao.com/jsonpc/refresh?type=";
    private String path="http://www.xieast.com/api/banner.php";
    private List<ImageView> imgs=new ArrayList<>();
    private List<JsonBean.DataBean> list = new ArrayList<>();
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what==0){
                String s = (String) msg.obj;
                Gson gson = new Gson();
                ImageBean imageBean = gson.fromJson(s, ImageBean.class);
                List<ImageBean.DataBean> data = imageBean.getData();
                for (int i = 0;i<data.size();i++){
                    String img = data.get(i).getImg();
                    ImageView imageView = new ImageView(getActivity());
                    //保存地址的方法
                    DisplayImageOptions options = ImageLoaderUtils.getOptions();
                    ImageLoader.getInstance().displayImage(img,imageView,options);
                    imgs.add(imageView);
                }
                 imageAdapter = new MyImageAdapter(getActivity(),imgs);
                image_view.setAdapter(imageAdapter);
            }else{
                int i = image_view.getCurrentItem();
                i++;
                image_view.setCurrentItem(i);
                handler.sendEmptyMessageDelayed(1,2000);
            }
        }
    };
    private MyImageAdapter imageAdapter;
    private MyJsonAdapter jsonAdapter;
    private Dao dao;
    private Beans beans;

    @Override
    public View onCreateView(LayoutInflater inflater,  ViewGroup container, Bundle savedInstanceState) {
        View inflate = View.inflate(getActivity(), R.layout.frag1, null);
        //获取控件
        image_view = inflate.findViewById(R.id.image_view);
        x_list = inflate.findViewById(R.id.x_list);
        return inflate;
    }

    @Override
    public void onActivityCreated( Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        dao = new Dao(getActivity());

        ConnectivityManager  manager = (ConnectivityManager) getActivity().getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = manager.getActiveNetworkInfo();
        if (info!=null){
            //轮播
            SetLunBo();
            //设置数据
            SetData();
            Toast.makeText(getActivity(),"有网",Toast.LENGTH_SHORT).show();
        }else{
            String url =urls + page;
            Beans select = dao.select(url);
          
            if (select!=null){
                JsonBean jsonBean = SelectJson(select.json);
                List<JsonBean.DataBean> data = jsonBean.getData();
                list.addAll(data);
                jsonAdapter = new MyJsonAdapter(getActivity(),list);
                x_list.setAdapter(jsonAdapter);
            }
        }

    }

    private JsonBean SelectJson(String json) {
        Gson gson = new Gson();
        return gson.fromJson(json, JsonBean.class);

    }

    private void SetData() {
        GetData();
        x_list.setPullRefreshEnable(true);
        x_list.setPullLoadEnable(true);
        x_list.setXListViewListener(new XListView.IXListViewListener() {
            @Override
            public void onRefresh() {
                page=5010;
                GetData();
            }

            @Override
            public void onLoadMore() {
                page = page+1;
                GetData();
            }
        });
        jsonAdapter = new MyJsonAdapter(getActivity(),list);
        x_list.setAdapter(jsonAdapter);
    }

    private void GetData() {
        String url = urls+page;
        HttpUtils httpUtils = new HttpUtils();
        httpUtils.GetUrl(url);
        httpUtils.SetTojson(new HttpUtils.GetToJosn() {
            @Override
            public void getjson(String json) {
                Gson gson = new Gson();
                String replace = json.replace("null(", "").replace(")", "");
                JsonBean bean = gson.fromJson(replace, JsonBean.class);
                List<JsonBean.DataBean> data = bean.getData();
                dao.insert(new Beans(urls+page,replace));
                if (page==5010){
                    list.clear();
                }
                list.addAll(data);
                jsonAdapter.notifyDataSetChanged();
                if (page==5010){
                    x_list.stopRefresh();
                }else{
                    x_list.stopLoadMore();
                }
            }
        });
    }

    private void SetLunBo() {
        //开线程
        new Thread(){
            @Override
            public void run() {
                super.run();
                //获取地址
                try {
                    URL url = new URL(path);
                   HttpURLConnection connection= (HttpURLConnection) url.openConnection();
                   //设置反应时间
                    connection.setReadTimeout(5000);
                    connection.setConnectTimeout(5000);
                    //读取成功
                    if (connection.getResponseCode()==200){
                        //转换为字符型
                        String s = ToString(connection.getInputStream());
                        //创建一个消息
                        Message message = new Message();
                        message.what=0;
                        message.obj=s;
                        handler.sendMessage(message);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }
    //轮播转换为字符型
    private String ToString(InputStream inputStream) {

        try {
            InputStreamReader in = new InputStreamReader(inputStream);
            BufferedReader reader = new BufferedReader(in);
            String  s= "";
            StringBuilder builder = new StringBuilder();
            while((s=reader.readLine())!=null){
                builder.append(s);
            }
            return builder.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
    //获取时间

    @Override
    public void onResume() {
        super.onResume();
        handler.sendEmptyMessageDelayed(1,2000);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        handler.removeCallbacksAndMessages(null);
    }

    @Override
    public void onPause() {
        super.onPause();
        handler.removeCallbacksAndMessages(null);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值