• (第二阶段)冲刺五


    徐利峰:

    今日完成动态的展示,遇到的困难有:图片的动态展示问题,采用的解决办法是在item布局中加入linerlayout水平布局,然后在布局中自动生成imgview来展示多个图片

    上代码:

    DongTaiActivity(上传动态文字及照片)

    package com.lh.std_everything.ui.home.hometype.dongtai;
    
    import android.content.Intent;
    import android.os.Build;
    import android.os.Bundle;
    import android.os.Handler;
    import android.os.Message;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.ProgressBar;
    import android.widget.Toast;
    
    import androidx.annotation.NonNull;
    import androidx.appcompat.app.AppCompatActivity;
    import androidx.recyclerview.widget.GridLayoutManager;
    import androidx.recyclerview.widget.RecyclerView;
    
    import com.giftedcat.easylib.selector.MultiImageSelector;
    import com.lh.std_everything.HttpUtil.HttpUtil;
    import com.lh.std_everything.MainActivity;
    import com.lh.std_everything.R;
    
    import java.io.File;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    import butterknife.BindView;
    import butterknife.ButterKnife;
    import butterknife.Unbinder;
    
    public class DongTaiActivity extends AppCompatActivity implements View.OnClickListener{
        private static final int REQUEST_IMAGE = 2;
        private int maxNum = 9;
        private Button submit;
        private EditText text;
        Unbinder unbinder;
        ProgressBar progressBar;
        @BindView(R.id.rv_images)
        RecyclerView rvImages;
        private Handler handle;
        NineGridAdapter adapter;
        private int uploadnum=0;
        private int size;
        private String urlimg;
        private List<String> select;
        List<String> mSelect;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_dong_tai);
            unbinder = ButterKnife.bind(this);
            submit=findViewById(R.id.submit);
            text=findViewById(R.id.text);
            progressBar=findViewById(R.id.progressBar);
            mSelect = new ArrayList<>();
            submit.setOnClickListener(this);
            initView();
        }
        private void initView() {
            rvImages.setLayoutManager(new GridLayoutManager(this, 3));
            adapter = new NineGridAdapter(DongTaiActivity.this, mSelect, rvImages);
            adapter.setMaxSize(maxNum);
            rvImages.setAdapter(adapter);
            adapter.setOnAddPicturesListener(new OnAddPicturesListener() {
                @Override
                public void onAdd() {
                    pickImage();
                }
            });
        }
    
        /*上传发动态的信息和照片到服务器
         */
        @Override
        public void onClick(View v) {
            switch (v.getId()){
                case R.id.submit:
                    final String daongtaitext=text.getText().toString();
                    if(daongtaitext.isEmpty()){
                        Toast.makeText(DongTaiActivity.this, "动态内容不能为空", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    String username= MainActivity.getUsername();
                    handle = new Handler(new Handler.Callback() {
                        @Override
                        public boolean handleMessage(@NonNull Message msg) {
                            switch (msg.what) {
                                case 100:
                                    if (uploadnum < size) {
                                        writeDongTaiImg(select.get(uploadnum));
                                    } else {
                                        Toast.makeText(DongTaiActivity.this, "上传成功", Toast.LENGTH_SHORT).show();
                                        progressBar.setVisibility(View.GONE);
                                    }
                                    break;
                                case 404:
                                    Toast.makeText(DongTaiActivity.this, "上传失败,您可以点击上传按钮重新上传", Toast.LENGTH_SHORT).show();
                                    progressBar.setVisibility(View.GONE);
                                    break;
                                default:
                                    break;
                            }
                            return true;
                        }
                    });
                    /*将动态写到服务器*/
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            String req="";
                            String context=text.getText().toString();
                            Log.i("输入的文本:", ""+context);
                            String url ="http://116.62.178.231:8080/BaiXiaoSheng/adddongtai?username="+ MainActivity.getUsername()+"&text="+context;
                            Log.i("url:", ""+url);
                            String msg=String.valueOf(HttpUtil.sendPost(url,req));
                            Log.d("文字上传:",msg);
                        }
                    }).start();
    
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            DongTaiActivity.this.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    progressBar.setVisibility(View.VISIBLE);
                                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                                        progressBar.setTooltipText("正在上传...");
                                    }
                                }
                            });
                            /*将图片一张一张上传到服务器*/
                            String context=text.getText().toString();
                            urlimg = "http://116.62.178.231:8080/BaiXiaoSheng/downloadimg?username="+ MainActivity.getUsername()+"&text="+context;
                            handle.sendEmptyMessage(100);
                        }
                    }).start();
            }
        }
        /*上传图片*/
        private void writeDongTaiImg(final String img) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Log.i("图片地址:", img);
                    Map<String, File> fileMap = new HashMap<String, File>();
                    fileMap.put("file", new File(img));
                    String msg = null;
                    try {
                        msg = HttpUtil.sendPostImg(urlimg, fileMap);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    uploadnum++;
                    Log.i("当前已上传照片数:", ""+uploadnum);
                    final String finalMsg = msg;
                    DongTaiActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Log.e("服务器返回信息:", ""+finalMsg);
                            if (finalMsg.equals("yes")) {
                                Log.d("tag", finalMsg);
                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                                    progressBar.setTooltipText("图片进度:" + uploadnum + "/" + size);
                                }
                                handle.sendEmptyMessage(100);
                            } else {
                                uploadnum = 0;
                                handle.sendEmptyMessage(404);
                            }
                        }
                    });
                }
            }).start();
        }
    
    
        /**
         * 选择添加图片
         */
        private void pickImage() {
            MultiImageSelector selector = MultiImageSelector.create(this);
            selector.showCamera(true);
            selector.count(maxNum);
            selector.multi();
            selector.origin(mSelect);
            selector.start(this, REQUEST_IMAGE);
        }
    
        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            if (requestCode == REQUEST_IMAGE) {
                if (resultCode == RESULT_OK) {
                    select = data.getStringArrayListExtra(MultiImageSelector.EXTRA_RESULT);
                    size=select.size()-1;
                    Log.i("照片总数:", ""+size);
                    mSelect.clear();
                    mSelect.addAll(select);
                    adapter.notifyDataSetChanged();
                }
            }
        }
    
        @Override
        protected void onDestroy() {
            super.onDestroy();
            unbinder.unbind();
        }
    
    }
    View Code

    TrendsFragment(动态展示页面)

    package com.lh.std_everything.ui.friends.type.trends;
    
    import androidx.lifecycle.Observer;
    import androidx.lifecycle.ViewModelProviders;
    
    import android.os.Bundle;
    
    import androidx.annotation.NonNull;
    import androidx.annotation.Nullable;
    import androidx.fragment.app.Fragment;
    import androidx.recyclerview.widget.LinearLayoutManager;
    import androidx.recyclerview.widget.RecyclerView;
    import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
    
    import android.os.Handler;
    import android.os.Message;
    import android.util.Log;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.Toast;
    
    import com.lh.std_everything.HttpUtil.HttpUtil;
    import com.lh.std_everything.R;
    import com.lh.std_everything.ui.home.hometype.news.adapter.NewsAdapter;
    
    import org.json.JSONArray;
    import org.json.JSONException;
    
    public class TrendsFragment extends Fragment {
    
        private TrendsViewModel mViewModel;
        private View view;
        private RecyclerView recyclerView;
        private TrendsAdapter trendsAdapter;
        private Handler handler;
        private SwipeRefreshLayout swipeRefreshLayout;
        public static TrendsFragment newInstance() {
            return new TrendsFragment();
        }
    
        @Override
        public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                                 @Nullable Bundle savedInstanceState) {
            view=inflater.inflate(R.layout.trends_fragment, container, false);
            recyclerView=view.findViewById(R.id.rec_dongtai);
            swipeRefreshLayout=view.findViewById(R.id.swiperefresh);
            return view;
        }
    
        @Override
        public void onActivityCreated(@Nullable Bundle savedInstanceState) {
            super.onActivityCreated(savedInstanceState);
            mViewModel = ViewModelProviders.of(this).get(TrendsViewModel.class);
            // TODO: Use the ViewModel
            recyclerView.setLayoutManager(new LinearLayoutManager(requireActivity()));
            trendsAdapter = new TrendsAdapter();
            recyclerView.setAdapter(trendsAdapter);
            swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
                @Override
                public void onRefresh() {
                    getThreadData();
                    Toast.makeText(view.getContext(),"刷新成功",Toast.LENGTH_LONG).show();
                }
            });
    
            mViewModel.getJsonArrayMutableLiveDate().observe(requireActivity(), new Observer<JSONArray>() {
                @Override
                public void onChanged(JSONArray jsonArray) {
                    if(swipeRefreshLayout.isRefreshing())
                        swipeRefreshLayout.setRefreshing(false);
                    trendsAdapter.setJsonArray(jsonArray);
                    trendsAdapter.notifyDataSetChanged();
                }
            });
    
            handler = new Handler(new Handler.Callback() {
                @Override
                public boolean handleMessage(@NonNull Message msg) {     //线程回调更新数据
                    if (msg.what == 200)
                        mViewModel.getJsonArrayMutableLiveDate().setValue((JSONArray) msg.obj);
                    return true;
                }
            });
            if (mViewModel.getJsonArrayMutableLiveDate().getValue() == null) {          //初始加载数据
                getThreadData();
            } else {
                trendsAdapter.setJsonArray(mViewModel.getJsonArrayMutableLiveDate().getValue());
                trendsAdapter.notifyDataSetChanged();
            }
        }
    
        private void getThreadData() {                     //线程封装网络请求
            new Thread(new Runnable() {
                @Override
                public void run() {
                    String address = "http://116.62.178.231:8080/BaiXiaoSheng/findalldongtai";
                    try {
                        final JSONArray json = new JSONArray(String.valueOf(HttpUtil.sendPost(address, "")));
                        Log.d("tag", json.toString());
                        Message msg = new Message();
                        msg.what = 200;
                        msg.obj = json;
                        handler.sendMessage(msg);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }
    View Code

    TrendsAdapter(动态适配器)

    package com.lh.std_everything.ui.friends.type.trends;
    
    import android.util.Log;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ImageView;
    import android.widget.LinearLayout;
    import android.widget.TextView;
    
    import androidx.annotation.NonNull;
    import androidx.recyclerview.widget.RecyclerView;
    
    import com.bumptech.glide.Glide;
    import com.bumptech.glide.request.RequestOptions;
    import com.lh.std_everything.R;
    import com.lh.std_everything.ui.home.hometype.news.adapter.NewsAdapter;
    
    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;
    
    public class TrendsAdapter extends RecyclerView.Adapter<TrendsAdapter.MyViewHolder> {
        JSONArray jsonArray=new JSONArray();
        private View itemview;
        public void setJsonArray(JSONArray jsonArray) {
            this.jsonArray = jsonArray;
        }
    
        @NonNull
        @Override
        public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            LayoutInflater layoutInflater=LayoutInflater.from(parent.getContext());
            itemview=layoutInflater.inflate(R.layout.dongtai_item,parent,false);
            return new TrendsAdapter.MyViewHolder(itemview);
        }
    
        @Override
        public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
            JSONObject bean= null;
            try {
                bean = jsonArray.getJSONObject(position);
                holder.tv_name.setText(bean.getString("username"));
                holder.tv_content.setText(bean.getString("content"));
                holder.tv_time.setText(bean.getString("dtime"));
                String []urls=bean.getString("imgurl").split(",");
                String userimg=bean.getString("userimg");
                RequestOptions options = new RequestOptions()
                        .error(R.drawable.error)
                        .placeholder(R.drawable.loading);
                Glide.with(itemview)
                        .load(userimg)
                        .apply(options)
                        .circleCrop()
                        .into(holder.img_user);
                holder.lin_imgs.removeAllViews();
                if(urls.length!=0) {
                    for(int i=0;i<urls.length;i++)
                    {
                        if(!urls[i].equals(""))
                        {
                            ImageView item=new ImageView(itemview.getContext());
                            Log.i("url",urls[i]);
                            Glide.with(itemview)
                                    .load(urls[i])
                                    .apply(options)
                                    .into(item);
                            Log.i("图片分割链接:", ""+urls[i]);
                            holder.lin_imgs.addView(item);
                        }
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    
        @Override
        public int getItemCount() {
            return jsonArray.length();
        }
    
    
        static class MyViewHolder extends RecyclerView.ViewHolder{
            TextView tv_name,tv_time,tv_content;
            LinearLayout lin_imgs;
            ImageView img_user;
            public MyViewHolder(@NonNull View itemView) {
                super(itemView);
                img_user=itemView.findViewById(R.id.img_user);
                tv_name=itemView.findViewById(R.id.tv_name);
                tv_content=itemView.findViewById(R.id.tv_content);
                tv_time=itemView.findViewById(R.id.tv_time);
                lin_imgs=itemView.findViewById(R.id.lin_imgs);
            }
        }
    }
    View Code

    服务器端:

    dongtaidao(服务器存储一条动态信息,查找所有动态信息)

    package Dao;
    
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    import java.util.ArrayList;
    
    import Bean.Dongtai;
    import Bean.News;
    import Bean.User;
    import util.DBUtil;
    
    public class dongtaidao {
        public boolean adddongtai(String username,String text,String userimg,String dtime)
        {
                Connection con=null;
                PreparedStatement pstmt=null;
                ResultSet rs=null;
                try {
                    con=DBUtil.getConn();
                    String sql="insert into dongtai(username,content,imgurl,userimg,dtime) values(?,?,?,?,?)";
                    pstmt=con.prepareStatement(sql);
                    pstmt.setString(1, username);
                    pstmt.setString(2, text);
                    pstmt.setString(3, "");
                    pstmt.setString(4, userimg);
                    pstmt.setString(5, dtime);
                    pstmt.executeUpdate();
                    return true;
                }
                catch (SQLException e) {
                    System.out.println("录入失败");
                    e.printStackTrace();
                }
                finally {
                    DBUtil.close(rs, pstmt, con);
                }
                return false;
        }
        public String findcurrenurl(String username,String text)
        {
            String sql="select * from dongtai where username='"+username+"'and content='"+text+"'";
            Connection con=null;
            Statement state=null;
            ResultSet rs=null;
            con=DBUtil.getConn();
            String urlString="";
            try {
                state=con.createStatement();
                rs=state.executeQuery(sql);
                while(rs.next())
                {
                    urlString=rs.getString("imgurl");
                    return urlString;
                }
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            DBUtil.close(rs, state, con);
            return "";
        }
        public boolean updateurls(String username,String text,String currenturl)
        {
            Connection con=null;
            PreparedStatement pstmt=null;
            ResultSet rs=null;
            try {
                con=DBUtil.getConn();
                String sql="update dongtai set imgurl=? where content=?";
                pstmt=con.prepareStatement(sql);
                pstmt.setString(1, currenturl);
                pstmt.setString(2, text);
                pstmt.executeUpdate();
                return true;
            }
            catch (SQLException e) {
                System.out.println("更新失败");
                e.printStackTrace();
            }
            finally {
                DBUtil.close(rs, pstmt, con);
            }
            return false;
        }
        public ArrayList<Dongtai> getall()
        {
            ArrayList<Dongtai> list=new ArrayList<>();
            String sql="select * from dongtai order by dtime desc";
            Connection con=null;
            Statement state=null;
            ResultSet rs=null;
            con=DBUtil.getConn();
            Dongtai bean=null;
            try {
                state=con.createStatement();
                rs=state.executeQuery(sql);
                while(rs.next())
                {
                    String username=rs.getString("username");
                    String content=rs.getString("content");
                    String imgurl=rs.getString("imgurl");
                    String userimg=rs.getString("userimg");
                    String dtime=rs.getString("dtime");
                    bean=new Dongtai(username, content, imgurl,userimg,dtime);
                    list.add(bean);
                }
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            DBUtil.close(rs, state, con);
            return list;
        }
    }
    View Code

    图片展示:

    李浩:

    完成“我的博客“点击事件,可以展示列表:

    效果图:

    明日任务:完成博客的删除功能。

  • 相关阅读:
    开源高性能网络库Libevent的简介
    网络IO之阻塞、非阻塞、同步、异步总结【转】
    C语言20150620
    EF那点事
    SSO单点登录的实现原理是怎样的
    SQL索引器
    基础数学知识
    hibernate优化笔记(随时更新)
    JAVA中保留小数的多种方法
    Hibernate的session缓存和对象的四种状态
  • 原文地址:https://www.cnblogs.com/xlk3/p/12945194.html
Copyright © 2020-2023  润新知