团队开发冲刺第十二天
今天实现的功能:
完成昨天的bug,同时修复之前的点赞数和评论数的获取不匹配的问题,成功完成消息的提醒。同时完成用户界面的头像选择(拍照,从图库中选择)
遇到的问题:
在编写的过程中,昨天就存在Android8以上的消息一直不显示的问题,今天早上找了一个集成的notification成功展示出来,在做头像选择倒是没什么问题,之前就做过
但是头像的上传,暂时没有头绪。
明天的安排:
将头像上传到服务器端,然后存入数据库中。有时间开始准备搜索框的实现。
今日修复:
修复点赞与评论的数目不对应的bug,从适配器上重新获取服务器端的数据(不再使用线程访问,有延迟导致数目不对)
主要是javaweb后台的代码,这里就不再展示
完成消息的提醒:(有声音,震动,点击后到一个活动中,右侧有图片,可以滑动删除,针对长文本展示,可拉伸)
private MeViewModel mViewModel; private View view; private TextView textViewname,textViewguanzhu,textViewfan; private ImageView photoimageView; private Button buttonmessage; private Uri imageUri; public static final int TAKE_PHOTO =1; public static final int CHOOSE_PHOTO=2; public static MeFragment newInstance() { return new MeFragment(); } public String getUsername(){ return MainActivity.getUserName(); } @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { view=inflater.inflate(R.layout.me_fragment, container, false); return view; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mViewModel = ViewModelProviders.of(this).get(MeViewModel.class); // TODO: Use the ViewModel textViewname=view.findViewById(R.id.username); textViewfan=view.findViewById(R.id.fannumber); textViewguanzhu=view.findViewById(R.id.guanzhunumber); photoimageView=view.findViewById(R.id.userphoto); buttonmessage=view.findViewById(R.id.button); Log.i("我的页面", getUsername()); textViewname.setText(getUsername()); photoimageView.setOnClickListener(l); buttonmessage.setOnClickListener(l); } View.OnClickListener l=new View.OnClickListener() { @Override public void onClick(View v) { switch (v.getId()){ case R.id.button: Intent intent = new Intent(view.getContext(), LoginActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(view.getContext(), 0, intent, 0); NotificationUtils notificationUtils=new NotificationUtils(view.getContext()); notificationUtils .setContentIntent(pendingIntent) .sendNotification(3,"这个是标题3", "这个是内容很长这个是内容很长这个是内容很长这个是内容很长这个是内容很长这个是内容很长这个是内容很长这个是内容很长这个是内容很长这个是内容很长这个是内容很长这个是内容很长这个是内容很长",R.drawable.qq); break; case R.id.userphoto: showTypeDialog(); } } };
头像的选择:(拍照与图库)
package com.example.newbsh.UI.user; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import androidx.core.content.FileProvider; import androidx.lifecycle.ViewModelProviders; import android.Manifest; import android.annotation.TargetApi; import android.app.AlertDialog; import android.app.PendingIntent; import android.content.ContentResolver; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Build; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import android.os.Environment; import android.provider.DocumentsContract; import android.provider.MediaStore; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.example.newbsh.HttpUtil.HttpUtil; import com.example.newbsh.HttpUtil.NotificationUtils; import com.example.newbsh.Login.LoginActivity; import com.example.newbsh.MainActivity; import com.example.newbsh.R; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.HashMap; import java.util.Map; import static android.app.Activity.RESULT_OK; public class MeFragment extends Fragment { private MeViewModel mViewModel; private View view; private TextView textViewname,textViewguanzhu,textViewfan; private ImageView photoimageView; private Button buttonmessage; private Uri imageUri; public static final int TAKE_PHOTO =1; public static final int CHOOSE_PHOTO=2; public static MeFragment newInstance() { return new MeFragment(); } public String getUsername(){ return MainActivity.getUserName(); } @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { view=inflater.inflate(R.layout.me_fragment, container, false); return view; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mViewModel = ViewModelProviders.of(this).get(MeViewModel.class); // TODO: Use the ViewModel textViewname=view.findViewById(R.id.username); textViewfan=view.findViewById(R.id.fannumber); textViewguanzhu=view.findViewById(R.id.guanzhunumber); photoimageView=view.findViewById(R.id.userphoto); buttonmessage=view.findViewById(R.id.button); Log.i("我的页面", getUsername()); textViewname.setText(getUsername()); photoimageView.setOnClickListener(l); buttonmessage.setOnClickListener(l); } View.OnClickListener l=new View.OnClickListener() { @Override public void onClick(View v) { switch (v.getId()){ case R.id.button: Intent intent = new Intent(view.getContext(), LoginActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(view.getContext(), 0, intent, 0); NotificationUtils notificationUtils=new NotificationUtils(view.getContext()); notificationUtils .setContentIntent(pendingIntent) .sendNotification(3,"这个是标题3", "这个是内容很长这个是内容很长这个是内容很长这个是内容很长这个是内容很长这个是内容很长这个是内容很长这个是内容很长这个是内容很长这个是内容很长这个是内容很长这个是内容很长这个是内容很长",R.drawable.qq); break; case R.id.userphoto: showTypeDialog(); } } }; /* 头像切换代码 */ private void showTypeDialog() { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); final AlertDialog dialog = builder.create(); final View view = View.inflate(getActivity(), R.layout.dialog_select_photo, null); TextView tv_select_gallery = (TextView) view.findViewById(R.id.tv_select_gallery); TextView tv_select_camera = (TextView) view.findViewById(R.id.tv_select_camera); tv_select_gallery.setOnClickListener(new View.OnClickListener() {// 在相册中选取 @Override public void onClick(View v) { if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1); } else { openAlbum(); } dialog.dismiss(); } }); tv_select_camera.setOnClickListener(new View.OnClickListener() {// 调用照相机 @Override public void onClick(View v) { File outputImage =new File(view.getContext().getExternalCacheDir(),"output_image.jpg"); try { if(outputImage.exists()){ outputImage.delete(); } outputImage.createNewFile(); } catch (IOException e) { e.printStackTrace(); } if(Build.VERSION.SDK_INT>=24){ imageUri= FileProvider.getUriForFile(view.getContext(), "com.example.cameraalbumtest.fileprovider1",outputImage); }else{ imageUri=Uri.fromFile(outputImage); } //启动相机程序 Intent intent=new Intent("android.media.action.IMAGE_CAPTURE"); intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri); startActivityForResult(intent,TAKE_PHOTO); dialog.dismiss(); } }); dialog.setView(view); dialog.show(); } private void openAlbum() { Intent intent=new Intent("android.intent.action.GET_CONTENT"); intent.setType("image/*"); startActivityForResult(intent,CHOOSE_PHOTO); } @Override public void onRequestPermissionsResult(int requestCode,String[] permissions,int[] grantResults) { switch (requestCode) { case 1: if(grantResults.length>0&&grantResults[0]==PackageManager.PERMISSION_GRANTED) { openAlbum(); } else { Toast.makeText(view.getContext(),"你否定了相册请求",Toast.LENGTH_SHORT).show(); } break; default: } } /** * user转换为file文件 *返回值为file类型 * @param uri * @return */ public static File uriToFile(Uri uri,Context context) { String path = null; if ("file".equals(uri.getScheme())) { path = uri.getEncodedPath(); if (path != null) { path = Uri.decode(path); ContentResolver cr = context.getContentResolver(); StringBuffer buff = new StringBuffer(); buff.append("(").append(MediaStore.Images.ImageColumns.DATA).append("=").append("'" + path + "'").append(")"); Cursor cur = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new String[] { MediaStore.Images.ImageColumns._ID, MediaStore.Images.ImageColumns.DATA }, buff.toString(), null, null); int index = 0; int dataIdx = 0; for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) { index = cur.getColumnIndex(MediaStore.Images.ImageColumns._ID); index = cur.getInt(index); dataIdx = cur.getColumnIndex(MediaStore.Images.ImageColumns.DATA); path = cur.getString(dataIdx); } cur.close(); if (index == 0) { } else { Uri u = Uri.parse("content://media/external/images/media/" + index); System.out.println("temp uri is :" + u); } } if (path != null) { return new File(path); } } else if ("content".equals(uri.getScheme())) { // 4.2.2以后 String[] proj = { MediaStore.Images.Media.DATA }; Cursor cursor = context.getContentResolver().query(uri, proj, null, null, null); if (cursor.moveToFirst()) { int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); path = cursor.getString(columnIndex); } cursor.close(); return new File(path); } else { //Log.i(TAG, "Uri Scheme:" + uri.getScheme()); } return null; } /* 获取uri的真实路径 */ /** * 根据Uri获取文件真实地址 */ public static String getRealFilePath(Context context, Uri uri) { if (null == uri) return null; final String scheme = uri.getScheme(); String realPath = null; if (scheme == null) realPath = uri.getPath(); else if (ContentResolver.SCHEME_FILE.equals(scheme)) { realPath = uri.getPath(); } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) { Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null); if (null != cursor) { if (cursor.moveToFirst()) { int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA); if (index > -1) { realPath = cursor.getString(index); } } cursor.close(); } } if (TextUtils.isEmpty(realPath)) { if (uri != null) { String uriString = uri.toString(); int index = uriString.lastIndexOf("/"); String imageName = uriString.substring(index); File storageDir; storageDir = Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_PICTURES); File file = new File(storageDir, imageName); if (file.exists()) { realPath = file.getAbsolutePath(); } else { storageDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES); File file1 = new File(storageDir, imageName); realPath = file1.getAbsolutePath(); } } } return realPath; } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode){ case TAKE_PHOTO: if(resultCode==RESULT_OK){ try { Bitmap bitmap= BitmapFactory.decodeStream(view.getContext().getContentResolver().openInputStream(imageUri)); // String ans=imageUri.toString(); // bean.image=ans; // muserOperator.updateImage(bean); Log.i("imguri", bitmap.toString()); //photoimageView.setImageURI(imageUri); photoimageView.setImageBitmap(bitmap); /* 图片上传 */ String uri=getRealFilePath(view.getContext(),imageUri); File file=new File(uri); Map<String,File> map=new HashMap<>(); map.put("photo",file); String ans= HttpUtil.sendPostImg("http://localhost:8080/BaiXiaoSheng/downloadimg?username=123",map); if (ans.equals("yes")){ Toast.makeText(view.getContext(),"上传成功",Toast.LENGTH_LONG).show(); }else{ Toast.makeText(view.getContext(),"上传失败",Toast.LENGTH_LONG).show(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } break; case CHOOSE_PHOTO: if(resultCode==RESULT_OK){ if(Build.VERSION.SDK_INT>=19){ handleImageOnKitKat(data); }else{ handleImageBeforeKitKat(data); } } break; default: break; } } @TargetApi(19) private void handleImageOnKitKat(Intent data) { String imagePath=null; Uri uri=data.getData(); Log.i("真实uri", uri.toString()); if(DocumentsContract.isDocumentUri(view.getContext(),uri)) { //如果是document类型的uri则通过document id处理 String docId= DocumentsContract.getDocumentId(uri); if("com.android.providers.media.documents".equals(uri.getAuthority())) { String id=docId.split(":")[1];//解析为数字格式的id String selection= MediaStore.Images.Media._ID +"="+id; imagePath=getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,selection); } else if("com.android.providers.downloads.documents".equals(uri.getAuthority())) { Uri contentUri= ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),Long.valueOf(docId)); imagePath=getImagePath(contentUri,null); } else if("content".equalsIgnoreCase(uri.getScheme())) { //如果是content类型的uri则使用普通方式处理 imagePath=getImagePath(uri,null); } else if("file".equalsIgnoreCase(uri.getScheme())) { //如果是file类型的uri直接获取图片路径就好 imagePath=uri.getPath(); } displayImage(imagePath);//根据图片的路径显示图片 } } private void handleImageBeforeKitKat(Intent data) { Uri uri=data.getData(); Log.i("真实uri", uri.toString()); String imagePath=getImagePath(uri,null); displayImage(imagePath); } private String getImagePath(Uri uri,String selection) { String path=null; //通过uri和selection来获取真实的图片路径 Cursor cursor=view.getContext().getContentResolver().query(uri,null,selection,null,null); if(cursor!=null) { if(cursor.moveToFirst()) { path=cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA)); } cursor.close(); } return path; } private void displayImage(String imagePath) { if(imagePath!=null) { //Bitmap bitmap= BitmapFactory.decodeFile(imagePath); //imageView.setImageBitmap(bitmap); Uri ans=getImageContentUri(view.getContext(),imagePath); Log.i("imgUri", ans.toString()); //保存图片到网址 photoimageView.setImageURI(ans); } else { Toast.makeText(view.getContext(),"获取图片失败", Toast.LENGTH_SHORT).show(); } } /** * 将图片转换成Uri * @param context 传入上下文参数 * @param path 图片的路径 * @return 返回的就是一个Uri对象 */ public static Uri getImageContentUri(Context context, String path) { Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new String[] { MediaStore.Images.Media._ID }, MediaStore.Images.Media.DATA + "=? ", new String[] { path }, null); if (cursor != null && cursor.moveToFirst()) { int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID)); Uri baseUri = Uri.parse("content://media/external/images/media"); return Uri.withAppendedPath(baseUri, "" + id); } else { // 如果图片不在手机的共享图片数据库,就先把它插入。 if (new File(path).exists()) { ContentValues values = new ContentValues(); values.put(MediaStore.Images.Media.DATA, path); return context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); } else { return null; } } } }