Not so Surprisingly, none of the solutions above worked for me. The REASON, well in all the above answers they're using the .P12 file, while I got a JSON file as an api key. There are these two different keys which I didn't know at first and I thought I was doing wrong and after one intense day of going through google docs, stackoverflow I was finally able to upload to the storage. None of the above answers show on how to do it for a JSON file and the code is tad bit simple so I'm posting this answers, hope this helps someone:
UploadFile.java
public class UploadFile {
public static Storage setCredentials(InputStream credentialFile) {
InputStream credentialsStream = null;;
Credentials credentials = null;
try {
credentialsStream = credentialFile;
credentials = GoogleCredentials.fromStream(credentialsStream);
} catch (IOException e) {
e.printStackTrace();
return null;
}
return StorageOptions.newBuilder()
.setProjectId("YOUR_PROJECT_ID").setCredentials(credentials)
.build().getService();
}
@RequiresApi(api = Build.VERSION_CODES.O)
public static String transmitImageFile(Storage storage, String srcFileName, String newName) {
File file = new File(srcFileName);
byte[] fileContent = null;
try {
fileContent = Files.readAllBytes(file.toPath());
} catch (IOException e) {
e.printStackTrace();
return null;
}
if (fileContent == null)
return null;
if (fileContent.length == 0)
return null;
BlobInfo.Builder newBuilder = Blob.newBuilder(BucketInfo.of("YOUR_BUCKET_NAME"), newName);
BlobInfo blobInfo = newBuilder.setContentType("image/png").build();
Blob blob = storage.create(blobInfo, fileContent);
String bucket = blob.getBucket();
String contentType = blob.getContentType();
Log.e("TAG", "transmitImageFile: "+contentType);
System.out.println("File " + srcFileName + " uploaded to bucket " + bucket + " as " + newName);
return newName;
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
private String currentPhotoPath;
private String imageName;
public static final int REQUEST_IMAGE_CAPTURE = 1;
private File photoFile = null;
private String[] permissions;
public static final int PERMISSION_REQ_CODE = 200;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView= findViewById(R.id.textView);
permissions = new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_PHONE_STATE, Manifest.permission.ACCESS_COARSE_LOCATION};
PermissionsRequest();
textView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dispatchTakePictureIntent();
ReadFromAsset();
}
});
}
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
try {
photoFile = createImageFile();
} catch (Exception ex) {
ex.printStackTrace();
}
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this, getPackageName(), photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
String fileName = "temp";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(imageFileName, ".jpg");
// Save a file: path for use with ACTION_VIEW intents
currentPhotoPath = image.getAbsolutePath();
imageName = image.getName();
return image;
}
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
Storage storage = UploadFile.setCredentials(getAssets().open("GoogleMapDemo.json"));
UploadFile.transmitImageFile(storage, currentPhotoPath, "sampleImage.jpg");
} catch (IOException e) {
e.printStackTrace();
}
}
});
thread.start();
Log.e("TAG", "ImagePath: " + currentPhotoPath);
Log.e("TAG", "ImageName: " + imageName);
}
}
private void PermissionsRequest() {
if (ContextCompat.checkSelfPermission(getApplicationContext(), permissions[0]) != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(getApplicationContext(), permissions[4]) != PackageManager.PERMISSION_GRANTED) {
AlertDialog.Builder builder1 = new AlertDialog.Builder(MainActivity.this);
builder1.setTitle("AAtten");
builder1.setMessage("Permissions");
builder1.setCancelable(false);
builder1.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
acceptPermissions();
}
});
builder1.setNegativeButton("SAIR", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
//Creating dialog box
AlertDialog alert1 = builder1.create();
alert1.show();
}
}
private void acceptPermissions() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(getApplicationContext(), permissions[0]) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(getApplicationContext(), permissions[1]) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(getApplicationContext(), permissions[2]) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(getApplicationContext(), permissions[3]) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(getApplicationContext(), permissions[4]) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(getApplicationContext(), permissions[5]) != PackageManager.PERMISSION_GRANTED)
requestPermissions(permissions, PERMISSION_REQ_CODE);
else {
if ((ContextCompat.checkSelfPermission(getApplicationContext(), permissions[0]) != PackageManager.PERMISSION_GRANTED) && (ContextCompat.checkSelfPermission(getApplicationContext(), permissions[1]) != PackageManager.PERMISSION_GRANTED) && (ContextCompat.checkSelfPermission(getApplicationContext(), permissions[2]) != PackageManager.PERMISSION_GRANTED) && (ContextCompat.checkSelfPermission(getApplicationContext(), permissions[3]) != PackageManager.PERMISSION_GRANTED) || ContextCompat.checkSelfPermission(getApplicationContext(), permissions[4]) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(getApplicationContext(), permissions[5]) != PackageManager.PERMISSION_GRANTED)
requestPermissions(permissions, PERMISSION_REQ_CODE);
}
}
}
private void ReadFromAsset(){
String string = "";
try {
//InputStream inputStream = new FileInputStream(String.valueOf(getAssets().open("key.p12")));
InputStream inputStream = getAssets().open("GoogleMapDemo.json");
int size = inputStream.available();
byte[] buffer = new byte[size];
inputStream.read(buffer);
string = new String(buffer);
} catch (IOException e) {
e.printStackTrace();
}
Log.e("TAG", "ReadFromAsset: "+string );
}
}
Now google on how to create a asset folder in the app and add the json key file in that folder. In onActivityResult class you'll pass the name of the json file.
And in UploadImage class give your projectID and bucketName in respective feilds. You can find the projectID in that json.file
Dependencies
android{
packagingOptions{
exclude 'META-INF/INDEX.LIST'
exclude 'META-INF/DEPENDENCIES'
}
}
implementation platform('com.google.cloud:libraries-bom:16.2.1')
implementation 'com.google.cloud:google-cloud-storage'
implementation 'com.google.cloud:google-cloud-core:1.94.0'
Maifest
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE">
<application
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.example.personalgooglestoragecheck"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
</application
file-path.xml
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-files-path
name="my_images"
path="/" />
<external-path
name="external"
path="." />
<cache-path
name="cache"
path="." />
<external-cache-path
name="external_cache"
path="." />
<files-path
name="files"
path="." />
</paths>
Hope this helps someone. Any questions feel free to ask.
EDIT 1:
Apparently Files.readAllBytes() is introduced in Java 7 and only works on Android api 26 or above. If you want to target lower versions use fileinputstream and remove all the @requireannotation tags.