今天做了什么:

完成了关于调用手机相机和相册的功能,并且传递图片url进行识图

package com.hui.testend.fragment;

import static android.app.Activity.RESULT_OK;
import static android.os.Looper.getMainLooper;

import android.Manifest;
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.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentContainerView;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import android.os.Handler;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.Toast;

import com.hui.testend.community.addcontent;
import com.hui.testend.list.MyAdapter1;
import com.hui.testend.mytool.Dao;
import com.hui.testend.R;
import com.hui.testend.list.ItemBean;
import com.hui.testend.list.MyAdapter;
import com.hui.testend.mytool.addtemp;
import com.hui.testend.recongnize.MyObject;
import com.hui.testend.recongnize.altest;
import com.hui.testend.recongnize.baiduapi;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
* A simple {@link Fragment} subclass.
* Use the {@link Fragment_home#newInstance} factory method to
* create an instance of this fragment.
*/
public class Fragment_home extends Fragment implements View.OnClickListener{
public int REQUEST_CODE_TAKE =1,REQUEST_CODE_CHOOSE=0;
Button btn_take,btn_choose;
Uri imageUri;
Handler mainhandler;
ImageView iv;
ListView listView;
MyAdapter1 myAdapter;
Bitmap img;
List<ItemBean> mBeanList;
String path;
int a1=0;

// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
public static final String ARG_PARAM1 = "param1";
public static final String ARG_PARAM2 = "param2";

// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;

public Fragment_home() {
// Required empty public constructor
}

/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment Fragment_home.
*/
// TODO: Rename and change types and number of parameters
public static Fragment_home newInstance(String param1, String param2) {
Fragment_home fragment = new Fragment_home();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_home, container, false);
}

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
init(view);
//initdata();
}
@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.btn_take:
takePhoto(v);
a1=1;
break;
case R.id.btn_choose:
choosePhoto(v);
a1=0;
break;
}

}
//
public void get1(List<MyObject.ResultItem> a) {
// 假设listView已经被初始化并设置了适配器
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// 显示弹出菜单
PopupMenu popupMenu = new PopupMenu(getContext(), view);
popupMenu.getMenuInflater().inflate(R.menu.menu1, popupMenu.getMenu());
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
int itemId = item.getItemId();
switch (itemId) {
case R.id.menu_add_comm1: // 注意这里应该是R.id.menu_add_comm1,而不是menu_add_comm1

break;
// ... 其他菜单项的处理逻辑 ...
case R.id.menu_baidu:
Intent intent =new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setData(Uri.parse("https://baike.baidu.com/item/"+a.get(position).getKeyword()));
startActivity(intent);
break;
default:
break;
}
return true; // 返回true表示菜单项已被处理
}
});
popupMenu.show(); // 最后显示弹出菜单

// 注意:启动浏览器活动的代码不应该放在这里,因为它会在弹出菜单显示之前立即执行
// 你应该将它移到上面switch-case语句中的某个case分支里,根据用户的选择来决定是否执行
}
});
}
public void initData(MyObject a){
if (a.getResult().get(0).getRoot().equals("feel this wave")){
a.getResult().remove(0);
}
get(a.getResult());
mBeanList=new ArrayList<>();
for (MyObject.ResultItem user:a.getResult()) {
ItemBean itemBean=new ItemBean();
itemBean.setTitle(user.getKeyword());
itemBean.setContent("准确度"+user.getScore());
itemBean.setImgs(img);
mBeanList.add(itemBean);
System.out.println(mBeanList.size());
}
Context context = getActivity();
if (context != null) {
myAdapter=new MyAdapter1(context,mBeanList);
}
listView.setAdapter(myAdapter);
}
@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode){
case 1:
if (resultCode==RESULT_OK){
InputStream inputStream = null;
try {
Context context = getActivity();
if (context!=null){
inputStream = context.getContentResolver().openInputStream(imageUri);
}

} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
iv.setImageBitmap(bitmap);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos); // 100表示压缩质量
byte[] byteArray = baos.toByteArray();
new Thread(new Runnable() {
@Override
public void run() {
altest altest=new altest();
MyObject a=altest.getdata1(byteArray);
mainhandler.post(new Runnable() {
@Override
public void run() {
try {
Context context = getActivity();
if (context!=null){
InputStream inputStream = context.getContentResolver().openInputStream(imageUri);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
iv.setImageBitmap(bitmap);
img=bitmap;
initData(a);
}
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
}
});
}
}).start();
}
break;
case 0:
if (resultCode == RESULT_OK) {
Uri uri = data.getData();
imageUri=uri;
String imagePath = getPathFromUri(uri);
path=imagePath;
new Thread(new Runnable() {
@Override
public void run() {
altest altest = new altest();
MyObject a=altest.getdata(imagePath);
mainhandler.post(new Runnable() {
@Override
public void run() {
Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
iv.setImageBitmap(bitmap);
img=bitmap;
initData(a);
}
});
}
}).start();
break;
}
}
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
Context context = getActivity();
if (context != null) {
switch (requestCode) {
case 1:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// 权限被授予,可以进行相应的操作
// 在这里进行访问文件的操作
doTake();
} else {
Toast.makeText(context, "需要读取外部存储权限才能访问文件", Toast.LENGTH_SHORT).show();
}
break;
case 0:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// 权限被授予,可以进行相应的操作
// 在这里进行访问文件的操作
dochoose();
} else {
Toast.makeText(context, "需要读取外部存储权限才能访问文件", Toast.LENGTH_SHORT).show();
}
break;
}

}
}

private void dochoose() {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, REQUEST_CODE_CHOOSE);
}
private void doTake() {
Context context = getActivity();
if (context!=null) {
File imageTemp = new File(context.getExternalCacheDir(), "imageOut.jpeg");
if (imageTemp.exists()) {
imageTemp.delete();
}
try {
imageTemp.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}

if (Build.VERSION.SDK_INT > 24) {
//Context context = getActivity();
imageUri = FileProvider.getUriForFile(context, "com.hui.testend.fileprovider", imageTemp);
// contentProvider
// imageUri = FileProvider.getUriForFile(this, "com.hui.testend.fileprovider", imageTemp);
} else {
imageUri = Uri.fromFile(imageTemp);
}
Intent intent = new Intent();
intent.setAction("android.media.action.IMAGE_CAPTURE");
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, REQUEST_CODE_TAKE);
}
}
public void choosePhoto(View view){
Context context = getActivity();
if (context != null) {
if (ContextCompat.checkSelfPermission(context, android.Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
// 真正的执行去相册
dochoose();
} else {
// 去申请权限
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
}
}
}
public void takePhoto(View view) {
Context context = getActivity();
if(context != null) {
if (ContextCompat.checkSelfPermission(context, android.Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
// 真正的执行去拍照
doTake();
} else {
// 去申请权限
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CAMERA}, 1);
}
}
}
private String getPathFromUri(Uri uri) {
String[] projection = {MediaStore.Images.Media.DATA};
Context context = getActivity();
String path = null;
if (context != null) {
Cursor cursor = context.getContentResolver().query(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
path = cursor.getString(column_index);
cursor.close();

}
return path;
}
public void init(View view){
iv=view.findViewById(R.id.iv);
mainhandler=new Handler(getMainLooper());
btn_take=view.findViewById(R.id.btn_take);
btn_choose=view.findViewById(R.id.btn_choose);
listView=view.findViewById(R.id.list);
registerForContextMenu(listView);
btn_take.setOnClickListener(this);
btn_choose.setOnClickListener(this);
}
public void get(List<MyObject.ResultItem> a){
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
PopupMenu popupMenu=new PopupMenu(getContext(),view);
popupMenu.inflate(R.menu.menu1);
popupMenu.show();
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
int itemid=item.getItemId();
switch (itemid){
case R.id.menu_add_comm1:
addtemp temp=new addtemp();
temp.setTitle(mBeanList.get(position).getTitle());
temp.setContent(mBeanList.get(position).getContent());
temp.setImgpath(imageUri);
System.out.println(imageUri+"555");
Bundle bundle=new Bundle();
bundle.putString("title",mBeanList.get(position).getTitle());
bundle.putString("content",mBeanList.get(position).getContent());
bundle.putString("path",path);
bundle.putString("img",imageUri.toString());
bundle.putInt("a",a1);
Intent intent=new Intent(getActivity(), addcontent.class);
intent.putExtra("temp" ,bundle);
startActivity(intent);
break;
case R.id.menu_baidu:
Intent intent1 =new Intent();
intent1.setAction(Intent.ACTION_VIEW);
intent1.setData(Uri.parse("https://baike.baidu.com/item/"+a.get(position).getKeyword()));
startActivity(intent1);
break;

}
return false;
}
});

}
});
}

}
// 发送界面
// Intent intent = new Intent(this, TargetActivity.class);
// String imageUriString = "file:///path/to/your/image.jpg"; // 替换为真实的图片URI
//intent.putExtra("image_uri", imageUriString);
// startActivity(intent);
//
//// 接收界面
// String imageUriString = getIntent().getStringExtra("image_uri");
// Uri imageUri = Uri.parse(imageUriString);
// ImageView imageView = findViewById(R.id.your_image_view);
// imageView.setImageURI(imageUri);
//// 注意:如果你的图片是在私有目录中,你可能需要设置适当的权限或使用FileProvider

 

遇到了什么困难:

很多,不好评价

明天准备做什么:

继续完成团队作业

代码量 400行

时间  3小时