Android客服端与服务器交互,实现图片上传,保存用户ID,信息,图片路径存储到数据库,
展示所有信息都客服端以list view 形式显示!
环境 eclipse ,Androidstudio, JDK 1.8.1, jre1.8.1 ,tomcat 9.0 ;
工具 okhttp, fastjson , MySQL;
图一,
tuy
第一步如图一所示,新建xml布局,获取 EditText里的值,新开一个线程,通过okhttp发送到服务器:
//得到通信
OkHttpClient client= new OkHttpClient();
//设置编码格式
MediaType JSON1 =MediaType.parse("application/json;charset=utf-8");
//传输对象 username (用户名)
RequestBodyrequestBody = RequestBody.create(JSON1, username);
//发送的地址(Yonhu)Servlet发送方式post
Request request = new Request.Builder().url("http://192.168.0.140:8080/HttpClientDemo1/Yonghu").post(requestBody).build();
//得到返回值
Response response =response = client.newCall(request).execute();
服务器接收到数据,进入数据库查询,如有此数据返回客服端false;否 存入数据库 反会true:
//新建Servlet post方法中
//得到发送过来的值
InputStream inputStream = request.getInputStream();
//转为编码格式为utf-8的字符串
String username = IOUtils.toString(inputStream, "utf-8");
然后获取数据库连接,执行SQL语句,得到想要的查询结果,返回给客服端!
最好使用fastjson list= JSON.toJSONString (“想要返回的值”);
PrintWriter out = response.getWriter();
//返回的值
Out.print(“list”)
线程里得到返回值,发送给Message 判断true 与false ,如过true 进行下一步,否则显示账号存在!
图二
第一步成功过后 ,跳转到此页面,传过来前面用户的id,打开相册照片选取功能:
Intent albumIntent = new Intent(Intent.ACTION_PICK, null); albumIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*"); startActivityForResult(albumIntent,0);
使用有返回值的Intent 方法,返回图片信息!
//内容解析器 ContentResolver resolver = getContentResolver(); try { InputStream inputStream = resolver.openInputStream(data.getData()); //bitmap 就是那张图片 bitmap = BitmapFactory.decodeStream(inputStream); ImageView imageView; imageView = (ImageView) findViewById(R.id.imageView2); imageView.setImageBitmap(bitmap);
这样把得到的图片 显示在当前页面!
当点击提交按钮的是后要对图片进行一系列操作,
File dir = new File(Environment.getExternalStorageDirectory().getPath() + "/campus_trading/");
将图片保存到本地文件夹!
final File file = new File(Environment.getExternalStorageDirectory().getPath() + "/campus_trading/" + id + ".png");
得到路径 和 设置保存的名字!
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream( file)); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
把文件转成输出流 ,压缩!
OkHttpClient client = new OkHttpClient(); //多段体形式。。。。。添加表单数据。。。。。。。。。。。。。。。。。。请求体 MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("pic", 0+ ".png", RequestBody.create(PNG, file)); RequestBody requestBody = builder.build(); Request request = new Request.Builder().url("http://192.168.0.140:8080/HttpClientDemo1/Upload").post(requestBody).build();
if(response.isSuccessful()){ file1= response.body().string();
把图片发送个服务器保存!并返回路径!file1!
服务器端写法:
第一个用户验证的Servlet 里得到username 的数据 把这个数据存入到application中去
在第二个得到 前保存的值!(详细写法下方问题一!)得到值过后更改数据库,把图片路径
UPDATE 进去!
第三步 把信息都发送到第3个Aactivity 中显示出来:
String userjson = intent.getStringExtra("a3"); User u2 = JSON.parseObject(userjson,User.class);
获取发送过来的数据 并转为User对象!
然后设置显示!
第四步 获取全部信息,并以listview形式显示出来!
OkHttpClient client = new OkHttpClient(); MediaType JSON1 = MediaType.parse("application/json; charset=utf-8"); RequestBody requestBody = RequestBody.create(JSON1, "wolaile"); Request request = new Request.Builder().url("http://192.168.0.140:8080/HttpClientDemo1/Tupain").post(requestBody).build(); Response response = null; try { response = client.newCall(request).execute(); String name= response.body().string(); String na=name.substring(name.indexOf('['),name.indexOf(']')+1);
Listuser=JSON.parseArray(na , User.class);
查询数据库里面的所有数据,并转字符json 为List 返回;
womap.setList(usermap); Log.i("info","__________________________9630___________________"+womap.getList().size()); msg.what=1; Bundle bundle=new Bundle(); //bundle.putString("user",usermap); bundle.putSerializable("map",womap); msg.setData(bundle);
myHandiler2.sendMessage(msg);
得到返回值 ,组装对象,放入message 中 进行操作!
Womap是一个 对象里面的成员变量是List;
myHandiler2 是一个类名!
MyAdapter l1.setAdapter(new MyAdapter(Main4Activity.this, womap.getList));
将List 发送给MyAdapter里面
public class MyAdapter extends BaseAdapter { private ListuserList; private LayoutInflater mIflater; public MyAdapter(Context context,List userList){ this.userList=userList; mIflater = LayoutInflater.from(context); } @Override public int getCount() { return userList.size(); } @Override public Object getItem(int i) { return userList.get(i); } @Override public long getItemId(int i) { return i; } @Override public View getView(int i, View view, ViewGroup viewGroup) { ViewHolder viewHolder = null; if (view == null){ viewHolder = new ViewHolder(); view = mIflater.inflate(R.layout.item,null); viewHolder.v1 = (ImageView) view.findViewById(R.id.imageView100); viewHolder.t1 = (TextView) view.findViewById(R.id.textView99); viewHolder.t2 = (TextView) view.findViewById(R.id.textView98); viewHolder.t3 = (TextView) view.findViewById(R.id.textView97); view.setTag(viewHolder); }else { viewHolder = (ViewHolder) view.getTag(); } // viewHolder.v1.setImageResource(R.drawable.qwq); viewHolder.t1.setText(userList.get(i).getUsername()); viewHolder.t2.setText(userList.get(i).getAge()+""); viewHolder.t3.setText(userList.get(i).getBumen()); Picasso.with(Main4Activity.this).load("http://"+userList.get(i).getPath()).error(R.drawable.qwq).into(viewHolder.v1); return view; } class ViewHolder{ public TextView t1,t2,t3; public ImageView v1; } }
将 发送过来的List 用Listview显示出来!
1:如和让 Servlet 与Servlet 之间传值!
ServletContextapplication=this.getServletContext();
//传值过去
application.setAttribute("username",username);
//取值
ServletContextapplication=this.getServletContext();
Object obj =application.getAttribute("username");
2:服务器 图片路径存储:
@MultipartConfig(
)
//存储到当前项目的imger目录下
part.write(getServletContext().getRealPath("/imger") + "/" + username+".png") ;
3:SQL 语句的拼写:
注意SQL语句的拼写;写完SQL语句 打印出来 ,放到数据库中运行一下,引号等都需要注意!
4:fastjson 的解析!
前面通过fastjson解析一直没报错 ,后面传回来的整张表却报了错,不能正确的解析!原因是应为传回来的json字符串多了几个字符,所有传回来后 应该Log 出来看下,是不是正确的json格式!
5.注意编码格式!
1. public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
2. //获取通信
3. OkHttpClient client = new OkHttpClient();
4. String post(String url, String json) throws IOException {
5. //设置请求类型
6. RequestBody body = RequestBody.create(JSON, json);
7. Request request = new Request.Builder()
8. //请求地址
9. .url(url)
10. //请求体
11. .post(body)
12. .build();
13. //获取返回值
14. Response response = client.newCall(request).execute();
15. f (response.isSuccessful()) {
16. return response.body().string();
17. } else {
18. throw new IOException("Unexpected code " + response);
19. }
20. }
1. // 转换成对象
2. String jsonstring = "{\"a\":51,\"b\":0}";
3. Usa u1 = JSON.parseObject(jsonstring, new TypeReference
4. Usa u2 = JSON.parseObject(jsonstring,Usa.class);
5. // 转换成对象数组
6. String jsonstring2 = "[{\"a\":51,\"b\":0}]";
7. Usa[] usa2 = JSON.parseObject(jsonstring2, new TypeReference
8. List list = Arrays.asList(usa2);
9. // 转换成ArrayList
10. ArrayList
11.
12. // 转换成ArrayList(默认) list3 与 list4 效果相同
13. ArrayList
14. ArrayList
15. for (int i = 0; i < list4.size(); i++) { // 推荐用这个
16. JSONObject io = list4.get(i);
17. System.out.println(io.get("a") + "======adn====="+io.get("b"));
18. }
19. }
20. }
json字符串 直接转换成List
查看文本打印
1. ArrayList
或者转换成对象数组
Usa[]usa2 = JSON.parseObject(jsonstring2, new TypeReference
对象数组转List
Listlist = Arrays.asList(usa2);
调用此类的构造方法,传如参数!我传的是一个User对象集合!
public class MyAdapter extends BaseAdapter{
private List
private LayoutInflater mIflater;
public MyAdapter(Contextcontext,List
mIflater =LayoutInflater.from(context);
}
//集合userlist的长度!
@Override
public int getCount() {
return userList.size();
}
//第几条数据
@Override
public ObjectgetItem(int i) {
return userList.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public ViewgetView(int i, View view, ViewGroup viewGroup) {
ViewHolder viewHolder = null;
if (view == null){
viewHolder = new ViewHolder();
view = mIflater.inflate(R.layout.item,null);
//给listview 显示!
viewHolder.v1 =(ImageView) view.findViewById(R.id.imageView100);
viewHolder.t1 = (TextView) view.findViewById(R.id.textView99);
viewHolder.t2 = (TextView) view.findViewById(R.id.textView98);
viewHolder.t3 = (TextView) view.findViewById(R.id.textView97);
view.setTag(viewHolder);
}else{
viewHolder = (ViewHolder)view.getTag();
}
// viewHolder.v1.setImageResource(R.drawable.qwq);
viewHolder.t1.setText(userList.get(i).getUsername());
viewHolder.t2.setText(userList.get(i).getAge()+"");
viewHolder.t3.setText(userList.get(i).getBumen());
Picasso.with(Main4Activity.this).load("http://"+userList.get(i).getPath()).error(R.drawable.qwq).into(viewHolder.v1);
return view;
}
class ViewHolder{
public TextViewt1,t2,t3;
public ImageView v1;
}
}
//毕加索使用
//显示的activity //图片路径 //失败是显示的图片
Picasso.with(Main4Activity.this).load("http://"+userList.get(i).getPath()).error(R.drawable.
/显示的imageView
qwq).into(viewHolder.v1);
//毕加索android studio 架包导入compile 'com.squareup.picasso:picasso:2.5.2'
其他使用方法:
1.适配器的下载
自动识别适配器并且重用,取消之前的下载任务。
[java] view plain copy
1. @Override public void getView(int position, View convertView, ViewGroup parent) {
2. SquaredImageView view = (SquaredImageView) convertView;
3. if (view == null) {
4. view = new SquaredImageView(context);
5. }
6. String url = getItem(position);
7.
8. Picasso.with(context).load(url).into(view);
9. }
2.图形的转换
转换图片来更好的适应布局,并且减少内存
1. Picasso.with(context)
2. .load(url)
3. .resize(50, 50)
4. .centerCrop()
5. .into(imageView)
你还可以自定义更先进的转换方法
1. public class CropSquareTransformation implements Transformation {
2. @Override public Bitmap transform(Bitmap source) {
3. int size = Math.min(source.getWidth(), source.getHeight());
4. int x = (source.getWidth() - size) / 2;
5. int y = (source.getHeight() - size) / 2;
6. Bitmap result = Bitmap.createBitmap(source, x, y, size, size);
7. if (result != source) {
8. source.recycle();
9. }
10. return result;
11. }
12.
13. @Override public String key() { return "square()"; }
14. }
或者是之前提到的图片变成圆角图片,你都可以自定义方法,然后通过该类的实例转换。
3.占位符即默认图片:
在很多软件中档图片没有加载出来前,都有有一个默认的图片或者头像的东西显示在那里。或者图片找不到,下载不下来,都可以使用这张默认的图片来代替。通过使用Picassoi你只需要一句代码就可以实现该功能
1. Picasso.with(context)
2. .load(url)
3. .placeholder(R.drawable.user_placeholder)
4. .error(R.drawable.user_placeholder_error)
5. .into(imageView);
他在加载这张默认图片之前会请求三次,如果三次请求还是没办法加载出来图片,就设置为默认图片
4.资源加载
Resources,assets,files,content
providers 都支持作为图片资源。
[java] view plain copy
1. Picasso.with(context).load(R.drawable.landing_screen).into(imageView1);
2. Picasso.with(context).load("file:///android_asset/DvpvklR.png").into(imageView2);
3. Picasso.with(context).load(new File(...)).into(imageView3);