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

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);
}
}

Related

Android Upload Images(Okhttp3) without interface

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";
}
?>

Using GCM to send push notification from one activity to another - Android Studio

I am currently programming an android application in Android Studio. I am trying to implement a push notification service with GCM. The push notification will be sent from one user account to another user account, the second user will accept and then the two accounts will be linked. I have the two accounts set up on a mySQL server using 000webhost.com. I tried to followed this tutorial , link, to implement GCM but I can't figure out how I send and receive the notification.
This is where I get the registration ID:
package com.jack.pointcollector;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.AsyncTask;
import android.util.Log;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.google.android.gms.iid.InstanceID;
import java.io.IOException;
public class GCMClientManager {
// Constants
public static final String TAG = "GCMClientManager";
public static final String PROPERTY_REG_ID = "registration_id";
private static final String PROPERTY_APP_VERSION = "appVersion";
private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
// Member variables
private GoogleCloudMessaging gcm;
private String regID;
private String projectNumber;
private Activity activity;
public GCMClientManager(Activity activity, String projectNumber) {
this.activity = activity;
this.projectNumber = projectNumber;
this.gcm = GoogleCloudMessaging.getInstance(activity);
}
/**
* #return Application's version code from the {#code PackageManager}.
*/
private static int getAppVersion(Context context) {
try {
PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
return packageInfo.versionCode;
} catch (NameNotFoundException e) {
// should never happen
throw new RuntimeException("Could not get package name: " + e);
}
}
// Register if needed or fetch from local store
public void registerIfNeeded(final RegistrationCompletedHandler handler) {
if (checkPlayServices()) {
regID = getRegistrationId(getContext());
if (regID.isEmpty()) {
registerInBackground(handler);
} else { // got id from cache
Log.i(TAG, regID);
handler.onSuccess(regID, false);
}
} else { // no play services
Log.i(TAG, "No valid Google Play Services APK found.");
}
}
/**
* Registers the application with GCM servers asynchronously.
* <p>
* Stores the registration ID and app versionCode in the application's
* shared preferences.
*/
private void registerInBackground(final RegistrationCompletedHandler handler) {
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(getContext());
}
InstanceID instanceID = InstanceID.getInstance(getContext());
regID = instanceID.getToken(projectNumber, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
Log.i(TAG, regID);
// Persist the regID - no need to register again.
storeRegistrationId(getContext(), regID);
} catch (IOException ex) {
// If there is an error, don't just keep trying to register.
// Require the user to click a button again, or perform
// exponential back-off.
handler.onFailure("Error :" + ex.getMessage());
}
return regID;
}
#Override
protected void onPostExecute(String regId) {
if (regId != null) {
handler.onSuccess(regId, true);
}
}
}.execute(null, null, null);
}
/**
* Gets the current registration ID for application on GCM service.
* <p>
* If result is empty, the app needs to register.
*
* #return registration ID, or empty string if there is no existing
* registration ID.
*/
private String getRegistrationId(Context context) {
final SharedPreferences prefs = getGCMPreferences(context);
String registrationId = prefs.getString(PROPERTY_REG_ID, "");
if (registrationId.isEmpty()) {
Log.i(TAG, "Registration not found.");
return "";
}
// Check if app was updated; if so, it must clear the registration ID
// since the existing regID is not guaranteed to work with the new
// app version.
int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
int currentVersion = getAppVersion(context);
if (registeredVersion != currentVersion) {
Log.i(TAG, "App version changed.");
return "";
}
return registrationId;
}
/**
* Stores the registration ID and app versionCode in the application's
* {#code SharedPreferences}.
*
* #param context application's context.
* #param regId registration ID
*/
private void storeRegistrationId(Context context, String regId) {
final SharedPreferences prefs = getGCMPreferences(context);
int appVersion = getAppVersion(context);
Log.i(TAG, "Saving regId on app version " + appVersion);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(PROPERTY_REG_ID, regId);
editor.putInt(PROPERTY_APP_VERSION, appVersion);
editor.apply();
}
private SharedPreferences getGCMPreferences(Context context) {
// This sample app persists the registration ID in shared preferences, but
// how you store the regID in your app is up to you.
return getContext().getSharedPreferences(context.getPackageName(), Context.MODE_PRIVATE);
}
/**
* Check the device to make sure it has the Google Play Services APK. If
* it doesn't, display a dialog that allows users to download the APK from
* the Google Play Store or enable it in the device's system settings.
*/
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getContext());
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, getActivity(),
PLAY_SERVICES_RESOLUTION_REQUEST).show();
} else {
Log.i(TAG, "This device is not supported.");
}
return false;
}
return true;
}
private Context getContext() {
return activity;
}
private Activity getActivity() {
return activity;
}
public static abstract class RegistrationCompletedHandler {
public abstract void onSuccess(String registrationId, boolean isNewRegistration);
public void onFailure(String ex) {
// If there is an error, don't just keep trying to register.
// Require the user to click a button again, or perform
// exponential back-off.
Log.e(TAG, ex);
}
}
}
This is my GCMListnerService class:
package com.jack.pointcollector;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import com.google.android.gms.gcm.GcmListenerService;
public class PushNotificationManager extends GcmListenerService{
#Override
public void onMessageReceived(String from, Bundle data) {
childNotification(from);
super.onMessageReceived(from, data);
}
private AlertDialog childNotification(String name) {
AlertDialog.Builder response = new AlertDialog.Builder(this.getBaseContext());
response.setMessage(name + " has added you as their child. Is this correct?");
response.setTitle("Point Collector");
response.setPositiveButton("Correct", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
response.setNegativeButton("I don't know them", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
response.setCancelable(false);
return response.create();
}
}
and finally the class the I want to send the notification from
package com.jack.pointcollector;
import android.app.Activity;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
public class Add_Child extends Activity implements View.OnClickListener {
Button bAddChild;
EditText etUsername, etEmail;
String PROJECT_NUMBER = "76770391940";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add__child);
bAddChild = (Button) findViewById(R.id.addButton);
etUsername = (EditText) findViewById(R.id.name);
etEmail = (EditText) findViewById(R.id.child_email);
bAddChild.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.addButton:
GCMClientManager pushClientManager = new GCMClientManager(this, PROJECT_NUMBER);
pushClientManager.registerIfNeeded(new GCMClientManager.RegistrationCompletedHandler() {
#Override
public void onSuccess(String registrationId, boolean isNewRegistration) {
Log.d("Registration id", registrationId);
//send this registrationId to your server
toServer(registrationId);
}
#Override
public void onFailure(String ex) {
super.onFailure(ex);
}
});
break;
}
}
private void toServer(final String id) {
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
try {
URL url = new URL("http://point_collector.netau.net/");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
Uri.Builder builder = new Uri.Builder().appendQueryParameter("id", id);
String query = builder.build().getEncodedQuery();
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
//Gets the response code to ensure this was succesful.
int code = conn.getResponseCode();
Log.d("code", Integer.toString(code));
conn.connect();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
};
}
}
I have looked and loads of video tutorials as well as online tutorials and can't figure it out at all. If anybody can help me out I would greatly appreciate it.
Thanks
edit - Still really stuck on this if anybody at all could offer some insight!

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();
}

Android Volley Crashing

I'm using Android Volley to login a user in but when addToRequestQueue is called the following crash report is shown.
The login request is carried out onclick in the Loginactivity as follows:
// Login button Click Event
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String username = inputUserName.getText().toString();
String pin = inputPIN.getText().toString();
// Check for empty data in the form
if (username.trim().length() > 0 && pin.trim().length() > 0) {
// login user
SharedPreferences prefs = getGCMPreferences(context);
String storeRegId = prefs.getString(PROPERTY_REG_ID, "");
String devid = Secure.getString(getBaseContext().getContentResolver(),Secure.ANDROID_ID);
String vars = "/?tag=login&username=" + username + "&pin=" + pin + "&regid=" + storeRegId + "&devid=" + devid;
WebRequest wr = new WebRequest(context);
wr.Request(AppConfig.URL_LOGIN, vars, true, "Please Wait", "Logging in...", "req_login");
} else {
// Prompt user to enter credentials
Toast.makeText(getApplicationContext(), "Please enter the credentials!", Toast.LENGTH_LONG).show();
}
}
});
WebRequest, which uses volley looks like this:
package app;
import helper.SQLiteHandler;
import helper.SessionManager;
import helper.dbTables;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import main.MainActivity;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.WindowManager;
import android.widget.Toast;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.Request.Method;
import com.android.volley.toolbox.StringRequest;
import com.google.android.gms.gcm.GoogleCloudMessaging;
public class WebRequest extends Activity {
private static final String TAG = "LoginActivity";
AtomicInteger msgId = new AtomicInteger();
GoogleCloudMessaging gcm;
SharedPreferences prefs;
public SQLiteHandler db;
SessionManager session;
protected Context context;
public WebRequest(Context context){
this.context = context.getApplicationContext();
}
public void Request(final String url, final String vars, final Boolean show, final String title, final String msg, final String requestName){
final SessionManager session = new SessionManager(context);
final ProgressDialog theProgressDialog = new ProgressDialog(context);
db = new SQLiteHandler(context);
if(show == true){
theProgressDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
theProgressDialog.setTitle(title);
theProgressDialog.setMessage(msg);
theProgressDialog.setIndeterminate(true);
theProgressDialog.setCancelable(false);
theProgressDialog.show();
}
StringRequest strreq = new StringRequest(Method.GET, url + vars,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "WEB Response: " + response.toString());
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
// Check for error node in json
if (!error) {
switch(requestName){
case "req_login":
//process user login
// Fetching user details from sqlite
HashMap<String, String> user = db.fetchResults(dbTables.TABLE_LOGIN, null);
String storedUid = user.get("uid");
JSONObject login = jObj.getJSONObject("login");
if(storedUid != login.getString("uid")){
//new user for device
String[] emptyTables = {dbTables.TABLE_LOGIN};
for(int i=0; i<emptyTables.length; i++){
db.emptyTable(emptyTables[i]);
Log.d(TAG, "empty table : " + emptyTables[i]);
}
}
//store user in database
db.addUser(login.getString("uid"),
login.getString("companyid"),
login.getString("resourceid"),
login.getString("groupid"),
login.getString("title"),
login.getString("firstname"),
login.getString("middleinitial"),
login.getString("lastname"),
login.getString("jobtitle"),
login.getString("managerid"),
login.getString("email"),
login.getString("photo_url"),
login.getString("signature_url"),
login.getString("language"),
login.getString("skin"),
login.getString("defaultprojectid"),
login.getString("cnNotifications"),
login.getString("crNotifications"),
login.getString("coNotifications"),
login.getString("addedby"),
login.getString("dateadded"),
login.getString("editedby"),
login.getString("dateedited"));
// Create login session
session.setLogin(true);
// Launch main activity
Intent intent = new Intent(context, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
//finish();
break;
}
if(show == true){
theProgressDialog.dismiss();
}
}else{
String errorMsg = jObj.getString("error_msg");
Toast.makeText(context, errorMsg, Toast.LENGTH_LONG).show();
if(show == true){
theProgressDialog.dismiss();
}
}
}catch(JSONException e){
// JSON error
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Web Error: " + error.getMessage());
Toast.makeText(context, error.getMessage(), Toast.LENGTH_LONG).show();
if(show == true){
theProgressDialog.dismiss();
}
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strreq, requestName);
}
}
I've also included the AppController which I haven't personally changed
package app;
import android.app.Application;
import android.text.TextUtils;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
public class AppController extends Application {
public static final String TAG = AppController.class.getSimpleName();
private RequestQueue mRequestQueue;
private static AppController mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized AppController getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
This is no way to create a Activity object. A lot get go wrong
like this.
Activity is a context therefore he doesnt need to hold a context
as a member. That is a common memory leak.
The activity doesnt go trough the proper life cycle and that is why
everything blows up.
I would suggest to you to start from the basic because when you will do this everything will be clearer.
The AppController isn't neccessary in creating a request using volley......Just add the request in volley android volley request.....https://www.simplifiedcoding.net/android-volley-post-request-tutorial/.......
The way you sends the request will determine if the app crashes.....one, the Sqlite will make the application crashes if the request is sent properly...

Google Cloud messaging service returning empty registration id

I'm running into an issue implementing Google Cloud Messaging. When i try to register my emulator i'm suppost to get the Registration ID of the device, which in this case is my emulator. So when i looked around i saw i needed to link a google account so i did that but i still have the same issue. it returns that it is a new registration but the registration id is empty. could someone help me in the right direction? If you need to know anything else let me know. Thanks in advance
Code:
LoginActivity.java
package com.vict.voffice;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.vict.voffice.utilities.Dialogs;
import com.vict.voffice.utilities.GCMClientManager;
import com.vict.voffice.utilities.UserDetailCache;
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.impl.client.DefaultHttpClient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class LoginActivity extends Activity {
EditText mNaam;
EditText mVersie;
EditText mWachtwoord;
String PROJECT_NUMBER = "##########";
private GCMClientManager pushClientManager;
private Context cont = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
cont = this;
pushClientManager = new GCMClientManager(this, PROJECT_NUMBER);
mNaam = (EditText)findViewById(R.id.editText_login);
mVersie = (EditText)findViewById(R.id.editText_bedrijf);
mWachtwoord = (EditText)findViewById(R.id.editText_wachtwoord);
final Button button = (Button) findViewById(R.id.btnLogin);
button.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
pushClientManager.registerIfNeeded(new GCMClientManager.RegistrationCompletedHandler() {
#Override
public void onSuccess(String registrationId, boolean isNewRegistration) {
//Dialogs.LoginDialog(cont).show();
Toast.makeText(getApplicationContext(), "Regid: "+registrationId+" "+isNewRegistration, Toast.LENGTH_SHORT).show();
//Login(mNaam.getText().toString(), mWachtwoord.getText().toString(), mVersie.getText().toString(), pushClientManager.getRegistrationId(cont));
}
#Override
public void onFailure(String ex) {}});
Log.d("DBG", "Login Pressed");
}
});
Log.d("DBG", ""+UserDetailCache.GetNodeFromFile(cont));
if(UserDetailCache.GetNodeFromFile(cont) != null || UserDetailCache.GetNodeFromFile(cont) != "" || UserDetailCache.GetNodeFromFile(cont) != "null" || UserDetailCache.GetNodeFromFile(cont).isEmpty()){
if(UserDetailCache.GetUserNameFromFile(cont) != null || UserDetailCache.GetUserNameFromFile(cont) != "" || UserDetailCache.GetUserNameFromFile(cont) != "null"){
if(UserDetailCache.GetPasswordFromFile(cont) != null || UserDetailCache.GetPasswordFromFile(cont) != "" || UserDetailCache.GetPasswordFromFile(cont) != "null"){
Log.d("DBG", "Filling Fields from DB");
mNaam.setText(UserDetailCache.GetUserNameFromFile(getApplicationContext()));
mWachtwoord.setText(UserDetailCache.GetPasswordFromFile(getApplicationContext()));
mVersie.setText(UserDetailCache.GetNodeFromFile(getApplicationContext()));
button.performClick();
}else{
Log.d("DBG", "No Password");
}
}else{
Log.d("DBG", "No Username");
}
}else{
Log.d("DBG", "No Node");
}
}
#Override
public void onBackPressed(){
Intent intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
super.onBackPressed();
System.exit(0);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
public void Login(String Username, String Password, String Node, String Token){
class LoginAsyncTask extends AsyncTask<String, Void, String>{
UserDetailCache Dtc = new UserDetailCache();
String uniqueKey = "";
#Override
protected void onPreExecute(){
super.onPreExecute();
//Dialogs.LoginDialog(getApplicationContext()).show();
}
#Override
protected String doInBackground(String... params) {
String paramUsername = params[0];
String paramPassword = params[1];
String paramVersion = params[2];
uniqueKey = params[3];
Log.d("LoginActivity", "Token: " + uniqueKey);
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://node11.voffice.nl/login/appcheck.asp?login=" + paramUsername + "&wachtw=" + paramPassword + "&versie=" + paramVersion + "&token=" + uniqueKey);
//Log.e("HTTP", "send link: " + httpPost.getURI());
try{
HttpResponse httpResponse = httpClient.execute(httpPost);
InputStream inputStream = httpResponse.getEntity().getContent();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
while((bufferedStrChunk = bufferedReader.readLine()) != null){
stringBuilder.append(bufferedStrChunk);
}
return stringBuilder.toString();
}catch (ClientProtocolException cpe){
// Log.e("HTTP", "First Exception, httpResponse : " + cpe);
cpe.printStackTrace();
}catch (IOException ioe){
// Log.e("HTTP", "Second Exception, httpResonse : " + ioe);
ioe.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result){
super.onPostExecute(result);
Log.e("HTTP", "Server Responded with : " + result);
String splitResult[] = result.split("\\|");
if(splitResult[0].equals("OK") && splitResult != null){
String tempCompany = splitResult[1].substring(8);
User usr = new User(splitResult[1], tempCompany, splitResult[2], uniqueKey, splitResult[4], splitResult[3]);
Dialogs.LoginDialog(getApplicationContext()).hide();
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivityForResult(intent, 0);
}else{
Dialogs.TextDialog(getApplicationContext(), "Verkeerde Logingegeven", Toast.LENGTH_LONG);
Dialogs.LoginDialog(getApplicationContext()).hide();
}
Dialogs.TextDialog(getApplicationContext(), "", Toast.LENGTH_LONG);
Dialogs.LoginDialog(getApplicationContext()).hide();
}
}
LoginAsyncTask Logintask = new LoginAsyncTask();
Logintask.execute(Username, Password, Node, Token);
}
}
GCMClientManager.java
package com.vict.voffice.utilities;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.util.Log;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import java.io.IOException;
/**
* Created by Kevin on 3/3/2015.
*/
public class GCMClientManager {
// Constants
public static final String TAG = "GCMClientManager";
public static final String PROPERTY_REG_ID = "registration_id";
private static final String PROPERTY_APP_VERSION = "6";
private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
// Member variables
private GoogleCloudMessaging gcm;
private String regid;
private String projectNumber;
private Activity activity;
public static abstract class RegistrationCompletedHandler {
public abstract void onSuccess(String registrationId, boolean isNewRegistration);
public void onFailure(String ex) {
// If there is an error, don't just keep trying to register.
// Require the user to click a button again, or perform
// exponential back-off.
Log.e(TAG, ex);
}
}
public GCMClientManager(Activity activity, String projectNumber) {
this.activity = activity;
this.projectNumber = projectNumber;
this.gcm = GoogleCloudMessaging.getInstance(activity);
}
// Register if needed or fetch from local store
public void registerIfNeeded(final RegistrationCompletedHandler handler) {
if (checkPlayServices()) {
regid = getRegistrationId(getContext());
if (regid.isEmpty()) {
registerInBackground(handler);
} else { // got id from cache
Log.i(TAG, regid);
handler.onSuccess(regid, false);
}
} else { // no play services
Log.i(TAG, "No valid Google Play Services APK found.");
}
}
/**
* Registers the application with GCM servers asynchronously.
* <p>
* Stores the registration ID and app versionCode in the application's
* shared preferences.
*/
private void registerInBackground(final RegistrationCompletedHandler handler) {
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(getContext());
}
regid = gcm.register(projectNumber);
Log.i(TAG, regid);
// Persist the regID - no need to register again.
storeRegistrationId(getContext(), regid);
} catch (IOException ex) {
// If there is an error, don't just keep trying to register.
// Require the user to click a button again, or perform
// exponential back-off.
handler.onFailure("Error :" + ex.getMessage());
}
return regid;
}
#Override
protected void onPostExecute(String regId) {
if (regId != null) {
handler.onSuccess(regId, true);
}
}
}.execute(null, null, null);
}
/**
* Gets the current registration ID for application on GCM service.
* <p>
* If result is empty, the app needs to register.
*
* #return registration ID, or empty string if there is no existing
* registration ID.
*/
public String getRegistrationId(Context context) {
final SharedPreferences prefs = getGCMPreferences(context);
String registrationId = prefs.getString(PROPERTY_REG_ID, "");
if (registrationId.isEmpty()) {
Log.i(TAG, "Registration not found.");
return "";
}
// Check if app was updated; if so, it must clear the registration ID
// since the existing regID is not guaranteed to work with the new
// app version.
int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
int currentVersion = getAppVersion(context);
if (registeredVersion != currentVersion) {
Log.i(TAG, "App version changed.");
return "";
}
return registrationId;
}
/**
* Stores the registration ID and app versionCode in the application's
* {#code SharedPreferences}.
*
* #param context application's context.
* #param regId registration ID
*/
private void storeRegistrationId(Context context, String regId) {
final SharedPreferences prefs = getGCMPreferences(context);
int appVersion = getAppVersion(context);
Log.i(TAG, "Saving regId on app version " + appVersion);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(PROPERTY_REG_ID, regId);
editor.putInt(PROPERTY_APP_VERSION, appVersion);
editor.commit();
}
/**
* #return Application's version code from the {#code PackageManager}.
*/
private static int getAppVersion(Context context) {
try {
PackageInfo packageInfo = context.getPackageManager()
.getPackageInfo(context.getPackageName(), 0);
return packageInfo.versionCode;
} catch (PackageManager.NameNotFoundException e) {
// should never happen
throw new RuntimeException("Could not get package name: " + e);
}
}
private SharedPreferences getGCMPreferences(Context context) {
// This sample app persists the registration ID in shared preferences, but
// how you store the regID in your app is up to you.
return getContext().getSharedPreferences(context.getPackageName(),
Context.MODE_PRIVATE);
}
/**
* Check the device to make sure it has the Google Play Services APK. If
* it doesn't, display a dialog that allows users to download the APK from
* the Google Play Store or enable it in the device's system settings.
*/
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getContext());
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, getActivity(),
PLAY_SERVICES_RESOLUTION_REQUEST).show();
} else {
Log.i(TAG, "This device is not supported.");
}
return false;
}
return true;
}
private Context getContext() {
return activity;
}
private Activity getActivity() {
return activity;
}
}
Try to set your emulator target to Google API and add a google
account.(add account on emulator: setting->account&sync)

Categories