xml 如何使用URI以json格式将多个图像保存到localdb
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了xml 如何使用URI以json格式将多个图像保存到localdb相关的知识,希望对你有一定的参考价值。
package com.multipart.mainactivity;
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;
import retrofit2.http.Multipart;
import retrofit2.http.POST;
import retrofit2.http.Part;
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_PERMISSION_CODE = 3;
private static final int REQUEST_CAMERA = 1;
private static final String TAG = "MainActivity";
private static final int REQUEST_GALLERY = 2;
private static final int REQUEST_STORAGE_PERMISSION_CODE = 500;
private static final int REQUEST_APP_SETTINGS = 1;
private static Retrofit mRetrofit;
private File photoFile = null;
private RecyclerView recyclerView;
private Button attachImage,sendBtn,saveBtn,getBtn;
private ImageView ViewImage;
private UploadImageAdapter adapter;
MainActivity mActivity;
private String TAKE_PIC = "Camera";
private String GALLERY_PIC = "Gallery";
private String CANCEL = "Cancel";
private String userChoosenTask;
private Uri photoURI;
private String mCurrentPhotoPath;
private String uriFromDocument;
private List<Uri> dataUriList = new ArrayList<>();
private List<File> fileList = new ArrayList<>();
private static final String MULTIPART_FORMDATA = "multipart/form-data";
private DataBaseHelper dataBaseHelper;
private List<String> mUriList;
int count;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dataBaseHelper = new DataBaseHelper(MainActivity.this);
mUriList = new ArrayList<>();
mActivity = MainActivity.this;
saveBtn = findViewById(R.id.save);
getBtn = findViewById(R.id.button2);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
LinearLayoutManager layoutmanager = new LinearLayoutManager(MainActivity.this);
layoutmanager.setOrientation(LinearLayoutManager.HORIZONTAL);
recyclerView.setLayoutManager(layoutmanager);
intializeAdapter();
attachImage = findViewById(R.id.attachimage);
ViewImage = (ImageView) findViewById(R.id.viewImage);
sendBtn = findViewById(R.id.button);
attachImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (ContextCompat.checkSelfPermission(mActivity, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(mActivity,
Manifest.permission.CAMERA) && ActivityCompat.shouldShowRequestPermissionRationale(mActivity,
Manifest.permission.CAMERA)) {
} else {
ActivityCompat.requestPermissions(mActivity,
new String[]{Manifest.permission.CAMERA},
REQUEST_PERMISSION_CODE);
}
} else
selectImage();
}
});
sendBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
updateProfileAPI();
}
});
saveBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
count++;
dataBaseHelper.insertUploadImagedata(mUriList,String.valueOf(count));
}
});
getBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
List<String> list = dataBaseHelper.getUploadedImageDataList();
List<Uri> uriList = new ArrayList<>();
for(int i=0;i<list.size();i++) {
uriList.add(Uri.parse(list.get(i)));
}
/* Gson gson = new Gson();
List<String> mOptionTarget = new ArrayList<>();
List<String> targetList = gson.fromJson(typeUrl, mOptionTarget);*/
Log.d(TAG, "onClick: list " + list);
dataUriList.clear();
Log.d(TAG, "onClick: uri List " + uriList);
intializeAdapter(uriList);
}
});
}
private void intializeAdapter(List<Uri> list) {
adapter = new UploadImageAdapter(list, MainActivity.this);
recyclerView.setAdapter(adapter);
}
private void intializeAdapter() {
adapter = new UploadImageAdapter(dataUriList, MainActivity.this);
recyclerView.setAdapter(adapter);
}
private void selectImage() {
final CharSequence[] items = {TAKE_PIC, GALLERY_PIC, CANCEL};
android.support.v7.app.AlertDialog.Builder alertdialog = new android.support.v7.app.AlertDialog.Builder(this);
alertdialog.setTitle(R.string.select_pic);
alertdialog.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int position) {
boolean result = PermissionUtils.checkPermission(mActivity);
if (items[position].equals(TAKE_PIC)) {
userChoosenTask = TAKE_PIC;
cameraIntent();
} else if (items[position].equals(GALLERY_PIC)) {
userChoosenTask = GALLERY_PIC;
galleryIntent();
} else if (items[position].equals(CANCEL)) {
dialog.dismiss();
}
}
});
alertdialog.show();
}
private void cameraIntent() {
if (PermissionUtils.checkStoragePermission(mActivity)) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(mActivity.getPackageManager()) != null) {
// Create the File where the photo should go
// File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
Log.d(TAG, "cameraIntent: excep " + ex.getMessage());
}
// Continue only if the File was successfully created
if (photoFile != null) {
if (Build.VERSION.SDK_INT < 23) {
photoURI = Uri.fromFile(photoFile);
}
else {
photoURI = FileProvider.getUriForFile(mActivity,
"com.sgs.bamp_app.fileprovider",
photoFile);
}
mCurrentPhotoPath = photoFile.getAbsolutePath();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_CAMERA);
} else {
Toast.makeText(mActivity, "file is null", Toast.LENGTH_SHORT).show();
}
}
}
else {
ActivityCompat.requestPermissions(mActivity, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE},
REQUEST_STORAGE_PERMISSION_CODE);
}
}
private void galleryIntent() {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(Intent.createChooser(intent, "Select File"), REQUEST_GALLERY);
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyy_MM_dd", Locale.getDefault()).format(new Date());
String imageFileName = timeStamp + "_";
File albumF = mActivity.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
return File.createTempFile(imageFileName, ".png", albumF);
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case REQUEST_STORAGE_PERMISSION_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (userChoosenTask.equals(TAKE_PIC))
cameraIntent();
else if (userChoosenTask.equals(GALLERY_PIC))
galleryIntent();
} else {
alertForCamera();
}
break;
}
}
private void alertForCamera() {
final AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle("Enable Camera permmissions")
.setMessage("Your Camera Settings is 'Off'")
.setPositiveButton("SETTINGS", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
Intent myAppSettings = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:" + getPackageName()));
myAppSettings.addCategory(Intent.CATEGORY_DEFAULT);
myAppSettings.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivityForResult(myAppSettings, REQUEST_APP_SETTINGS);
}
})
.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
finish();
}
});
dialog.show();
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == REQUEST_GALLERY)
onSelectFromGalleryResult(data);
if (requestCode == REQUEST_CAMERA)
onCaptureImageResult(data);
}
}
private void onCaptureImageResult(Intent data) {
/* Bundle extras = data.getExtras();
mImageBitmap = (Bitmap) extras.get("data");
profilePic.setImageBitmap(mImageBitmap);*/
photoURI = Uri.fromFile(photoFile);
dataUriList.add(photoURI);
// save the uri String in to the localDb
mUriList.add(photoURI.toString());
if (mCurrentPhotoPath != null) {
RequestOptions options = new RequestOptions();
options.autoClone();
Log.d(TAG, "onActivityResult: " + photoFile);
Glide.with(this)
.load(photoFile)
.into(ViewImage);
fileList.add(photoFile);
}
else {
Log.d(TAG, "onActivityResult: null path");
}
}
private void onSelectFromGalleryResult(Intent data) {
if (data != null && data.getData() != null) {
photoURI = data.getData();
// save the uri String in to the localDb
mUriList.add(photoURI.toString());
if (photoURI != null) {
try {
dataUriList.add(photoURI);
Log.d(TAG, "onActivityResult: " + photoURI);
photoFile = new File(getPath(photoURI));
RequestOptions options = new RequestOptions();
options.autoClone();
Glide.with(this)
.load(photoFile)
.apply(options)
.into(ViewImage);
fileList.add(photoFile);
}
catch (Exception e) {
Log.d(TAG, "onActivityResult: " + e.getMessage());
Toast.makeText(this, "Choose proper image", Toast.LENGTH_SHORT).show();
}
}
}
else {
Log.d(TAG, "onActivityResult: null path");
Toast.makeText(this, "Image not selected! Try Again", Toast.LENGTH_LONG).show();
}
}
public String getPath(Uri uri) {
try {
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
if (cursor == null) return null;
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
String s = null;
if (cursor.moveToFirst()) {
s = cursor.getString(column_index);
} else {
Log.d(TAG, "Cursor is not moving");
}
cursor.close();
return s;
} catch (Exception e) {
Log.d(TAG, "getPath: " + e.getMessage());
return null;
}
}
private void updateProfileAPI() {
int fileSize = fileList.size();
RegisterService updateProfileAPI = getRetrofit().create(RegisterService.class);
RequestBody rbBridgeId = null;
RequestBody rbUserId = null;
MultipartBody.Part photo1 = null;
MultipartBody.Part photo2 = null;
MultipartBody.Part photo3 = null;
MultipartBody.Part photo4 = null;
MultipartBody.Part photo5 = null;
MultipartBody.Part photo6 = null;
MultipartBody.Part photo7 = null;
MultipartBody.Part photo8 = null;
rbBridgeId = RequestBody.create(MediaType.parse(MULTIPART_FORMDATA), "KAKA-17N098DV6577654355");
rbUserId = RequestBody.create(MediaType.parse(MULTIPART_FORMDATA), "678");
if (!fileList.isEmpty() && fileSize > 0) {
RequestBody requestFile =
RequestBody.create(MediaType.parse(MULTIPART_FORMDATA), fileList.get(0));
photo1 =
MultipartBody.Part.createFormData("images[]", fileList.get(0).getName(), requestFile);
RequestBody requestFile2 =
RequestBody.create(MediaType.parse(MULTIPART_FORMDATA), fileList.get(1));
photo2 =
MultipartBody.Part.createFormData("images[]", fileList.get(1).getName(), requestFile2);
RequestBody requestFile3 =
RequestBody.create(MediaType.parse(MULTIPART_FORMDATA), fileList.get(2));
photo3 =
MultipartBody.Part.createFormData("images[]", fileList.get(2).getName(), requestFile3);
RequestBody requestFile4 =
RequestBody.create(MediaType.parse(MULTIPART_FORMDATA), fileList.get(4));
photo4 =
MultipartBody.Part.createFormData("images[]", fileList.get(4).getName(), requestFile4);
RequestBody requestFile5 =
RequestBody.create(MediaType.parse(MULTIPART_FORMDATA), fileList.get(5));
photo5 =
MultipartBody.Part.createFormData("images[]", fileList.get(5).getName(), requestFile5);
RequestBody requestFile6 =
RequestBody.create(MediaType.parse(MULTIPART_FORMDATA), fileList.get(1));
photo6 =
MultipartBody.Part.createFormData("images[]", fileList.get(1).getName(), requestFile6);
/* RequestBody requestFile7 =
RequestBody.create(MediaType.parse(MULTIPART_FORMDATA), fileList.get(7));
photo7 =
MultipartBody.Part.createFormData("images[]", fileList.get(7).getName(), requestFile7);*/
RequestBody requestFile33 =
RequestBody.create(MediaType.parse(MULTIPART_FORMDATA), fileList.get(3));
photo8 =
MultipartBody.Part.createFormData("images[]", fileList.get(3).getName(), requestFile33);
}
Call<List<ResponseBody1>> call = updateProfileAPI.uploadImage(photo1,photo2,photo3,photo4,photo5,photo6,photo7,photo8,rbBridgeId,rbUserId);
call.enqueue(new Callback<List<ResponseBody1>>() {
@Override
public void onResponse(Call<List<ResponseBody1>> call, Response<List<ResponseBody1>> response) {
if(response.isSuccessful()) {
Toast.makeText(MainActivity.this, "Success!", Toast.LENGTH_SHORT).show();
}
else {
try {
Log.d(TAG, "onResponse: failure " + response.errorBody().string());
Toast.makeText(MainActivity.this, "Failure!", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public void onFailure(Call<List<ResponseBody1>> call, Throwable t) {
Log.d(TAG, "onFailure: " + t.getMessage());
Toast.makeText(MainActivity.this, "Failure", Toast.LENGTH_SHORT).show();
}
});
}
public interface RegisterService {
@Multipart
@POST("add_images")
Call<List<ResponseBody1>> uploadImage(
@Part MultipartBody.Part file1,
@Part MultipartBody.Part file2,
@Part MultipartBody.Part file3,
@Part MultipartBody.Part file4,
@Part MultipartBody.Part file5,
@Part MultipartBody.Part file6,
@Part MultipartBody.Part file7,
@Part MultipartBody.Part file8,
@Part("bridge_id") RequestBody rbBridgeId,
@Part("user_id") RequestBody rbUserId );
}
private static Retrofit initializeRetrofit() {
Gson gson = new GsonBuilder()
.setLenient()
.create();
mRetrofit = new Retrofit.Builder()
.baseUrl("http://bampstage.shrigowri.com/ibms/index.php/bamp_api/")
.addConverterFactory(GsonConverterFactory.create(gson))
.addConverterFactory(ScalarsConverterFactory.create())
.build();
return mRetrofit;
}
public static Retrofit getRetrofit() {
if (mRetrofit != null) {
return mRetrofit;
} else {
return initializeRetrofit();
}
}
}
package com.multipart.mainactivity;
import android.provider.BaseColumns;
public class DataBaseContract {
public static final class UploadImageEntry implements BaseColumns {
public static final String TABLE_NAME = "uploadimage_table";
public static final String COLUMN_BRIDGE_ID= "bridged_id";
public static final String COLUMN_IMAGE_URL_SCOR_EFFICIENCY = "uploadimage_url_scor_efficiency";
public static final String COLUMN_IMG_URL_NONINTEGRAL = "images_for_nonintegral";
public static final String COLUMN_IMG_URL_SUPER_STRUCTURE = "images_for_superstructure";
public static final String COLUMN_IMG_URL_SUB_STRUCTURE = "images_for_subtructure";
public static final String COLUMN_TOTAL_IMG= "totalImg";
}
}
package com.multipart.mainactivity;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;
import android.util.Log;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
public class DataBaseHelper extends SQLiteOpenHelper {
private static final String TAG = "BampDbHelper";
private static final int DATABASE_VERSION = 8;
private static final String DATABASE_NAME = "BampIndia.db";
private SQLiteDatabase db;
public DataBaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
final String SQL_CREATE_UPLOADIMAGE_TABLE = "CREATE TABLE " + DataBaseContract.UploadImageEntry.TABLE_NAME + " ( " +
DataBaseContract.UploadImageEntry.COLUMN_BRIDGE_ID + " TEXT PRIMARY KEY, " +
DataBaseContract.UploadImageEntry.COLUMN_IMG_URL_NONINTEGRAL + " TEXT, " +
DataBaseContract.UploadImageEntry.COLUMN_IMG_URL_SUPER_STRUCTURE + " TEXT, " +
DataBaseContract.UploadImageEntry.COLUMN_IMG_URL_SUB_STRUCTURE + " TEXT, " +
DataBaseContract.UploadImageEntry.COLUMN_TOTAL_IMG + " INTEGER, " +
DataBaseContract.UploadImageEntry.COLUMN_IMAGE_URL_SCOR_EFFICIENCY + " TEXT " + " )";
Log.d(TAG, "onCreate: table created is " + SQL_CREATE_UPLOADIMAGE_TABLE);
sqLiteDatabase.execSQL(SQL_CREATE_UPLOADIMAGE_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
//INSERTING AND RETRIEVIBG UPLOAD IMAGE DATA FROM AND TO SQLITE DATABASE
public boolean insertUploadImagedata(List<String> mUriList, String bridgeId) {
int length = mUriList.size();
SQLiteDatabase db = this.getWritableDatabase();
Gson gson = new Gson();
// for (int i = 0; i < length; i++) {
ContentValues contentvalues = new ContentValues();
contentvalues.put(DataBaseContract.UploadImageEntry.COLUMN_BRIDGE_ID, bridgeId);
contentvalues.put(DataBaseContract.UploadImageEntry.COLUMN_IMAGE_URL_SCOR_EFFICIENCY, gson.toJson(mUriList));
/* contentvalues.put(DataBaseContract.UploadImageEntry.COLUMN_IMG_URL_NONINTEGRAL, mUriList.get(i));
contentvalues.put(DataBaseContract.UploadImageEntry.COLUMN_IMG_URL_SUPER_STRUCTURE, mUriList.get(i));
contentvalues.put(DataBaseContract.UploadImageEntry.COLUMN_IMG_URL_SUB_STRUCTURE, mUriList.get(i));*/
contentvalues.put(DataBaseContract.UploadImageEntry.COLUMN_TOTAL_IMG, length);
long result = db.insert(DataBaseContract.UploadImageEntry.TABLE_NAME, null, contentvalues);
Log.d(TAG, "insertDeckdata: " + result);
// }
db.close();
return result > 0;
}
public List<String> getUploadedImageDataList() {
SQLiteDatabase db = this.getReadableDatabase();
Type mOptionTarget = new TypeToken<List<String>>() {}.getType();
List<Uri> responses = new ArrayList<>();
List<String> targetList = null;
/* Gson gson = new Gson();
Type mOptionTarget = new TypeToken<List<Zone>>() {
}.getType();
*/
Cursor cursor = db.query(DataBaseContract.UploadImageEntry.TABLE_NAME, null, null, null, null, null, null);
if (cursor != null) {
Gson gson = new Gson();
if (cursor.moveToFirst()) {
do {
try {
// String typeCode = cursor.getString(cursor.getColumnIndex(DataBaseContract.UploadImageEntry.COLUMN_IMG_URL_NONINTEGRAL));
String typeUrl = cursor.getString(cursor.getColumnIndex(DataBaseContract.UploadImageEntry.COLUMN_IMAGE_URL_SCOR_EFFICIENCY));
// String typeUrl = cursor.getString(cursor.getColumnIndex(BampContract.UploadImageEntry.COLUMN_IMG_URL_SUPER_STRUCTURE));
// String typeUrl = cursor.getString(cursor.getColumnIndex(BampContract.UploadImageEntry.COLUMN_IMG_URL_SUB_STRUCTURE));
int fd = cursor.getInt(cursor.getColumnIndex(DataBaseContract.UploadImageEntry.COLUMN_TOTAL_IMG));
targetList = gson.fromJson(typeUrl, mOptionTarget);
//imageData.setStringUri(typeCode);
// imageData.setUri(Uri.parse(typeUrl));
/* ArrayList<String> playersList = (ArrayList<String>) gson.fromJson(playersString,
new TypeToken<ArrayList<String>>() {
}.getType());*/
responses.add(Uri.parse(typeUrl));
}
catch (SQLiteException e) {
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
} while (cursor.moveToNext());
cursor.close();
}
}
db.close();
return targetList;
}
public boolean updateImageList(List<String> mUriList,String bridgeId) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentvalues = new ContentValues();
for(int i=0; i<mUriList.size(); i++) {
contentvalues.put(DataBaseContract.UploadImageEntry.COLUMN_BRIDGE_ID, bridgeId);
contentvalues.put(DataBaseContract.UploadImageEntry.COLUMN_IMAGE_URL_SCOR_EFFICIENCY, mUriList.get(i));
contentvalues.put(DataBaseContract.UploadImageEntry.COLUMN_IMG_URL_NONINTEGRAL, mUriList.get(i));
contentvalues.put(DataBaseContract.UploadImageEntry.COLUMN_IMG_URL_SUPER_STRUCTURE, mUriList.get(i));
contentvalues.put(DataBaseContract.UploadImageEntry.COLUMN_IMG_URL_SUB_STRUCTURE, mUriList.get(i));
contentvalues.put(DataBaseContract.UploadImageEntry.COLUMN_TOTAL_IMG, mUriList.get(i));
}
int result = db.update(DataBaseContract.UploadImageEntry.TABLE_NAME, contentvalues,
DataBaseContract.UploadImageEntry.COLUMN_BRIDGE_ID + " = ? ",
new String[]{String.valueOf(bridgeId)});
return result>0;
}
}
package com.multipart.mainactivity;
import android.content.Context;
import android.net.Uri;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import java.util.List;
public class UploadImageAdapter extends RecyclerView.Adapter<UploadImageAdapter.ImageViewHolder> {
private static final String TAG = "UploadImageAdapter1";
private List<Uri> uriList = null;
private Context context;
// private OnSelectImageClickListener onSelectImageClickListener;
private ImageView imageViewnull;
public UploadImageAdapter(List<Uri> uriList, Context context) {
this.uriList = uriList;
this.context = context;
/*try {
onSelectImageClickListener = (OnSelectImageClickListener) fragment;
} catch (Exception e) {
Log.d(TAG, "UploadImageAdapter: " + e.getMessage());
}*/
}
@Override
public int getItemCount() {
return uriList.size();
}
@Override
public void onBindViewHolder(ImageViewHolder viewHolder, int i) {
Uri ci = uriList.get(i);
ImageView image = viewHolder.mImage;
if (ci != null) {
Log.d(TAG, "onBindViewHolder: image is " + ci);
Glide.with(context).load(ci).into(image);
} else {
Glide.with(context).load("").into(image);
}
// viewHolder.mImage.setImageResource(ci.getImage());
}
@Override
public ImageViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.
from(viewGroup.getContext()).
inflate(R.layout.recycler_list_item, viewGroup, false);
return new UploadImageAdapter.ImageViewHolder(itemView);
}
public class ImageViewHolder extends RecyclerView.ViewHolder {
private ImageView mImage;
private ImageView imageViewDelete;
private View mView;
public ImageViewHolder(View view) {
super(view);
this.mView = view;
mImage = (ImageView) view.findViewById(R.id.upload_image);
imageViewDelete = (ImageView) view.findViewById(R.id.imageview_recyler_delete);
mView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int position = getAdapterPosition();
Uri uri = uriList.get(position);
/* if (onSelectImageClickListener != null) {
onSelectImageClickListener.onSelectedImageClicked(uri, position);
}*/
imageViewDelete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int position = getAdapterPosition();
Uri uri = uriList.get(position);
/* if (onSelectImageClickListener != null) {
onSelectImageClickListener.onClickImageDelete(uri, position);
uriList.remove(position);
notifyItemRemoved(position);
Toast.makeText(context, "image succesfully deleted", Toast.LENGTH_SHORT).show();
}*/
}
});
}
});
}
}
public interface OnSelectImageClickListener {
public void onSelectedImageClicked(Uri uri, int postion);
public void onClickImageDelete(Uri uri, int postion);
}
}
package com.multipart.mainactivity;
import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.util.Log;
public class PermissionUtils {
public static final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 123;
public static final String TAG = "PermissionUtil";
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public static boolean checkPermission(final Context context)
{
int currentAPIVersion = Build.VERSION.SDK_INT;
if (currentAPIVersion >= android.os.Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) context, Manifest.permission.READ_EXTERNAL_STORAGE)) {
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context);
alertBuilder.setCancelable(true);
alertBuilder.setTitle("Permission necessary");
alertBuilder.setMessage("External storage permission is necessary");
alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener()
{
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
}
});
AlertDialog alert = alertBuilder.create();
alert.show();
} else
{
ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
}
return false;
}
else
{
return true;
}
}
else
{
return true;
}
}
public static boolean checkStoragePermission(Context context)
{
return ((Build.VERSION.SDK_INT < 23) || (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED));
}
public static boolean checkLocationPermission(final Context context)
{
int currentAPIVersion = Build.VERSION.SDK_INT;
if (currentAPIVersion >= android.os.Build.VERSION_CODES.M)
{
return (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED);
}
else
{
return true;
}
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public static boolean checkingCameraPermission(final Context context)
{
int currentAPIVersion = Build.VERSION.SDK_INT;
if (currentAPIVersion >= android.os.Build.VERSION_CODES.M)
{
return (ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED );
}
else
{
return true;
}
}
public static boolean verifyPermissions(int[] grantResults)
{
// At least one result must be checked.
if(grantResults.length < 1)
{
return false;
}
// Verify that each required permission has been granted, otherwise return false.
for (int result : grantResults)
{
Log.d(TAG, "verifyPermissions: ");
if (result != PackageManager.PERMISSION_GRANTED)
{
return false;
}
}
return true;
}
}
package com.multipart.mainactivity;
public class ResponseBody1 {
private String Status;
public String getStatus() {
return Status;
}
public void setStatus(String status) {
Status = status;
}
@Override
public String toString() {
return "ResponseBody1{" +
"Status='" + Status + '\'' +
'}';
}
}
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Attach Image"
android:textSize="18sp"
android:textColor="@android:color/white"
android:textStyle="bold"
android:textAllCaps="false"
android:layout_marginRight="32dp"
app:layout_constraintRight_toRightOf="parent"
android:layout_marginLeft="32dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginTop="20dp"
android:id="@+id/attachimage"
android:layout_marginStart="32dp"
android:layout_marginEnd="32dp" />
<ImageView
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginRight="8dp"
app:layout_constraintRight_toRightOf="parent"
android:layout_marginLeft="8dp"
app:layout_constraintLeft_toLeftOf="parent"
android:layout_marginTop="8dp"
app:layout_constraintTop_toBottomOf="@+id/attachimage"
android:scaleType="fitXY"
android:layout_marginStart="8dp"
android:layout_marginEnd="8dp"
android:id="@+id/viewImage"
app:layout_constraintHorizontal_bias="0.498"
android:layout_marginBottom="8dp"
app:layout_constraintBottom_toTopOf="@+id/recyclerView"
app:layout_constraintVertical_bias="0.502" />
<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="0dp"
android:layout_height="100dp"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="8dp"
app:layout_constraintBottom_toTopOf="@+id/button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent">
</android.support.v7.widget.RecyclerView>
<Button
android:id="@+id/button"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:text="Send"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.537"
app:layout_constraintStart_toStartOf="parent"/>
<Button
android:id="@+id/save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginBottom="8dp"
android:text="save"
app:layout_constraintBottom_toTopOf="@+id/recyclerView"
app:layout_constraintStart_toStartOf="parent"/>
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="12dp"
android:text="get"
app:layout_constraintBottom_toTopOf="@+id/recyclerView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.962"
app:layout_constraintStart_toEndOf="@+id/save"/>
</android.support.constraint.ConstraintLayout>
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths"/>
</provider>
?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="/"/>
</paths>
以上是关于xml 如何使用URI以json格式将多个图像保存到localdb的主要内容,如果未能解决你的问题,请参考以下文章
将图像作为数据 URI 存储在数据库 BLOB 中是否很糟糕?
我应该将 ArrayList 中的图像保存为 SQLite 字符串列中的 Json 对象吗
如何使用 FOR json API 调用将图像保存在 mysql 数据库中以进行移动应用程序开发?
如何使用 Ajax 以数组格式将多个图像从 MVC 视图发送到控制器?