冲刺六

今天做了什么:

  以下是我takeactivity类,用来执行点击拍照识别后的行为。

package com.example.vastland;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import android.Manifest;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

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;

public class TakeActivity extends AppCompatActivity {

public int REQUEST_CODE_TAKE =1;
public int REQUEST_CODE_CAMERA = 1;
Uri imageUri;
Handler mainhandler;
ImageView iv;
ListView listView;
MyAdapter myAdapter;
List<ItemBean> mBeanList;
ImageView back;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_take);
back = findViewById(R.id.back);
init();
takePhoto();
back.setOnClickListener(v -> {
Intent intent = new Intent(this,homeFragment.class);
startActivity(intent);
});
}



public void get(List<MyObject.ResultItem> a){
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent =new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setData(Uri.parse("https://baike.baidu.com/item/"+a.get(position).getKeyword()));
startActivity(intent);
}
});
}
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<>();
String firstUser = null;
for (MyObject.ResultItem user:a.getResult()) {
ItemBean itemBean=new ItemBean();
itemBean.setTitle(user.getKeyword());
itemBean.setContent("概率"+user.getScore()+"点击了解详情");
itemBean.setImgsId(R.drawable.ani);
mBeanList.add(itemBean);
System.out.println(mBeanList.size());
if (firstUser == null) {
firstUser = user.getKeyword(); // 保存第一个user
}

}
if (firstUser != null) {
saveToHistorys(firstUser); // 只调用一次saveToHistorys()方法
}
myAdapter=new MyAdapter(TakeActivity.this,mBeanList);
listView.setAdapter(myAdapter);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);

if (resultCode==RESULT_OK){
InputStream inputStream = null;
try {
inputStream = 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 {
InputStream inputStream = getContentResolver().openInputStream(imageUri);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
iv.setImageBitmap(bitmap);
initData(a);
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
}
});
}
}).start();
}

}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);

if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// 权限被授予,可以进行相应的操作
// 在这里进行访问文件的操作
doTake();
} else {
Toast.makeText(this, "需要读取外部存储权限才能访问文件", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(this,homeFragment.class);
startActivity(intent);
}

}

private void takePhoto() {
// 检查相机权限
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
// 已授予相机权限,执行拍照逻辑
doTake();
} else {
// 未授予相机权限,向用户请求权限
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, REQUEST_CODE_CAMERA);
}
}

private void doTake() {
File imageTemp = new File(getExternalCacheDir(), "imageOut.jpeg");
if (imageTemp.exists()) {
imageTemp.delete();
}
try {
imageTemp.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}

if (Build.VERSION.SDK_INT > 24) {
// contentProvider
imageUri = FileProvider.getUriForFile(this, "com.example.vastland.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 init(){
iv=findViewById(R.id.iv);
mainhandler=new Handler(getMainLooper());
listView=findViewById(R.id.list);

}
private void saveToHistory(String imagePath) {
DatabaseHelper databaseHelper = new DatabaseHelper(this);
SQLiteDatabase db = databaseHelper.getWritableDatabase();

ContentValues values = new ContentValues();
values.put(DatabaseHelper.COLUMN_IMAGE_PATH, imagePath);
long rowId = db.insert(DatabaseHelper.TABLE_NAME, null, values);
if (rowId == -1) {
// 保存失败
} else {
// 保存成功
System.out.println("保存成功11111111111111111111111111111111111111111");
}

db.close();
}
private void saveToHistorys( String result) {
DatabaseHelper databaseHelper = new DatabaseHelper(this);
SQLiteDatabase db = databaseHelper.getWritableDatabase();

ContentValues values = new ContentValues();
values.put(DatabaseHelper.COLUMN_RESULT, result);
long rowId = db.insert(DatabaseHelper.TABLE_NAME, null, values);
if (rowId == -1) {
// 保存失败
} else {
// 保存成功
System.out.println("保存成功2222222222222222222222222222222222222222222");
}

db.close();
}
}
package com.example.vastland;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.List;

public class MyAdapter extends BaseAdapter {
private List<ItemBean> MyList;
private LayoutInflater mlayoutInflater;
private Context mContext;
public MyAdapter(Context mContext ,List<ItemBean> MyList){
this.mContext=mContext;
this.MyList=MyList;
mlayoutInflater=LayoutInflater.from(mContext);
}

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

@Override
public Object getItem(int position) {
return MyList.get(position);
}

@Override
public long getItemId(int position) {
return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView=mlayoutInflater.inflate(R.layout.activity_item,parent,false);
ImageView imageView=convertView.findViewById(R.id.Iv_img);
TextView tv_title=convertView.findViewById(R.id.tv_title);
TextView tv_content=convertView.findViewById(R.id.tv_content);
ItemBean itemBean=MyList.get(position);
imageView.setImageResource(itemBean.getImgsId());
tv_title.setText(itemBean.getTitle());
tv_content.setText(itemBean.getContent());
return convertView;
}
}这是我的list的适配器,用来将调取api后的结果以列表显示
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingTop="5dp"
android:paddingBottom="5dp">
<ImageView
android:id="@+id/imageview"
android:layout_width="100dp"
android:layout_height="100dp"
android:src="@drawable/ani"
android:scaleType="centerCrop"/>
<TextView
android:id="@+id/titleTextview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="标题"
android:maxLines="1"
android:layout_toRightOf="@id/imageview"
android:layout_marginRight="10dp"
android:layout_marginLeft="10dp"
android:textSize="20sp"
android:textStyle="bold"/>
<TextView
android:id="@+id/contentTextview"
android:layout_width="match_parent"
android:layout_height="70dp"
android:text="内容"
android:layout_toRightOf="@id/imageview"
android:layout_below="@id/titleTextview"
android:layout_marginRight="10dp"
android:layout_marginLeft="10dp"/>
</RelativeLayout>
</LinearLayout>列表的每一列的样式
posted @ 2024-05-23 23:32  ZzHhyao  阅读(9)  评论(0)    收藏  举报