Uploading an Image to Google Drive Using Drive API - android

I am trying to upload an image to the google drive using drive API. As the first step, I developed a code to upload a PDF file (file path is hard coded) to the google drive by following a tutorial.
PDF will be uploaded successfully but sometimes I get a time out message from the log. this may be because of my poor connection. But is there a proper way to handle this by the code when something like this happens?
Please guide me on how to upload an image instead of PDF by changing this code. I tried but I could not do it successfully. Please Help for this part. I am stuck here for two days
import android.util.Log;
import com.google.android.gms.tasks.Task;
import com.google.android.gms.tasks.Tasks;
import com.google.api.client.http.FileContent;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.model.File;
import java.io.IOException;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
public class DriveServiceHelper {
private final Executor mExecutor = Executors.newSingleThreadExecutor();
private Drive mDriveService;
public DriveServiceHelper(Drive mDriveService){
this.mDriveService = mDriveService;
}
public Task<String> createFilePdf(String filePath){
return Tasks.call(mExecutor, () -> {
File fileMetaData = new File();
fileMetaData.setName("MyPDFFile");
java.io.File file = new java.io.File(filePath);
FileContent mediaContent = new FileContent("application/pdf",file);
File myFile = null;
try {
myFile = mDriveService.files().create(fileMetaData,mediaContent).execute();
}catch (Exception e){
e.printStackTrace();
Log.i("myissue", e.getMessage());
}
if (myFile == null){
throw new IOException("Null result when requesting file creation");
}
return myFile.getId();
});
}
}
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.api.Scope;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
import java.util.Collections;
public class MainActivity extends AppCompatActivity {
DriveServiceHelper driveServiceHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
requestSignIn();
}
private void requestSignIn() {
GoogleSignInOptions signInOptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.requestScopes(new Scope(DriveScopes.DRIVE_FILE))
.build();
GoogleSignInClient client = GoogleSignIn.getClient(this,signInOptions);
startActivityForResult(client.getSignInIntent(),400);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode){
case 400:
if (resultCode == RESULT_OK){
handleSignInIntent(data);
break;
}
}
}
private void handleSignInIntent(Intent data) {
GoogleSignIn.getSignedInAccountFromIntent(data)
.addOnSuccessListener(new OnSuccessListener<GoogleSignInAccount>() {
#Override
public void onSuccess(GoogleSignInAccount googleSignInAccount) {
GoogleAccountCredential credential = GoogleAccountCredential
.usingOAuth2(MainActivity.this, Collections.singleton(DriveScopes.DRIVE_FILE));
credential.setSelectedAccount(googleSignInAccount.getAccount());
Drive googleDriveServices = new Drive.Builder(
AndroidHttp.newCompatibleTransport(),
new GsonFactory(),
credential)
.setApplicationName("uploadtodrive")
.build();
driveServiceHelper = new DriveServiceHelper(googleDriveServices);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
}
public void uploadPdfFile(View v){
ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setTitle("Uploading to google Drive");
progressDialog.setMessage("Please wait........");
progressDialog.show();
String filePath = "/storage/emulated/0/mypdf.pdf";
driveServiceHelper.createFilePdf(filePath).addOnSuccessListener(new OnSuccessListener<String>() {
#Override
public void onSuccess(String s) {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(),"Uploaded Successfully", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(),"Check your google Drive api key",Toast.LENGTH_SHORT).show();
}
});
}
}
Please Help for this part. I am stuck here for two days. thank you

Set appropriate MIME type:
In order to upload a specific file type to Drive, you have to specify its MIME type on the media content. In your case, this is handled by FileContent:
FileContent mediaContent = new FileContent("application/pdf",file);
So you would have to replace application/pdf with the appropriate MIME type (see for example the supported MIME types in G Suite documents). Possible MIME types for images include image/jpeg and image/png. For example, you could do this:
FileContent mediaContent = new FileContent("image/jpeg",file);
Note:
I'm assuming that you do have an image on the provided filePath.
Reference:
MIME types (IANA media types)

Related

Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference, iven that object is not null and initialize

i know that quastion has asked lot of times, but im realy dont found solution.
i know the error come couse the object intent is null, but how? if i choose a picture from a gallery?
this is the the error i get
E/Volley: [497] NetworkDispatcher.processRequest: Unhandled exception java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference
at java.net.URLEncoder.encode(URLEncoder.java:205)
at com.android.volley.Request.encodeParameters(Request.java:491)
at com.android.volley.Request.getBody(Request.java:477)
at com.android.volley.toolbox.HurlStack.addBodyIfExists(HurlStack.java:245)
at com.android.volley.toolbox.HurlStack.setConnectionParametersForRequest(HurlStack.java:219)
at com.android.volley.toolbox.HurlStack.executeRequest(HurlStack.java:97)
at com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:131)
at com.android.volley.NetworkDispatcher.processRequest(NetworkDispatcher.java:120)
at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:87)
D/EGL_emulation: eglMakeCurrent: 0xa7685060: ver 3 1 (tinfo 0xa7683280)
D/EGL_emulation: eglMakeCurrent: 0xa7685060: ver 3 1 (tinfo 0xa7683280)
this is my intent object part:
btnSelectImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Dexter.withActivity(uploadimage.this).withPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
.withListener(new PermissionListener() {
#Override
public void onPermissionGranted(PermissionGrantedResponse response) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent,"Select image"),1);
}
when i came to this part of the code, its fall, couse intent is null? but why is like that?
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if(requestCode==1 && requestCode==RESULT_OK && data!= null){
Uri filePath = data.getData();
try {
InputStream inputStream = getContentResolver().openInputStream(filePath);
bitmap = BitmapFactory.decodeStream(inputStream);
imageView.setImageBitmap(bitmap);
imageStore(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
what can be the problem?
i add to manifest the permission of READ_EXTERNAL_STORAGE .
this is all my code, if its relevant.
package com.example.yacovapp;
import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.android.volley.toolbox.StringRequest;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;
import com.karumi.dexter.Dexter;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.PermissionDeniedResponse;
import com.karumi.dexter.listener.PermissionGrantedResponse;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.single.PermissionListener;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import android.util.Base64;
public class uploadimage extends AppCompatActivity {
Button btnSelectImage, btnUploadImage;
ImageView imageView;
Bitmap bitmap;
String encodedImage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_uploadimage);
btnSelectImage = (Button) findViewById(R.id.btnSelectImage);
btnUploadImage = (Button) findViewById(R.id.buttonUploadImage);
imageView = findViewById(R.id.imView);
btnSelectImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Dexter.withActivity(uploadimage.this).withPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
.withListener(new PermissionListener() {
#Override
public void onPermissionGranted(PermissionGrantedResponse response) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent,"Select image"),1);
}
#Override
public void onPermissionDenied(PermissionDeniedResponse response) { }
#Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) { }
}).check();
}
});
btnUploadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
StringRequest request = new StringRequest(Request.Method.POST, "https://kerron.xyz/htdocs/images.php"
, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(uploadimage.this, response, Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(uploadimage.this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map <String, String> param = new HashMap<>();
param.put("image", encodedImage);
return param;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(uploadimage.this);
requestQueue.add(request);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if(requestCode==1 && requestCode==RESULT_OK && data!= null){
Uri filePath = data.getData();
try {
InputStream inputStream = getContentResolver().openInputStream(filePath);
bitmap = BitmapFactory.decodeStream(inputStream);
imageView.setImageBitmap(bitmap);
imageStore(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
private void imageStore(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte [] imageBytes = stream.toByteArray();
encodedImage = android.util.Base64.encodeToString(imageBytes,Base64.DEFAULT);
}
}
php file: (on server in the folder of public_html i create a folder htdocs and in this folder i have all my php files of the project)
<?php
$conn = mysqli_connect("78.140.191.36","kerronxy_yacov", "]k2oIl?WBRPh", "kerronxy_users");
if(isset($_POST['image'])) {
$target_dir = "htdocs/";
$image = $_POST['image'];
$imageStore = rand()."_".time()."jpeg";
$target_dir = $target_dir."/".$imageStore;
file_put_contents($target_dir, base64_decode($image));
$select = "INSERT INTO images (image) VALUES ($imageStore)";
$responce = mysqli_query($conn, $select);
if($responce) {
echo "Image Uploaded";
mysqli_close($conn);
}
}
The Logcat error indicates Nullpointer exception means that some of the variable are null at runtime.
You might have put some null value or key in your post parameters.Please make sure your postParams in your case
encodedImage is notnull before calling the request,because the keys or values that is returned from these methods should not be null.
Hope this helps..

Upload image to server from imagepath stored in Sqlite database in Android

The app does the following initially
Get data from user including image and store in Sqlite database.
image path is stored in Sqlite db.
The aim of the app is to upload the data automatically and I am able to do that successfully using BroadcaseReciever for text using Volley but stuck as I don't know how the process to upload the image from Android.
I am able to retrieve the image path from the database but not sure what to do next.
I have done fair research but not getting solution when comes to upload image to server from imagepath stored in Sqlite.
Below is image path example stored in sqlite. ( I am a beginner in Android)
/storage/emulated/0/Pictures/1547728376728.jpg
Below code that I am working from.
PS : I believe the purpose of getimagepath method would be to 1. find the image 2. convert it into bytes 3. pass to Volley. I am stuck on 1. and the code might be wrong.
package com.example.narendra.e5.activities.Connectivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.provider.MediaStore;
import android.util.Base64;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.example.narendra.e5.activities.database.DatabaseHelper;
import com.example.narendra.e5.activities.others.AppSingleton;
import com.example.narendra.e5.activities.others.MySingleton;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
public class NetworkMonitor extends BroadcastReceiver {
Context context;
public Bitmap bitmap;
#Override
public void onReceive(final Context context, Intent intent) {
if (checkNetworkConnection(context)){
Toast.makeText(context, "Hello hello", Toast.LENGTH_LONG).show();
final DatabaseHelper db=new DatabaseHelper(context);
SQLiteDatabase database=db.getWritableDatabase();
Cursor cursor=db.getdataIncoming(database);
while (cursor.moveToNext()){
final String incoming=cursor.getString(cursor.getColumnIndex(DatabaseHelper.INCOMINGTIME));
Toast.makeText(context, incoming, Toast.LENGTH_LONG).show();
final String INVENID=cursor.getString(cursor.getColumnIndex(DatabaseHelper.INVENIDAPP));
final String imageurl=cursor.getString(cursor.getColumnIndex(DatabaseHelper.SLIP_IMAGE));
// get image path from database and convert it into bitmap
// Uri uri = Uri.parse(imageurl);
// bitmap=MediaStore.Images.Media.getBitmap();
StringRequest stringRequest=new StringRequest(Request.Method.POST, DatabaseHelper.SERVER_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject=new JSONObject(response);
String getResponse=jsonObject.getString("response");
if (getResponse.equals("OK")){
Toast.makeText(context, "Response ok", Toast.LENGTH_LONG).show();
//db.deleteOfflineSaveOutgoingDetails(INVENID);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, "Response error", Toast.LENGTH_LONG).show();
}
}
){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params=new HashMap<>();
params.put("name",incoming);
// params.put("image",getimagepath(imageurl));
return params;
}
}
;
MySingleton.getInstance(context).addToRequestQue(stringRequest);
}
}
}
public boolean checkNetworkConnection(Context context){
ConnectivityManager connectivityManager= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo=connectivityManager.getActiveNetworkInfo();
return (networkInfo!=null && networkInfo.isConnected());
}
public String getimagepath(Intent imageurl){
// File imagepath=new File(String.valueOf(imageurl));
ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
Uri imagePath = imageurl.getData();
bitmap=BitmapFactory.decodeFile(String.valueOf(imagePath));
bitmap.compress(Bitmap.CompressFormat.JPEG,60,byteArrayOutputStream);
byte[] imgByte=byteArrayOutputStream.toByteArray();
return Base64.encodeToString(imgByte,Base64.DEFAULT);
}
}
For POST you can use JsonObjectRequest like this way. No need to override getParams method.
HashMap<String,String> maps=new HashMap<>();
maps.put("name",incoming);
maps.put("image",getimagepath(imageurl));
JsonObjectRequest jsonObjectRequest=new JsonObjectRequest(Request.Method.POST, YOUR_URL, new JSONObject(maps), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
jsonObjectRequest.setTag("TAG");
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(2,0f));
VolleySingleton.getInstance(context).addToRequestQueue(jsonObjectRequest);
I resolved the issue by correcting the method public String getimagepath(Intent imageurl)
to this:
public String getimagepath(String imageurl){
// File imagepath=new File(String.valueOf(imageurl));
ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
//Uri imagePath = imageurl.getData();
if (imageurl !=null){
// Uri imagePath = Uri.fromFile(new File(imageurl));
bitmap=BitmapFactory.decodeFile(imageurl);
bitmap.compress(Bitmap.CompressFormat.JPEG,60,byteArrayOutputStream);
byte[] imgByte=byteArrayOutputStream.toByteArray();
return Base64.encodeToString(imgByte,Base64.DEFAULT);
}
else {
return null;
}
}

Accessing users google drive without using Android Activities

I am trying to implement an android app where the app uploads images to users google drive. I successfully implemented the quick start guide given here. It is uploading the images but all the examples/samples of uploading the image using android Activity. I went through the documentation provided by google but it is very loosely coupled.
Is there any example/sample which upload the file without using an activity so that later I could convert it into a background service?
I reached the following point. Now, at this point GoogleSignIn.getLastSignedInAccount is returning null and I am looking for a solution where it picks the account and gets the permission from the user. In google sample it appears to do in startActivityForResult. I tried to look for that too but there is no Drive REST v3 samples for Android.
package com.mpathak.drivetesting;
import android.content.Context;
import android.content.IntentSender;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.drive.CreateFileActivityOptions;
import com.google.android.gms.drive.Drive;
import com.google.android.gms.drive.DriveClient;
import com.google.android.gms.drive.DriveContents;
import com.google.android.gms.drive.DriveResourceClient;
import com.google.android.gms.drive.MetadataChangeSet;
import com.google.android.gms.tasks.Task;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
public class DriveSample {
private GoogleSignInClient mGoogleSignInClient;
private DriveClient mDriveClient;
private DriveResourceClient mDriveResourceClient;
private Context _context;
private static final String TAG = "drive-Testing";
public DriveSample(Context context)
{
_context = context;
}
public void uploadFile()
{
GoogleSignInClient GoogleSignInClient = buildGoogleSignInClient();
mDriveClient = Drive.getDriveClient(_context, GoogleSignIn.getLastSignedInAccount(_context));
mDriveResourceClient =
Drive.getDriveResourceClient(_context, GoogleSignIn.getLastSignedInAccount(_context));
saveFileToDrive();
}
private GoogleSignInClient buildGoogleSignInClient() {
GoogleSignInOptions signInOptions =
new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestScopes(Drive.SCOPE_FILE)
.build();
return GoogleSignIn.getClient(_context, signInOptions);
}
private void saveFileToDrive() {
Log.i(TAG, "Creating new contents.");
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 10;
final Bitmap image = BitmapFactory.decodeFile("/DCIM/Camera/some_image.jpg", options);
mDriveResourceClient
.createContents()
.continueWithTask(
task -> createFileIntentSender(task.getResult(), image))
.addOnFailureListener(
e -> Log.w(TAG, "Failed to create new contents.", e));
}
private Task<Void> createFileIntentSender(DriveContents driveContents, Bitmap image) {
Log.i(TAG, "New contents created.");
OutputStream outputStream = driveContents.getOutputStream();
ByteArrayOutputStream bitmapStream = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.PNG, 100, bitmapStream);
try {
outputStream.write(bitmapStream.toByteArray());
} catch (IOException e) {
Log.w(TAG, "Unable to write file contents.", e);
}
MetadataChangeSet metadataChangeSet =
new MetadataChangeSet.Builder()
.setMimeType("image/jpeg")
.setTitle("Android Photo.png")
.build();
CreateFileActivityOptions createFileActivityOptions =
new CreateFileActivityOptions.Builder()
.setInitialMetadata(metadataChangeSet)
.setInitialDriveContents(driveContents)
.build();
return mDriveClient
.newCreateFileActivityIntentSender(createFileActivityOptions)
.continueWith(
task -> {
return null;
});
}
}

Using Retrofits2 upload file to server in android

Why can not I upload files to the server? When I used Log.d to print to the log screen, it reported an error can not connect to 192.168.10.2:8080 although I have asked for permission to the Internet and read the internal memory of the device.
APIUtils.java
import android.provider.ContactsContract;
public class APIUtils {
public static final String Base_Url = "http://192.168.10.2:8080/Quanlysinhvien/";
public static DataClient getData(){
return RetrofitClient.getClient(Base_Url).create(DataClient.class);
}
}
DataClient.java
import okhttp3.MultipartBody;
import retrofit2.Call;
import retrofit2.http.Multipart;
import retrofit2.http.POST;
import retrofit2.http.Part;
public interface DataClient {
#Multipart
#POST("uploadhinhanh.php")
Call<String> UploadPhot(#Part MultipartBody.Part phto);
}
RetrofitClient.java
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class RetrofitClient {
private static Retrofit retrofit = null;
public static Retrofit getClient(String baseurl){
OkHttpClient builder = new OkHttpClient.Builder()
.readTimeout(5000, TimeUnit.MILLISECONDS)
.writeTimeout(5000, TimeUnit.MILLISECONDS)
.connectTimeout(10000, TimeUnit.MILLISECONDS)
.retryOnConnectionFailure(true)
.build();
Gson gson = new GsonBuilder().setLenient().create();
retrofit = new Retrofit.Builder()
.baseUrl(baseurl)
.client(builder)
.addConverterFactory(GsonConverterFactory.create())
.build();
return retrofit;
}
}
DangKyActivity.java
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import com.example.nhutkhanh.demoretrofit2.Retrofit2.APIUtils;
import com.example.nhutkhanh.demoretrofit2.Retrofit2.DataClient;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;
import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Callback;
import retrofit2.Response;
public class DangKyActivity extends AppCompatActivity {
ImageView imgdangky;
EditText edtUsername, edtPassword;
Button btnhuy, btnxacnhan;
int Request_Code_Image = 123;
String realpath = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dang_ky);
anhxa();
imgdangky.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, Request_Code_Image);
}
});
btnxacnhan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
File file = new File(realpath);
String file_path = file.getAbsolutePath();
String[] mangtenfile = file_path.split("\\.");
file_path = mangtenfile[0] + System.currentTimeMillis() + "." + mangtenfile[1];
RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/from-data"), file);
MultipartBody.Part body = MultipartBody.Part.createFormData("uploaded_file", file_path, requestBody);
DataClient dataClient = APIUtils.getData();
retrofit2.Call<String> callback = dataClient.UploadPhot(body);
callback.enqueue(new Callback<String>() {
#Override
public void onResponse(retrofit2.Call<String> call, Response<String> response) {
if(response != null){
String message = response.body();
Log.d("AAA", message);
}
}
#Override
public void onFailure(retrofit2.Call<String> call, Throwable t) {
Log.d("BBB", "Lỗi " + t.getMessage());
}
});
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == Request_Code_Image && resultCode == RESULT_OK && data != null){
Uri uri = data.getData();
realpath = getRealPathFromURI(uri);
try {
InputStream inputStream = getContentResolver().openInputStream(uri);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
imgdangky.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
public String getRealPathFromURI (Uri contentUri) {
String path = null;
String[] proj = { MediaStore.MediaColumns.DATA };
Cursor cursor = getContentResolver().query(contentUri, proj, null, null, null);
if (cursor.moveToFirst()) {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
path = cursor.getString(column_index);
}
cursor.close();
return path;
}
private void anhxa() {
imgdangky = (ImageView)findViewById(R.id.imageViewDK);
edtPassword = (EditText)findViewById(R.id.editTextDKMK);
edtUsername = (EditText)findViewById(R.id.editTextDKTK);
btnhuy = (Button)findViewById(R.id.buttonHuy);
btnxacnhan = (Button)findViewById(R.id.buttonXacNhan);
}
}
MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}

Bluemix: How to insert JSON in Cloudant in Android with Replicator?

I am finding it difficult to make this simple upload. I've used all encontrandos tutorials on the internet such as Bluelist and android-sync. I already have a database created within the service. My code is as follows:
MainActivity.java
package com.example.engenharia.replicator;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
import com.cloudant.sync.datastore.BasicDocumentRevision;
import com.cloudant.sync.datastore.Datastore;
import com.cloudant.sync.datastore.DatastoreException;
import com.cloudant.sync.datastore.DatastoreManager;
import com.cloudant.sync.datastore.DocumentBodyFactory;
import com.cloudant.sync.datastore.DocumentException;
import com.cloudant.sync.datastore.DocumentRevision;
import com.cloudant.sync.datastore.MutableDocumentRevision;
import com.cloudant.sync.query.IndexManager;
import com.cloudant.sync.replication.ReplicatorBuilder;
import com.cloudant.sync.replication.Replicator;
import java.io.File;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
public class MainActivity extends AppCompatActivity {
private static final String DATASTORE_MANGER_DIR = "data";
private Datastore DataStore;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
URI uri = new URI(my_uri);
File path = getApplicationContext().getDir(DATASTORE_MANGER_DIR, Context.MODE_PRIVATE);
DatastoreManager manager = new DatastoreManager(path.getAbsolutePath());
DataStore = manager.openDatastore("banco0"); //banco0 is the DB created in Cloudant NoSQL service.
// Create a replicator that replicates changes from the local
// datastore to the remote database.
Replicator replicator = ReplicatorBuilder.push().to(uri).from(DataStore).build();
// Use a CountDownLatch to provide a lightweight way to wait for completion
CountDownLatch latch = new CountDownLatch(1);
Listener listener = new Listener(latch);
replicator.getEventBus().register(listener);
replicator.start();
latch.await();
replicator.getEventBus().unregister(listener);
if(replicator.getState() != Replicator.State.COMPLETE){
System.out.println("Error replicating TO remote");
System.out.println(listener.error);
} else {
System.out.println(String.format("Replicated %d documents in %d batches",
listener.documentsReplicated, listener.batchesReplicated));
}
}catch (Exception e){
e.printStackTrace();
}
}
public DocumentRevision createDocument() {
MutableDocumentRevision rev = new MutableDocumentRevision();
rev.body = DocumentBodyFactory.create(HashMap());
try {
return DataStore.createDocumentFromRevision(rev);
} catch (DocumentException e) {
//throw new RuntimeException(e);
e.printStackTrace();
return null;
}
}
public Map<String, Object> HashMap() {
HashMap<String, Object> map = new HashMap<String, Object>();
HashMap<String, String> map1 = new HashMap<String, String>();
map1.put("Street", "121");
map1.put("Street1", "12112");
map1.put("Street123", "1211111");
String[] array1 = new String[]{"Cloudant", "NoSQL", "JSON"};
map.put("address", map1);
map.put("description", "This is sample description");
map.put("skills", array1);
return map;
}
}
listener.java
package com.example.engenharia.replicator;
import com.cloudant.sync.notifications.ReplicationCompleted;
import com.cloudant.sync.notifications.ReplicationErrored;
import com.cloudant.sync.replication.ErrorInfo;
import com.google.common.eventbus.Subscribe;
import com.cloudant.sync.replication.ReplicatorBuilder;
import com.cloudant.sync.replication.Replicator;
import java.util.concurrent.CountDownLatch;
/**
* Created by engenharia on 19/08/16.
*/
public class Listener {
private final CountDownLatch latch;
public ErrorInfo error = null;
public int documentsReplicated;
public int batchesReplicated;
Listener(CountDownLatch latch) {
this.latch = latch;
}
#Subscribe
public void complete(ReplicationCompleted event) {
this.documentsReplicated = event.documentsReplicated;
this.batchesReplicated = event.batchesReplicated;
latch.countDown();
}
#Subscribe
public void error(ReplicationErrored event) {
this.error = event.errorInfo;
latch.countDown();
}
}
Executing this code I have the follow error:
CouchException: error: forbidden, reason: server_admin access is
required for this request, statusCode: 403, msg: null, cause: null
But I am the admin!
How do I fix the problem or what is the solution?

Categories

Resources