Android Upload Images(Okhttp3) without interface - java

I am a student, just learn Android develop few days,
There have a question about how can upload a image in background without user interface.
I'm mean there already have the file path ,I don't need the user click to select images,When user run the activity,the image with auto upload. I know i can using okhttp3 ,such as below video:
https://www.youtube.com/watch?v=K48jnbM8yS4
(I'm think this is good video ,is my stupid not know how can modify the code )
However, in the video , the MainActivity such as this
package app.file_upload;
import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.Button;
import com.nbsp.materialfilepicker.MaterialFilePicker;
import com.nbsp.materialfilepicker.ui.FilePickerActivity;
import java.io.File;
import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class UploadActivity extends AppCompatActivity {
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
if(ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},100);
return;
}
}
enable_button();
}
private void enable_button() {
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new MaterialFilePicker()
.withActivity(UploadActivity.this)
.withRequestCode(10)
.start();
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if(requestCode == 100 && (grantResults[0] == PackageManager.PERMISSION_GRANTED)){
enable_button();
}else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},100);
}
}
}
ProgressDialog progress;
#Override
protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
if(requestCode == 10 && resultCode == RESULT_OK){
progress = new ProgressDialog(UploadActivity.this);
progress.setTitle("Uploading");
progress.setMessage("Please wait...");
progress.show();
Thread t = new Thread(new Runnable() {
#Override
public void run() {
File f = new File(data.getStringExtra(FilePickerActivity.RESULT_FILE_PATH));
String content_type = getMimeType(f.getPath());
String file_path = f.getAbsolutePath();
OkHttpClient client = new OkHttpClient();
RequestBody file_body = RequestBody.create(MediaType.parse(content_type),f);
RequestBody request_body = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("type",content_type)
.addFormDataPart("uploaded_file",file_path.substring(file_path.lastIndexOf("/")+1), file_body)
.build();
Request request = new Request.Builder()
.url("URL_TO_THE_SERVER/YOUR_SCRIPT.php")
.post(request_body)
.build();
try {
Response response = client.newCall(request).execute();
if(!response.isSuccessful()){
throw new IOException("Error : "+response);
}
progress.dismiss();
} catch (IOException e) {
e.printStackTrace();
}
}
});
t.start();
}
}
private String getMimeType(String path) {
String extension = MimeTypeMap.getFileExtensionFromUrl(path);
return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
}
}
for my case , I only upload the image ,but i not need the user interface (Such as button to select picture),So I'm try to modify the code ,such as below :
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
File f = new File(" /storage/emulated/0/Android/data/abc.package.name/files/images.jpg");
String content_type = getMimeType(f.getPath());
String file_path = f.getAbsolutePath();
OkHttpClient client = new OkHttpClient();
RequestBody file_body = RequestBody.create(MediaType.parse(content_type),f);
RequestBody request_body = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("type",content_type)
.addFormDataPart("uploaded_file",file_path.substring(file_path.lastIndexOf("/")+1), file_body)
.build();
Request request = new Request.Builder()
.url("My php File Link ")
.post(request_body)
.build();
try {
Response response = client.newCall(request).execute();
if(!response.isSuccessful()){
throw new IOException("Error : "+response);
}
} catch (IOException e) {
e.printStackTrace();
}
}
private String getMimeType(String path) {
String extension = MimeTypeMap.getFileExtensionFromUrl(path);
return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
}
}
I'm only need to use okhttp3 to upload image in backround task , no need any interface ,But I'm feel difficult for me ,maybe i am new user of android studio...>_<
Can anyone help me to modify the code ....
My php code also here:
<?php
$file_path = "images/";
$file_path = $file_path . basename($_FILES['uploaded_file']['name']);
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'],$file_path)) {
echo "success";
}else {
echo "error";
}
?>

Related

Getting a null object reference on getting token from SharedPreferences using Retrofit2 GET request

I'm trying to get an access_token from my SharedPreferences to pass into the Body of a Retrofit2 GET request. When I login I get an access_token and save it in SharedPreferences, but when I try and get the value of the SharedPreference I get a null object reference error but I am unsure as to why.
The full error log can be found below:
Logcat log:
2020-08-27 10:23:29.597 2825-2974/com.example.dentdevils E/AndroidRuntime: FATAL EXCEPTION: OkHttp Dispatcher
Process: com.example.dentdevils, PID: 2825
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.dentdevils.helper.retrofit.oauth2.PreferenceClass.getToken()' on a null object reference
at com.example.dentdevils.helper.retrofit.oauth2.client.cCustomerService$1.intercept(cCustomerService.java:41)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:142)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:117)
at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:229)
at okhttp3.RealCall$AsyncCall.execute(RealCall.java:172)
at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)
at java.util.concurrent.ThreadPoolExecutor.processTask(ThreadPoolExecutor.java:1187)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1152)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:929)
My classes can be found below:
PreferenceClass.java
package com.example.dentdevils.helper.retrofit.oauth2;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
public class PreferenceClass extends Application {
public static final String PREFERENCE = "accessTokenPref";
private SharedPreferences sharedPreferences;
public PreferenceClass() {
super();
}
public PreferenceClass(Context context) {
sharedPreferences = context.getSharedPreferences(PREFERENCE, Context.MODE_PRIVATE);
}
public String getToken() {
String token = sharedPreferences.getString("token", "");
return token;
}
public void setToken(String token) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("token", token);
editor.commit();
}
public void clearToken() {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.remove("token");
editor.commit();
}
}
cCustomerService.java
package com.example.dentdevils.helper.retrofit.oauth2.client;
import android.content.Context;
import android.content.SharedPreferences;
import com.example.dentdevils.helper.retrofit.oauth2.OauthConstant;
import com.example.dentdevils.helper.retrofit.oauth2.PreferenceClass;
import java.io.IOException;
import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.Buffer;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class cCustomerService {
private static OkHttpClient httpClient = new OkHttpClient.Builder()
.addInterceptor(new Interceptor() {
private PreferenceClass preferenceClass;
public PreferenceClass getPreferenceClass() {
return preferenceClass;
}
#Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Request.Builder requestBuilder = request.newBuilder();
RequestBody formBody = new FormBody.Builder()
.add("access_token", getPreferenceClass().getToken())
.build();
String postBodyToString = bodyToString(request.body());
postBodyToString += ((postBodyToString.length() > 0) ? "&" : "") + bodyToString(formBody);
request = requestBuilder.post(RequestBody.create(MediaType.parse("application/x-www-form-urlencoded;charset=UTF-8"), postBodyToString))
.build();
return chain.proceed(request);
}
}).build();
private static Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl(OauthConstant.DATA_SERVER_URL)
.addConverterFactory(GsonConverterFactory.create());
public static Retrofit retrofit = builder.client(httpClient).build();
public static <S> S createService(Class<S> serviceClass) {
builder.client(httpClient).build();
retrofit = builder.build();
return retrofit.create(serviceClass);
}
public static String bodyToString(final RequestBody requestBody) {
try {
final RequestBody copy = requestBody;
final Buffer buffer = new Buffer();
if (copy != null) {
copy.writeTo(buffer);
} else {
return "";
}
return buffer.readUtf8();
} catch (IOException e) {
return "didn't work";
}
}
}
MainActivity.java - This is where I save the access_token
package com.example.dentdevils;
import android.Manifest;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.dentdevils.helper.retrofit.oauth2.PreferenceClass;
import com.example.dentdevils.helper.retrofit.oauth2.client.cOauthService;
import com.example.dentdevils.helper.retrofit.oauth2.request.AccessToken;
import com.example.dentdevils.helper.retrofit.oauth2.response.AccessTokenResponse;
import com.example.dentdevils.helper.retrofit.oauth2.service.OauthService;
import com.example.dentdevils.ui.HomeActivity;
import retrofit2.Call;
import retrofit2.Callback;
public class MainActivity extends AppCompatActivity {
public static final int MY_PERMISSIONS_REQUEST_CAMERA = 99;
private static final String TAG = MainActivity.class.getSimpleName();
private Button btnLogin;
private EditText inputEmail;
private EditText inputPassword;
private ProgressDialog progressDialog;
private PreferenceClass preferenceClass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
checkCameraPermission();
preferenceClass = new PreferenceClass(this);
inputEmail = findViewById(R.id.email);
inputPassword = findViewById(R.id.txtEditPassword);
btnLogin = findViewById(R.id.btnLogin);
progressDialog = new ProgressDialog(this);
progressDialog.setCancelable(false);
btnLogin.setOnClickListener(v -> getAccessToken());
}
public void getAccessToken() {
progressDialog.show();
AccessToken accessToken = new AccessToken();
accessToken.setClient_id("client");
accessToken.setClient_secret("client");
accessToken.setGrant_type("client_credentials");
OauthService oauthService = cOauthService.createService(OauthService.class, inputEmail.getText().toString(), inputPassword.getText().toString());
Call<AccessTokenResponse> call = oauthService.fetchAccessToken(accessToken);
call.enqueue(new Callback<AccessTokenResponse>() {
#Override
public void onResponse(Call<AccessTokenResponse> call, retrofit2.Response<AccessTokenResponse> response) {
if (response.isSuccessful()) {
String a = response.body().getAccess_token();
preferenceClass.setToken(a);
progressDialog.dismiss();
Intent i = new Intent(getApplicationContext(), HomeActivity.class);
startActivity(i);
} else {
progressDialog.dismiss();
Toast.makeText(MainActivity.this, "There was an error, please try again!", Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call<AccessTokenResponse> call, Throwable t) {
Log.d("Error", t.getMessage());
}
});
}
public boolean checkCameraPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
new AlertDialog.Builder(this)
.setTitle("Permission Required!")
.setMessage("This app requires the camera permission to be able to capture images of car damage. Please grant the app access to the camera by going into your Settings > Apps > Apps > Dent Devils > Permissions > Camera, then press Allow.")
.setPositiveButton("", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CAMERA}, MY_PERMISSIONS_REQUEST_CAMERA);
}
})
.create()
.show();
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, MY_PERMISSIONS_REQUEST_CAMERA);
}
return false;
} else {
return true;
}
}
}
ViewCustomers.java - This is where I try to access the token
package com.example.dentdevils;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Build;
import android.os.Bundle;
import android.widget.Toast;
import com.example.dentdevils.helper.retrofit.oauth2.PreferenceClass;
import com.example.dentdevils.helper.retrofit.oauth2.client.cCustomerService;
import com.example.dentdevils.helper.retrofit.oauth2.response.CustomerResponse;
import com.example.dentdevils.helper.retrofit.oauth2.service.CustomerService;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class ViewCustomers extends AppCompatActivity {
private PreferenceClass preferenceClass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_customers);
preferenceClass = new PreferenceClass(this);
getAllCustomers();
}
public void getAllCustomers() {
CustomerService customerService = cCustomerService.createService(CustomerService.class);
Call<List<CustomerResponse>> callArray = customerService.getCustomers();
callArray.enqueue(new Callback<List<CustomerResponse>>() {
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public void onResponse(Call<List<CustomerResponse>> call, Response<List<CustomerResponse>> response) {
if (response.isSuccessful()) {
Toast.makeText(ViewCustomers.this, "Success!", Toast.LENGTH_LONG).show();
// List<CustomerResponse> customers = response.body();
// customers.forEach(customer -> Log.d("CUSTOMERS", customer.getName()));
} else {
Toast.makeText(ViewCustomers.this, "There was an error, please try again!", Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call<List<CustomerResponse>> call, Throwable t) {
Toast.makeText(ViewCustomers.this, "Failed!", Toast.LENGTH_LONG).show();
}
});
}
}
I'm not sure where I'm going wrong, any help would be appreciated!

Unable to fetch file from google drive

I am working on a project where user can upload a document to my server. This file can be selected either from local storage or a cloud storage ,say google drive. When i click on the file from file chooser all i am receiving is an account info and doc info as a uri, When i tried to fetch doc from this URI it is showing FileNotFound . I have gone through Drive API also but It is a bit confusing to me. Following are the points i came accross while trying Google Drive API:
1. How to select file from local storage.
2. How do I get FileId form the selected file.
I tried with the following code snippet:
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.setType("**/");
startActivityForResult(intent, 1000);
and In onActivityResult
#Override
public void onActivityResult(int requestCode, int resultCode,
Intent resultData) {
// The ACTION_OPEN_DOCUMENT intent was sent with the request code
// READ_REQUEST_CODE. If the request code seen here doesn't match, it's the
// response to some other intent, and the code below shouldn't run at all.
if (requestCode == 1000 && resultCode == Activity.RESULT_OK) {
// The document selected by the user won't be returned in the intent.
// Instead, a URI to that document will be contained in the return intent
// provided to this method as a parameter.
// Pull that URI using resultData.getData().
Uri uri = null;
if (resultData != null) {
uri = resultData.getData();
Log.i("URI", "Uri: " + uri.toString());
try {
readTextFromUri(uri);
getMimeType(this,uri);
} catch (IOException e) {
e.printStackTrace();
}
// showImage(uri);
}
}
}
private String readTextFromUri(Uri uri) throws IOException {
// FileInputStream fileInputStream=new FileInputStream(uri.)
InputStream inputStream = getContentResolver().openInputStream(uri);
BufferedReader reader = new BufferedReader(new InputStreamReader(
inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
// fileInputStream.close();
// parcelFileDescriptor.close();
return stringBuilder.toString();
}
Conclusion:
Can anyone please send me a link how to upload a document(I should even check the extension of the document) from both local storage and Google drive in a File chooser.
package com.example.ayyappaboddupalli.gdrive;
import android.content.Intent;
import android.content.IntentSender;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
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.drive.Drive;
import com.google.android.gms.drive.DriveClient;
import com.google.android.gms.drive.DriveContents;
import com.google.android.gms.drive.DriveFile;
import com.google.android.gms.drive.DriveId;
import com.google.android.gms.drive.DriveResourceClient;
import com.google.android.gms.drive.OpenFileActivityOptions;
import com.google.android.gms.drive.query.Filters;
import com.google.android.gms.drive.query.SearchableField;
import com.google.android.gms.tasks.Continuation;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.android.gms.tasks.TaskCompletionSource;
import com.google.api.services.drive.model.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashSet;
import java.util.Set;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "Google drive";
private static final String SIGN_IN = "Sign In";
private static final String DOWNLOAD_FILE = "Download file";
private static final int REQUEST_CODE_SIGN_IN = 0;
private static final int REQUEST_CODE_OPEN_ITEM = 1;
private static final int REQUEST_WRITE_STORAGE = 112;
private GoogleSignInAccount signInAccount;
private Set<Scope> requiredScopes;
private DriveClient mDriveClient;
private DriveResourceClient mDriveResourceClient;
private OpenFileActivityOptions openOptions;
private TaskCompletionSource<DriveId> mOpenItemTaskSource;
private java.io.File storageDir;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView( R.layout.activity_main);
initialize();
requestPermission();
signInAccount = GoogleSignIn.getLastSignedInAccount(this);
if (signInAccount != null && signInAccount.getGrantedScopes().containsAll(requiredScopes)) {
initializeDriveClient(signInAccount);
} else {
// onDriveClientReady();
signIn();
}
Button button=(Button)findViewById(R.id.Submit);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onDriveClientReady();
}
});
}
private void showMessage(String message) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQUEST_CODE_SIGN_IN:
if (resultCode == RESULT_OK) {
Task<GoogleSignInAccount> getAccountTask = GoogleSignIn.getSignedInAccountFromIntent(data);
if (getAccountTask.isSuccessful()) {
initializeDriveClient(getAccountTask.getResult());
showMessage("Sign in successfully.");
// binding.btnSubmit.setText(DOWNLOAD_FILE);
} else {
showMessage("Sign in failed.");
}
} else {
showMessage("Sign in failed.");
}
break;
case REQUEST_CODE_OPEN_ITEM:
if (resultCode == RESULT_OK) {
DriveId driveId = data.getParcelableExtra(OpenFileActivityOptions.EXTRA_RESPONSE_DRIVE_ID);
mOpenItemTaskSource.setResult(driveId);
} else {
mOpenItemTaskSource.setException(new RuntimeException("Unable to open file"));
}
break;
}
}
private void initialize() {
requiredScopes = new HashSet<>(2);
requiredScopes.add(Drive.SCOPE_FILE);
requiredScopes.add(Drive.SCOPE_APPFOLDER);
openOptions = new OpenFileActivityOptions.Builder()
.setSelectionFilter(Filters.eq(SearchableField.MIME_TYPE, "application/pdf"))
.setActivityTitle("Select file")
.build();
}
private void initializeDriveClient(GoogleSignInAccount signInAccount) {
mDriveClient = Drive.getDriveClient(getApplicationContext(), signInAccount);
mDriveResourceClient = Drive.getDriveResourceClient(getApplicationContext(), signInAccount);
}
private void signIn() {
GoogleSignInOptions signInOptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestScopes(Drive.SCOPE_FILE)
.requestScopes(Drive.SCOPE_APPFOLDER)
.build();
GoogleSignInClient googleSignInClient = GoogleSignIn.getClient(this, signInOptions);
startActivityForResult(googleSignInClient.getSignInIntent(), REQUEST_CODE_SIGN_IN);
}
private void onDriveClientReady() {
mOpenItemTaskSource = new TaskCompletionSource<>();
mDriveClient.newOpenFileActivityIntentSender(openOptions)
.continueWith(new Continuation<IntentSender, Void>() {
#Override
public Void then(#NonNull Task<IntentSender> task) throws Exception {
startIntentSenderForResult(
task.getResult(), REQUEST_CODE_OPEN_ITEM, null, 0, 0, 0);
return null;
}
});
Task<DriveId> tasks = mOpenItemTaskSource.getTask();
tasks.addOnSuccessListener(this,
new OnSuccessListener<DriveId>() {
#Override
public void onSuccess(DriveId driveId) {
retrieveContents(driveId.asDriveFile());
}
})
.addOnFailureListener(this, new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
showMessage("File not selected.");
}
});
}
private void retrieveContents(final DriveFile file) {
// [START open_file]
final Task<DriveContents> openFileTask = mDriveResourceClient.openFile(file, DriveFile.MODE_READ_ONLY);
// [END open_file]
// [START read_contents]
openFileTask.continueWithTask(new Continuation<DriveContents, Task<Void>>() {
#Override
public Task<Void> then(#NonNull Task<DriveContents> task) throws Exception {
DriveContents contents = task.getResult();
Log.v(TAG, "File name : " + contents.toString());
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
InputStream input = contents.getInputStream();
try {
java.io.File file = new java.io.File(getExternalFilesDir(null), "umesh.pdf");
Log.v(TAG, storageDir + "");
OutputStream output = new FileOutputStream(file);
try {
try {
byte[] buffer = new byte[4 * 1024]; // or other buffer size
int read;
while ((read = input.read(buffer)) != -1) {
output.write(buffer, 0, read);
}
output.flush();
} finally {
output.close();
}
} catch (Exception e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
showMessage("Download file successfully.");
return mDriveResourceClient.discardContents(contents);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
showMessage("Unable to download file.");
}
});
// [END read_contents]
}
private void requestPermission() {
String dirPath = getFilesDir().getAbsolutePath() + java.io.File.separator + "PDF";
storageDir = new java.io.File(dirPath);
if (!storageDir.exists())
storageDir.mkdirs();}}
//in gradle
implementation 'com.google.android.gms:play-services:11.8.0'
compile 'com.google.android.gms:play-services-auth:11.8.0'
compile 'com.google.api-client:google-api-client:1.23.0'
compile 'com.google.oauth-client:google-oauth-client-jetty:1.23.0'
compile 'com.google.apis:google-api-services-drive:v3-rev110-1.23.0'

Change screen after successful login? (Android studio)

I've been tasked during my internship to take over someone else's code and work on a project.I am having difficulties trying to navigate to another screen after a successful login.Currently, the code below redirects me back to the original main menu page after a successful login (While a failed login does nothing).
My question is how do I display a toast message saying wrong username/password?
Currently it displays nothing during a failed login.Also, how do I change screens from activity_login.xml to landing_page.xml after a SUCCESSFUL login? What code should I add?
LoginActivity.java :
package com.finchvpn.androidcloudpark;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.Objects;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class LoginActivity extends AppCompatActivity {
private EditText textUsername;
private EditText txtPassword;
private static RestClient restClient = new RestClient();
private SharedPreferences.Editor sharedPreferencesEditor;
#SuppressLint("CommitPrefEdits")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
try {
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
} catch (Exception e) {
}
textUsername = findViewById(R.id.textUsername);
txtPassword = findViewById(R.id.textPassword);
SharedPreferences sharedPreferences = getSharedPreferences("UserInfo", 0);
sharedPreferencesEditor = sharedPreferences.edit();
textUsername.setText(sharedPreferences.getString("textUsername", ""));
txtPassword.setText(sharedPreferences.getString("txtPassword", ""));
}
public static RestClient getRestClient() {
return restClient;
}
public void loginButtonClick(View v) {
if (!textUsername.getText().toString().equals("") && !txtPassword.getText().toString().equals("")) {
apiPostLogin(Constants.ANDROID_KEY + ":" + textUsername.getText().toString() + ":" + txtPassword.getText().toString());
sharedPreferencesEditor.putString("textUsername", textUsername.getText().toString());
sharedPreferencesEditor.putString("txtPassword", txtPassword.getText().toString());
sharedPreferencesEditor.commit();
} else {
Toast.makeText(LoginActivity.this, "NULL", Toast.LENGTH_LONG).show();
}
}
private void apiPostLogin(String data) {
final ProgressDialog progress = new ProgressDialog(this);
progress.setTitle("Logging in");
progress.setMessage("Please wait ...");
progress.setCancelable(false); // disable dismiss by tapping outside of the dialog
progress.show();
Call<ResponseBody> call = getRestClient().getLoginService().postLogin(data);
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful() && response.body() != null) {
try {
String data = response.body().string();
JSONObject jsonObject = new JSONObject(data);
Constants.uid = Integer.parseInt(jsonObject.getString("id"));
Constants.username = jsonObject.getString("username");
Constants.email = jsonObject.getString("email");
Constants.credit = jsonObject.getString("credit");
Constants.qr_code = jsonObject.getString("qr_code");
Constants.created_at = jsonObject.getString("created_at");
Constants.updated_at = jsonObject.getString("updated_at");
Toast.makeText(LoginActivity.this, "apiPostLogin onResponse <<<< \r\n\r\n" + jsonObject.toString(), Toast.LENGTH_LONG).show();
Intent returnIntent = new Intent();
setResult(Activity.RESULT_CANCELED, returnIntent);
finish();
} catch (IOException | JSONException e) {
e.printStackTrace();
}
}
progress.dismiss();
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(LoginActivity.this, "Incorrect username/password, please try again." + t.getMessage(), Toast.LENGTH_LONG).show();
progress.dismiss();
}
});
}
}
First of all, for changing your activity layout you have to change this line of code in the onCreate method:
setContentView(R.layout.activity_login);
Second, to display toast if the login fails, change your apiPostLogin method to:
private void apiPostLogin(String data) {
final ProgressDialog progress = new ProgressDialog(this);
progress.setTitle("Logging in");
progress.setMessage("Please wait ...");
progress.setCancelable(false); // disable dismiss by tapping outside of the dialog
progress.show();
Call<ResponseBody> call = getRestClient().getLoginService().postLogin(data);
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful() && response.body() != null) {
try {
String data = response.body().string();
JSONObject jsonObject = new JSONObject(data);
Constants.uid = Integer.parseInt(jsonObject.getString("id"));
Constants.username = jsonObject.getString("username");
Constants.email = jsonObject.getString("email");
Constants.credit = jsonObject.getString("credit");
Constants.qr_code = jsonObject.getString("qr_code");
Constants.created_at = jsonObject.getString("created_at");
Constants.updated_at = jsonObject.getString("updated_at");
Toast.makeText(LoginActivity.this, "apiPostLogin onResponse <<<< \r\n\r\n" + jsonObject.toString(), Toast.LENGTH_LONG).show();
Intent returnIntent = new Intent();
setResult(Activity.RESULT_CANCELED, returnIntent);
finish();
} catch (IOException | JSONException e) {
e.printStackTrace();
}
} else {
//
//
//This scope runs where the login fails
}
progress.dismiss();
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(LoginActivity.this, "Incorrect username/password, please try again." + t.getMessage(), Toast.LENGTH_LONG).show();
progress.dismiss();
}
});
}
If you are starting this loginactivity using startActivityForResult then handle the response from onActivityResult method in your calling activity.
And
setResult(Activity.RESULT_CANCELED, returnIntent);
this should be
setResult(Activity.RESULT_OK, returnIntent);

Upload image from android camera to web server

package com.camerafileupload;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
// LogCat tag
private static final String TAG = MainActivity.class.getSimpleName();
// Camera activity request codes
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
private static final int CAMERA_CAPTURE_VIDEO_REQUEST_CODE = 200;
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
private Uri fileUri; // file url to store image/video
private Button btnCapturePicture, btnRecordVideo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Changing action bar background color
// These two lines are not needed
getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor(getResources().getString(R.color.action_bar))));
btnCapturePicture = (Button) findViewById(R.id.btnCapturePicture);
btnRecordVideo = (Button) findViewById(R.id.btnRecordVideo);
/**
* Capture image button click event
*/
btnCapturePicture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// capture picture
captureImage();
}
});
/**
* Record video button click event
*/
btnRecordVideo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// record video
recordVideo();
}
});
// Checking camera availability
if (!isDeviceSupportCamera()) {
Toast.makeText(getApplicationContext(),
"Sorry! Your device doesn't support camera",
Toast.LENGTH_LONG).show();
// will close the app if the device does't have camera
finish();
}
}
/**
* Checking device has camera hardware or not
* */
private boolean isDeviceSupportCamera() {
if (getApplicationContext().getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA)) {
// this device has a camera
return true;
} else {
// no camera on this device
return false;
}
}
/**
* Launching camera app to capture image
*/
private void captureImage() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
/**
* Launching camera app to record video
*/
private void recordVideo() {
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);
// set video quality
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file
// name
// start the video capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_VIDEO_REQUEST_CODE);
}
/**
* Here we store the file url as it will be null after returning from camera
* app
*/
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// save file url in bundle as it will be null on screen orientation
// changes
outState.putParcelable("file_uri", fileUri);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// get the file url
fileUri = savedInstanceState.getParcelable("file_uri");
}
/**
* Receiving activity result method will be called after closing the camera
* */
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// if the result is capturing Image
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// successfully captured the image
// launching upload activity
launchUploadActivity(true);
} else if (resultCode == RESULT_CANCELED) {
// user cancelled Image capture
Toast.makeText(getApplicationContext(),
"User cancelled image capture", Toast.LENGTH_SHORT)
.show();
} else {
// failed to capture image
Toast.makeText(getApplicationContext(),
"Sorry! Failed to capture image", Toast.LENGTH_SHORT)
.show();
}
} else if (requestCode == CAMERA_CAPTURE_VIDEO_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// video successfully recorded
// launching upload activity
launchUploadActivity(false);
} else if (resultCode == RESULT_CANCELED) {
// user cancelled recording
Toast.makeText(getApplicationContext(),
"User cancelled video recording", Toast.LENGTH_SHORT)
.show();
} else {
// failed to record video
Toast.makeText(getApplicationContext(),
"Sorry! Failed to record video", Toast.LENGTH_SHORT)
.show();
}
}
}
private void launchUploadActivity(boolean isImage){
Intent i = new Intent(MainActivity.this, UploadActivity.class);
i.putExtra("filePath", fileUri.getPath());
i.putExtra("isImage", isImage);
startActivity(i);
}
/**
* ------------ Helper Methods ----------------------
* */
/**
* Creating file uri to store image/video
*/
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
/**
* returning image / video
*/
private static File getOutputMediaFile(int type) {
// External sdcard location
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
Config.IMAGE_DIRECTORY_NAME);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(TAG, "Oops! Failed create "
+ Config.IMAGE_DIRECTORY_NAME + " directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
} else if (type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "VID_" + timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
}
I get this code from android hive, I didn't know where the code to upload the image to server. I already build this code into .apk it working when taking photo and video to local storage but not to server.
and this is uploadactivity
package com.camerafileupload;
import com.camerafileupload.AndroidMultiPartEntity.ProgressListener;
import java.io.File;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;
public class UploadActivity extends Activity {
// LogCat tag
private static final String TAG = MainActivity.class.getSimpleName();
private ProgressBar progressBar;
private String filePath = null;
private TextView txtPercentage;
private ImageView imgPreview;
private VideoView vidPreview;
private Button btnUpload;
long totalSize = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload);
txtPercentage = (TextView) findViewById(R.id.txtPercentage);
btnUpload = (Button) findViewById(R.id.btnUpload);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
imgPreview = (ImageView) findViewById(R.id.imgPreview);
vidPreview = (VideoView) findViewById(R.id.videoPreview);
// Changing action bar background color
getActionBar().setBackgroundDrawable(
new ColorDrawable(Color.parseColor(getResources().getString(
R.color.action_bar))));
// Receiving the data from previous activity
Intent i = getIntent();
// image or video path that is captured in previous activity
filePath = i.getStringExtra("filePath");
// boolean flag to identify the media type, image or video
boolean isImage = i.getBooleanExtra("isImage", true);
if (filePath != null) {
// Displaying the image or video on the screen
previewMedia(isImage);
} else {
Toast.makeText(getApplicationContext(),
"Sorry, file path is missing!", Toast.LENGTH_LONG).show();
}
btnUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// uploading the file to server
new UploadFileToServer().execute();
}
});
}
/**
* Displaying captured image/video on the screen
* */
private void previewMedia(boolean isImage) {
// Checking whether captured media is image or video
if (isImage) {
imgPreview.setVisibility(View.VISIBLE);
vidPreview.setVisibility(View.GONE);
// bimatp factory
BitmapFactory.Options options = new BitmapFactory.Options();
// down sizing image as it throws OutOfMemory Exception for larger
// images
options.inSampleSize = 8;
final Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);
imgPreview.setImageBitmap(bitmap);
} else {
imgPreview.setVisibility(View.GONE);
vidPreview.setVisibility(View.VISIBLE);
vidPreview.setVideoPath(filePath);
// start playing
vidPreview.start();
}
}
/**
* Uploading the file to server
* */
private class UploadFileToServer extends AsyncTask<Void, Integer, String> {
#Override
protected void onPreExecute() {
// setting progress bar to zero
progressBar.setProgress(0);
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Integer... progress) {
// Making progress bar visible
progressBar.setVisibility(View.VISIBLE);
// updating progress bar value
progressBar.setProgress(progress[0]);
// updating percentage value
txtPercentage.setText(String.valueOf(progress[0]) + "%");
}
#Override
protected String doInBackground(Void... params) {
return uploadFile();
}
#SuppressWarnings("deprecation")
private String uploadFile() {
String responseString = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Config.FILE_UPLOAD_URL);
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new ProgressListener() {
#Override
public void transferred(long num) {
publishProgress((int) ((num / (float) totalSize) * 100));
}
});
File sourceFile = new File(filePath);
// Adding file data to http body
entity.addPart("image", new FileBody(sourceFile));
// Extra parameters if you want to pass to server
entity.addPart("website",
new StringBody("www.fintech-dev.com/cpeco"));
entity.addPart("email", new StringBody("i117dr4#gmail.com"));
totalSize = entity.getContentLength();
httppost.setEntity(entity);
// Making server call
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
// Server response
responseString = EntityUtils.toString(r_entity);
} else {
responseString = "Error occurred! Http Status Code: "
+ statusCode;
}
} catch (ClientProtocolException e) {
responseString = e.toString();
} catch (IOException e) {
responseString = e.toString();
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
Log.e(TAG, "Response from server: " + result);
// showing the server response in an alert dialog
showAlert(result);
super.onPostExecute(result);
}
}
/**
* Method to show alert dialog
* */
private void showAlert(String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(message).setTitle("Response from Servers")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// do nothing
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
and this is androidmultipartentity
package com.camerafileupload;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
#SuppressWarnings("deprecation")
public class AndroidMultiPartEntity extends MultipartEntity
{
private final ProgressListener listener;
public AndroidMultiPartEntity(final ProgressListener listener) {
super();
this.listener = listener;
}
public AndroidMultiPartEntity(final HttpMultipartMode mode,
final ProgressListener listener) {
super(mode);
this.listener = listener;
}
public AndroidMultiPartEntity(HttpMultipartMode mode, final String boundary,
final Charset charset, final ProgressListener listener) {
super(mode, boundary, charset);
this.listener = listener;
}
#Override
public void writeTo(final OutputStream outstream) throws IOException {
super.writeTo(new CountingOutputStream(outstream, this.listener));
}
public static interface ProgressListener {
void transferred(long num);
}
public static class CountingOutputStream extends FilterOutputStream {
private final ProgressListener listener;
private long transferred;
public CountingOutputStream(final OutputStream out,
final ProgressListener listener) {
super(out);
this.listener = listener;
this.transferred = 0;
}
public void write(byte[] b, int off, int len) throws IOException {
out.write(b, off, len);
this.transferred += len;
this.listener.transferred(this.transferred);
}
public void write(int b) throws IOException {
out.write(b);
this.transferred++;
this.listener.transferred(this.transferred);
}
}
}
This is config
package com.camerafileupload;
public class Config {
public static final String FILE_UPLOAD_URL = "url.com/android_upload/file_upload.php";
// Directory name to store captured images and videos
public static final String IMAGE_DIRECTORY_NAME = "android_upload";
DataHolder.FILE_UPLOAD_URL containing the url to upload.
onclick write
new UploadFileToServer().execute();
private class UploadFileToServer extends AsyncTask<Void, Integer, String> {
#Override
protected void onPreExecute() {
// setting progress bar to zero
pDialog.setProgress(0);
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Integer... progress) {
// Making progress bar visible
// updating progress bar value
pDialog.setProgress(progress[0]);
// updating percentage value
// txtPercentage.setText(String.valueOf(progress[0]) + "%");
}
#Override
protected String doInBackground(Void... params) {
return uploadFile();
}
#SuppressWarnings("deprecation")
private String uploadFile() {
String responseString = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(DataHolder.FILE_UPLOAD_URL);
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new ProgressListener() {
#Override
public void transferred(long num) {
publishProgress((int) ((num / (float) totalSize) * 100));
}
});
File sourceFile = new File(filePath);
// Adding file data to http body
entity.addPart("image", new FileBody(sourceFile));
// Extra parameters if you want to pass to server
entity.addPart("username", new StringBody("xyz"));
totalSize = entity.getContentLength();
httppost.setEntity(entity);
// Making server call
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
// Server response
responseString = EntityUtils.toString(r_entity);
} else {
responseString = "Error occurred! Http Status Code: "
+ statusCode;
}
} catch (ClientProtocolException e) {
responseString = e.toString();
} catch (IOException e) {
responseString = e.toString();
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
Log.e(TAG, "Response from server: " + result);
// showing the server response in an alert dialog
showAlert(result);
super.onPostExecute(result);
}
}
/**
* Method to show alert dialog
* */
private void showAlert(String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(message).setTitle("Response from Servers")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// do nothing
}
});
AlertDialog alert = builder.create();
alert.show();
}

how to get meetup access token on android, via oauth 2

my app needs to get user's meetup id. meetup uses oauth 2.0. found different pieces of code across the web, will paste in stackoverflow as answer to this question, for the next person.
import a library via graddle build file:
dependencies {
compile 'net.smartam.leeloo:oauth2-common:0.1'
compile 'net.smartam.leeloo:oauth2-client:0.1'
}
create a class for meetup authenticating. this class written by adrianmaurer (https://gist.github.com/adrianmaurer/4673944), thank you adrianmaurer!
MeetupAuthActivity:
package pixtas.com.nightout;
import android.content.ContentValues;
import android.content.Context;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
import android.view.Window;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
// leeloo oAuth lib https://bitbucket.org/smartproject/oauth-2.0/wiki/Home
import net.smartam.leeloo.client.OAuthClient;
import net.smartam.leeloo.client.URLConnectionClient;
import net.smartam.leeloo.client.request.OAuthClientRequest;
import net.smartam.leeloo.client.response.OAuthAccessTokenResponse;
import net.smartam.leeloo.client.response.OAuthAuthzResponse;
import net.smartam.leeloo.common.exception.OAuthProblemException;
import net.smartam.leeloo.common.exception.OAuthSystemException;
import net.smartam.leeloo.common.message.types.GrantType;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
/**
* Created by tmr_byronMac on 4/24/15.
*/
public class MeetupAuthActivity extends Activity {
private final String TAG = getClass().getName();
// Meetup OAuth Endpoints
public static final String AUTH_URL = "https://secure.meetup.com/oauth2/authorize";
public static final String TOKEN_URL = "https://secure.meetup.com/oauth2/access";
// Consumer
//public static final String REDIRECT_URI_SCHEME = "oauthresponse";
//public static final String REDIRECT_URI_HOST = "com.yourpackage.app";
//public static final String REDIRECT_URI_HOST_APP = "yourapp";
//public static final String REDIRECT_URI = REDIRECT_URI_SCHEME + "://" + REDIRECT_URI_HOST + "/";
public static final String REDIRECT_URI = "NightOut://meetup.com";
public static final String CONSUMER_KEY = "YOUR_KEY";
public static final String CONSUMER_SECRET = "YOUR_SECRET";
private WebView _webview;
private Intent _intent;
private Context _context;
public void onCreate(Bundle savedInstanceState) {
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
_intent = getIntent();
_context = getApplicationContext();
_webview = new WebView(this);
_webview.setWebViewClient(new MyWebViewClient());
setContentView(_webview);
_webview.getSettings().setJavaScriptEnabled(true);
OAuthClientRequest request = null;
try {
request = OAuthClientRequest.authorizationLocation(
AUTH_URL).setClientId(
CONSUMER_KEY).setRedirectURI(
REDIRECT_URI).buildQueryMessage();
} catch (OAuthSystemException e) {
Log.d(TAG, "OAuth request failed", e);
}
_webview.loadUrl(request.getLocationUri() + "&response_type=code&set_mobile=on");
}
public void finishActivity() {
//do something here before finishing if needed
finish();
}
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Uri uri = Uri.parse(url);
String code = uri.getQueryParameter("code");
String error = uri.getQueryParameter("error");
if (code != null) {
new MeetupRetrieveAccessTokenTask().execute(uri);
// setResult(RESULT_OK, _intent);
// finishActivity();
} else if (error != null) {
setResult(RESULT_CANCELED, _intent);
finishActivity();
}
return false;
}
}
private class MeetupRetrieveAccessTokenTask extends AsyncTask<Uri, Void, Void> {
#Override
protected Void doInBackground(Uri... params) {
Uri uri = params[0];
String code = uri.getQueryParameter("code");
OAuthClientRequest request = null;
try {
request = OAuthClientRequest.tokenLocation(TOKEN_URL)
.setGrantType(GrantType.AUTHORIZATION_CODE).setClientId(
CONSUMER_KEY).setClientSecret(
CONSUMER_SECRET).setRedirectURI(
REDIRECT_URI).setCode(code)
.buildBodyMessage();
OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());
OAuthAccessTokenResponse response = oAuthClient.accessToken(request);
// do something with these like add them to _intent
// Intent returnIntent = new Intent();
// returnIntent.putExtra("access_token", response.getAccessToken());
// setResult(RESULT_OK,returnIntent);
Log.d(TAG, "access token: " + response.getAccessToken());
Log.d(TAG, response.getExpiresIn());
Log.d(TAG, response.getRefreshToken());
_intent.putExtra("access_token", response.getAccessToken());
setResult(RESULT_OK, _intent);
finish();
} catch (OAuthSystemException e) {
Log.e(TAG, "OAuth System Exception - Couldn't get access token: " + e.toString());
Toast.makeText(_context, "OAuth System Exception - Couldn't get access token: " + e.toString(), Toast.LENGTH_LONG).show();
} catch (OAuthProblemException e) {
Log.e(TAG, "OAuth Problem Exception - Couldn't get access token");
Toast.makeText(_context, "OAuth Problem Exception - Couldn't get access token", Toast.LENGTH_LONG).show();
}
return null;
}
}
#Override
public void onBackPressed()
{
setResult(RESULT_CANCELED, _intent);
finishActivity();
}
}
call MeetupAuthActivity from your main activity.
MainActivity:
public void getMeetupAccessToken(){
Intent intent;
intent = new Intent(this, MeetupAuthActivity.class);
// startActivity(intent);
startActivityForResult(intent,GET_MEETUP_ACCESS_TOKEN_ACTIVITY);
}
in MainActivity, capture the results form auth activity.
MainActivity:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
// if(requestCode == 1 && resultCode == RESULT_OK)
if(requestCode == GET_MEETUP_ACCESS_TOKEN_ACTIVITY)
{
accessToken = data.getExtras().getString("access_token");
saveMeetupAccessTokenToSharedPreferences();
//save meetupid plus device id to parse
getMyMeetupIdFromMeetupServer();
// Log.i(DEBUG_TAG,"MainActivity, accessToken" + accessToken);
}
}

Categories