How to write unit tests for firebase notification? - android

I have made the following class to receive firebase messages and create notifications. I have tested it by sending firebase messages to the app and it works perfectly. However, I need to write unit tests to test this feature. But the 2 unit tests I have written for it are failing.
onMessageReceived() receives data in a RemoteMessage object. It then finds the value of the key type and depending on whether it is 0 or 1, it calls either buildNotificationBigText() or buildNotificationBigPicture() . Hence I have written 2 test methods. In my test methods I have created a RemoteMessage object and passed this to onMessageReceived(). However, these tests are not working correctly and I get the following error:
java.lang.NullPointerException: Attempt to invoke virtual method 'void in.ac.bits_pilani.goa.ard.services.HandleFirebaseMessages.onMessageReceived(com.google.firebase.messaging.RemoteMessage)' on a null object reference
at in.ac.bits_pilani.goa.ard.activities.MainActivityTest.handleFirebaseMessageBigPicture(MainActivityTest.java:90)
java.lang.NullPointerException: Attempt to invoke virtual method 'void in.ac.bits_pilani.goa.ard.services.HandleFirebaseMessages.onMessageReceived(com.google.firebase.messaging.RemoteMessage)' on a null object reference
at in.ac.bits_pilani.goa.ard.activities.MainActivityTest.handleFirebaseMessagesBigText(MainActivityTest.java:80)
HandleFirebaseMessages.java
public class HandleFirebaseMessages extends FirebaseMessagingService {
/**
* default id for notification in case specific id is not given in data.
*/
final int default_id = 42;
NotificationCompat.Builder builder ;
/**
* contains bigTitle value of data in onMessageReceived().
*/
String bigTitle;
/**
* is assigned the bigSummaryText value of data in onMessageReceived().
*/
String bigSummaryText;
public HandleFirebaseMessages() {
}
/**
* returns the bitmap image from the url given.
* #param src image url
* #return bitmap image at url
*/
public static Bitmap getBitmapFromURL(final String src) {
try {
final URL url = new URL(src);
final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
final InputStream input = connection.getInputStream();
return BitmapFactory.decodeStream(input);
} catch (final IOException e) {
// Log exception
Log.e("TAG", "fucked man " + e.getMessage());
return null;
}
}
/**
* creates the notification when type is 1 or big text.
* #param data data to be put in notification
*/
public void buildNotificationBigText(final Map<String, String> data) {
Log.e("Tag4", "entered buildNotificationBigText");
//final String bigTitle = data.get("bigTitle");
final String bigSubTitle = data.get("bigSubTitle");
//final String bigSummaryText = data.get("bigSummaryText");
final NotificationCompat.BigTextStyle notificationBigText = new NotificationCompat.BigTextStyle();
if (bigTitle != null) {
notificationBigText.setBigContentTitle(bigTitle);
}
if (bigSubTitle != null) {
notificationBigText.bigText(bigSubTitle);
}
if (bigSummaryText != null) {
notificationBigText.setSummaryText(bigSummaryText);
}
builder.setStyle(notificationBigText);
}
/**
* creates the notification when type is 2 or big picture.
* #param data data to be put in notification
*/
public void buildNotificationBigPicture(final Map<String, String> data) {
Log.e("Tag3", "entered buildNotificationBigPicture");
final String imageUrl = data.get("imageUrl");
//final String bigSummaryText = data.get("bigSummaryText");
//final String bigTitle = data.get("bigTitle");
final NotificationCompat.BigPictureStyle notificationBigPicture = new NotificationCompat.BigPictureStyle();
if (imageUrl != null) {
final Bitmap image = getBitmapFromURL(imageUrl);
if (image != null) {
notificationBigPicture.bigPicture(image);
} else {
//TODO Image is null bt url wasn;t!
}
}
if (bigSummaryText != null) {
notificationBigPicture.setSummaryText(bigSummaryText);
}
if (bigTitle != null) {
notificationBigPicture.setBigContentTitle(bigTitle);
}
//TODO icon
builder.setStyle(notificationBigPicture);
}
#Override
public void onMessageReceived(final RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
Log.e("Tag1", "onMessageReceived() started");
final Map<String, String> data = remoteMessage.getData();
if (data == null) {
return;
}
bigTitle = data.get("bigTitle");
bigSummaryText = data.get("bigSummaryText");
final String type = data.get("type");
final String id = data.get("id");
final String smallTitle = data.get("smallTitle");
final String smallSubTitle = data.get("smallSubTitle");
//final String contentInfo = data.get("contentInfo");
//final String ticker = data.get("ticker");
final String link = data.get("link");
final String className = data.get("className");
Log.e("Tag2", "type = " + type);
builder = new NotificationCompat.Builder(this);
if (type != null) {
if (type.compareTo("1") == 0) {
//Large Text Style corresponds to "1"
buildNotificationBigText(data);
} else if (type.compareTo("2") == 0) {
//BigPicture style specific
buildNotificationBigPicture(data);
}
}
//General things to be added for any kind of notification
if (smallTitle != null) {
builder.setContentTitle(smallTitle);
}
if (smallSubTitle != null) {
builder.setContentText(smallSubTitle);
}
int notificationId = default_id;
if (id != null) {
notificationId = Integer.parseInt(id);
}
builder.setContentIntent(addWebsiteLinkPendingIntent(notificationId, link, className));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
builder.setCategory(Notification.CATEGORY_SOCIAL);
}
builder.setSmallIcon(R.drawable.ic_stat);
builder.setColor(ContextCompat.getColor(this, R.color.colorPrimary));
builder.setAutoCancel(true);
final NotificationManagerCompat mNotificationManager = NotificationManagerCompat.from(this);
mNotificationManager.notify(notificationId, builder.build());
}
/**
* returns the intent for the webpage or activity to open from the notification.
* #param id notification id
* #param link webpage link
* #param className class for the activity to open
* #return PendingIntent for the webpage ot activity
*/
private PendingIntent addWebsiteLinkPendingIntent(final int id, final String link, final String className) {
Intent intent;
if (link != null) {
//TODO Change to ChromeCustomTabs later
intent = new Intent(Intent.ACTION_VIEW, Uri.parse(link));
} else if (className != null) {
try {
intent = new Intent(this, Class.forName("com.csatimes.dojma." + className));
//TODO check for page number
} catch (final ClassNotFoundException e) {
intent = new Intent(this, MainActivity.class);
}
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
} else {
intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION);
}
return PendingIntent.getActivity(
this,
id,
intent,
PendingIntent.FLAG_CANCEL_CURRENT);
}
}
MainActivityTests.java :
#RunWith(AndroidJUnit4.class)
public class MainActivityTest {
private Context context;
#Mock
private HandleFirebaseMessages handleFirebaseMessages;
#Rule
public ActivityTestRule<MainActivity> activityTestRule =
new ActivityTestRule<>(MainActivity.class);
#Before
public void init() {
context = InstrumentationRegistry.getTargetContext();
//MockitoAnnotations.initMocks(this);
//handleFirebaseMessages = new HandleFirebaseMessages();
}
#Test
public void handleFirebaseMessagesBigText() {
HandleFirebaseMessages handleFirebaseMessages=new HandleFirebaseMessages();
RemoteMessage remoteMessage = new RemoteMessage.Builder("token").addData("type","1").build();
handleFirebaseMessages.onMessageReceived(remoteMessage);
Map<String,String> data = new HashMap<>() ;
data.put("type","1");
Mockito.verify(handleFirebaseMessages).buildNotificationBigText(data);
}
#Test
public void handleFirebaseMessagesBigPicture() {
HandleFirebaseMessages handleFirebaseMessages=new HandleFirebaseMessages();
RemoteMessage remoteMessage = new RemoteMessage.Builder("token").addData("type","2").build();
handleFirebaseMessages.onMessageReceived(remoteMessage);
Map<String,String> data = new HashMap<>() ;
data.put("type","2");
Mockito.verify(handleFirebaseMessages).buildNotificationBigPicture(data);
}
}

While testing it is advised to limit dependencies that you are testing. You could refactor your code in a way that it would not depend on FirebaseMessagingService.
For example instead of having your logic in onMessageReceived(), you could extract it to separate method preferably in other class (along with other methods from HandleFirebaseMessages) that would not depend on FirebaseMessagingService. It could even be structured so that it relies on plain java code, so that no instrumentation is required to run the test.
This way you would only be testing your code and not other dependencies, which would make it easier to test.

Related

Android intent data return null

I am starter at Android and now I want to transfer data using intent from one activity to another.
First activity will collect datas and give it to second. but on second the data returns null. So have some errors on there. Here are my code.
public void previewStack(final Context context, final CreateStackNewActivity createStackNewActivity, final Stack stackDetails) {
Map<String, String> options = new HashMap<String, String>();
if(stackDetails.getStackId() != -1){
options.put("stack_id", String.valueOf(stackDetails.getStackId()));
}
int index = 1;
for(StackLineNew stackLine : stackDetails.getLines()){
options.put("title" + index, stackLine.getTitle());
options.put("line_type" + index, Integer.toString(stackLine.getLineType().intValue));
options.put("title" + index, stackLine.getTitle());
if (stackLine.getBody().indexOf("file:/") == -1 && stackLine.getBody().indexOf("content:") == -1) {
options.put("description" + index, stackLine.getBody());
if (stackLine.getLineId() != -1) {
options.put("line_id" + index, Integer.toString(stackLine.getLineId()));
}
}
index++;
}
Call<GenericAPIResponse> call = Hype4DAPI.previewStack(stackDetails.getName(), stackDetails.getCategory(), Integer.toString(stackDetails.getLines().size()), options, "");
call.enqueue(new Callback<GenericAPIResponse>() {
#Override
public void onResponse(Call<GenericAPIResponse> call, Response<GenericAPIResponse> response) {
if(response.isSuccessful()) {
GenericAPIResponse saveStackResponse = response.body();
System.out.println(saveStackResponse);
Toast.makeText(context, saveStackResponse.toString(), Toast.LENGTH_SHORT).show();
createStackNewActivity.saveInProgress = false;
createStackNewActivity.somethingHasChanged = false;
createStackNewActivity.updatePostButtonState();
Intent itnt = new Intent(createStackNewActivity, StackDetailsPage.class);
itnt.putExtra("stackId", stackDetails.getStackId());
itnt.putExtra("isPreview", "true");
itnt.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
createStackNewActivity.startActivity(itnt);
} else {
System.out.println(response.errorBody());
Toast.makeText(context, response.errorBody().toString(), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<GenericAPIResponse> call, Throwable t) {
t.printStackTrace();
}
});
}
And the code of second activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stack_details);
final Intent intent = getIntent();
final String stackId;
if (intent != null) { //Null Checking
stackId = intent.getStringExtra("stackId");
isPreview = intent.getStringExtra("isPreview");
stackTitleStr = intent.getStringExtra("stackTitle");
saveLine = (HashMap<String, Object>)intent.getSerializableExtra("saveLine");
}
else{
stackId = null;
}
On second activity, I have all variables are null. isPreview, stackTitleStr, saveLine are all null.
So anyone please help me quickly.
first you should not create the intent in the onResponse callBack method but create a static method in your StackDetailsPage activity that return the intent it needs. With that, this activity "said" to the other ones whats it needs, and it avoid duplicate string extra keys. use this :
//in StackDetailsPage activity
public static Intent getIntent(Context context, String stackId, String...)
{
Intent intent = new Intent(context, StackDetailsPage.class);
intent.putExtra("stackId", stackId);
...
return intent;
}
and then in onResponse method do that :
startActivity(StackDetailsPage.getIntent(context,stackDetails.getStackId(), ...))

FCM onReceived method to implement Shortcut Badger library

I found this library (https://github.com/leolin310148/ShortcutBadger) to implement app icon counter badge in android.
badge works when i implement in activity. but i want to implement this when push notification is received. i currently have the initialize code in onMesseageReceived() method in Firebase messaging service but its not working.
see code below:
Thanks for your help
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Logger.i("Received message");
//Shourtcut Badger
int badgeCount = 1;
ShortcutBadger.applyCount(context, badgeCount);
//parseNotification(bundle);
parseNotification(remoteMessage.getData());
if (remoteMessage.getData() != null) {
String str = remoteMessage.getData().get("notification");
String from_user = "";
String message = "";
String name = "";
int type = 0;
if (str != null && str.length() > 0) {
try {
JSONObject jobj = new JSONObject(str);
from_user = jobj.optString("from");
message = jobj.optString("message");
name = jobj.optString("name");
type = Integer.parseInt(jobj.optString("type"));
if (type == LIKE_STATUS) {
handleStatusLikeByFriendPush(jobj, "" + type);
} else if (type == PHOTO_UPDATE) {
handlePhotoUpdateByFriendPush(jobj, "" + type);
} catch (Exception e) {
e.printStackTrace();
}
} else {
message = "";//bundle.getString("message");
from_user = "";//bundle.getString("source");
if (from_user != null && from_user.contains(IMHandler.AT + IMHandler.DOMAIN)) {
from_user = from_user.substring(0, from_user.indexOf(IMHandler.AT));
}
showNotification(from_user, message, type, name);
}
}
}
public void handleStatusLikeByFriendPush(JSONObject jobj, String pushType) {
// method
}
public void handlePhotoLikeByFriendPush(JSONObject jobj, String pushType) {
//method implement
}
}
private void showNotification(String from, String body, int type, String name) {
}
}
After lots of research i understand implementation of this Shortcut badge is not working in FCM service. I Am Able to resolve this issue by simply calling a a custom service from FCM service each time push notification is received and the custom service handles the badge codes and there affter destroys itself.
This way is working perfectly.

AmazonSNS - AwsCredentials.properties - NullPointerException

I am new to Android Studio and intelliJ.
I am trying to work with AmazonSNS - Push. I am unable to figure out how to add AwsCredentials.properties file to classpath of the module. I get a NPE at line 57 in the image below(at method getResourceAsStream()). I added the required keys in AwsCredentials.properties file.
Error:
In the questions that i have come across on StackOverflow regarding similar issues, some suggested that the file should be in the root folder, where, src is. I placed it in the same folder as that of src, but still getting the NPE. I also tried placing the file in com/test/ but with no use.
How do i solve this? Are there any other steps involved?
EDIT after starting a bounty - Adding java files
Here is what i did till now..
Create an Android Application called MyApplication. Imported all classes(AndroidMobilePushApp.java, ExternalReceiver.java, MessageReceivingService.java) from the demo application. Added required libs, and ran it and got the registationId as response from Amazon.
In the same application, i created a new module called snspush and imported SNSMobilePush.java file into it. Also imported the AwsCredentials.properties file to the same path as that of SNSMobilePush.java. Added the keys in AwsCredentials.properties file.
Followed the steps in documentation to uncomment necessary funtions.
Project Structure:
Java files:
AndroidMobilePushApp.java:
public class AndroidMobilePushApp extends AppCompatActivity {
private TextView tView;
private SharedPreferences savedValues;
private String numOfMissedMessages;
// Since this activity is SingleTop, there can only ever be one instance. This variable corresponds to this instance.
public static Boolean inBackground = true;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
numOfMissedMessages = getString(R.string.num_of_missed_messages);
setContentView(R.layout.activity_main);
tView = (TextView) findViewById(R.id.tViewId);
tView.setMovementMethod(new ScrollingMovementMethod());
startService(new Intent(this, MessageReceivingService.class));
}
public void onStop(){
super.onStop();
inBackground = true;
}
public void onRestart(){
super.onRestart();
tView.setText("");;
}
public void onResume(){
super.onResume();
inBackground = false;
savedValues = MessageReceivingService.savedValues;
int numOfMissedMessages = 0;
if(savedValues != null){
numOfMissedMessages = savedValues.getInt(this.numOfMissedMessages, 0);
}
String newMessage = getMessage(numOfMissedMessages);
if(newMessage!=""){
Log.i("displaying message", newMessage);
tView.append(newMessage);
}
}
public void onNewIntent(Intent intent){
super.onNewIntent(intent);
setIntent(intent);
}
// If messages have been missed, check the backlog. Otherwise check the current intent for a new message.
private String getMessage(int numOfMissedMessages) {
String message = "";
String linesOfMessageCount = getString(R.string.lines_of_message_count);
if(numOfMissedMessages > 0){
String plural = numOfMissedMessages > 1 ? "s" : "";
Log.i("onResume","missed " + numOfMissedMessages + " message" + plural);
tView.append("You missed " + numOfMissedMessages +" message" + plural + ". Your most recent was:\n");
for(int i = 0; i < savedValues.getInt(linesOfMessageCount, 0); i++){
String line = savedValues.getString("MessageLine"+i, "");
message+= (line + "\n");
}
NotificationManager mNotification = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotification.cancel(R.string.notification_number);
SharedPreferences.Editor editor=savedValues.edit();
editor.putInt(this.numOfMissedMessages, 0);
editor.putInt(linesOfMessageCount, 0);
editor.commit();
}
else{
Log.i("onResume","no missed messages");
Intent intent = getIntent();
if(intent!=null){
Bundle extras = intent.getExtras();
if(extras!=null){
for(String key: extras.keySet()){
message+= key + "=" + extras.getString(key) + "\n";
}
}
}
}
message+="\n";
return message;
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == R.id.menu_clear){
tView.setText("");
return true;
}
else{
return super.onOptionsItemSelected(item);
}
}
}
ExternalReceiver.java
package com.test.awstestapp;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
public class ExternalReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
if(intent!=null){
Bundle extras = intent.getExtras();
if(!AndroidMobilePushApp.inBackground){
MessageReceivingService.sendToApp(extras, context);
}
else{
MessageReceivingService.saveToLog(extras, context);
}
}
}
}
MessageReceivingService.java
public class MessageReceivingService extends Service{
private GoogleCloudMessaging gcm;
public static SharedPreferences savedValues;
public static void sendToApp(Bundle extras, Context context){
Intent newIntent = new Intent();
newIntent.setClass(context, AndroidMobilePushApp.class);
newIntent.putExtras(extras);
newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(newIntent);
}
public void onCreate(){
super.onCreate();
final String preferences = getString(R.string.preferences);
savedValues = getSharedPreferences(preferences, Context.MODE_PRIVATE);
// In later versions multi_process is no longer the default
if(VERSION.SDK_INT > 9){
savedValues = getSharedPreferences(preferences, Context.MODE_MULTI_PROCESS);
}
gcm = GoogleCloudMessaging.getInstance(getBaseContext());
SharedPreferences savedValues = PreferenceManager.getDefaultSharedPreferences(this);
if(savedValues.getBoolean(getString(R.string.first_launch), true)){
register();
SharedPreferences.Editor editor = savedValues.edit();
editor.putBoolean(getString(R.string.first_launch), false);
editor.commit();
}
// Let AndroidMobilePushApp know we have just initialized and there may be stored messages
sendToApp(new Bundle(), this);
}
protected static void saveToLog(Bundle extras, Context context){
SharedPreferences.Editor editor=savedValues.edit();
String numOfMissedMessages = context.getString(R.string.num_of_missed_messages);
int linesOfMessageCount = 0;
for(String key : extras.keySet()){
String line = String.format("%s=%s", key, extras.getString(key));
editor.putString("MessageLine" + linesOfMessageCount, line);
linesOfMessageCount++;
}
editor.putInt(context.getString(R.string.lines_of_message_count), linesOfMessageCount);
editor.putInt(context.getString(R.string.lines_of_message_count), linesOfMessageCount);
editor.putInt(numOfMissedMessages, savedValues.getInt(numOfMissedMessages, 0) + 1);
editor.commit();
postNotification(new Intent(context, AndroidMobilePushApp.class), context);
}
protected static void postNotification(Intent intentAction, Context context){
final NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
final PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intentAction, Notification.DEFAULT_LIGHTS | Notification.FLAG_AUTO_CANCEL);
final Notification notification = new NotificationCompat.Builder(context).setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Message Received!")
.setContentText("")
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.getNotification();
mNotificationManager.notify(R.string.notification_number, notification);
}
private void register() {
new AsyncTask(){
protected Object doInBackground(final Object... params) {
String token;
try {
token = gcm.register(getString(R.string.project_number));
Log.i("registrationId", token);
}
catch (IOException e) {
Log.i("Registration Error", e.getMessage());
}
return true;
}
}.execute(null, null, null);
}
public IBinder onBind(Intent arg0) {
return null;
}
}
SNSMobilePush.java
package com.test;
public class SNSMobilePush {
private AmazonSNSClientWrapper snsClientWrapper;
public SNSMobilePush(AmazonSNS snsClient) {
this.snsClientWrapper = new AmazonSNSClientWrapper(snsClient);
}
public static final Map<Platform, Map<String, MessageAttributeValue>> attributesMap = new HashMap<Platform, Map<String, MessageAttributeValue>>();
static {
attributesMap.put(Platform.ADM, null);
attributesMap.put(Platform.GCM, null);
attributesMap.put(Platform.APNS, null);
attributesMap.put(Platform.APNS_SANDBOX, null);
attributesMap.put(Platform.BAIDU, addBaiduNotificationAttributes());
attributesMap.put(Platform.WNS, addWNSNotificationAttributes());
attributesMap.put(Platform.MPNS, addMPNSNotificationAttributes());
}
public static void main(String[] args) throws IOException {
/*
* TODO: Be sure to fill in your AWS access credentials in the
* AwsCredentials.properties file before you try to run this sample.
* http://aws.amazon.com/security-credentials
*/
AmazonSNS sns = new AmazonSNSClient(new PropertiesCredentials(
SNSMobilePush.class
.getResourceAsStream("AwsCredentials.properties")));
sns.setEndpoint("https://sns.us-west-2.amazonaws.com");
System.out.println("===========================================\n");
System.out.println("Getting Started with Amazon SNS");
System.out.println("===========================================\n");
try {
SNSMobilePush sample = new SNSMobilePush(sns);
/* TODO: Uncomment the services you wish to use. */
sample.demoAndroidAppNotification();
// sample.demoKindleAppNotification();
// sample.demoAppleAppNotification();
// sample.demoAppleSandboxAppNotification();
// sample.demoBaiduAppNotification();
// sample.demoWNSAppNotification();
// sample.demoMPNSAppNotification();
} catch (AmazonServiceException ase) {
System.out
.println("Caught an AmazonServiceException, which means your request made it "
+ "to Amazon SNS, but was rejected with an error response for some reason.");
System.out.println("Error Message: " + ase.getMessage());
System.out.println("HTTP Status Code: " + ase.getStatusCode());
System.out.println("AWS Error Code: " + ase.getErrorCode());
System.out.println("Error Type: " + ase.getErrorType());
System.out.println("Request ID: " + ase.getRequestId());
} catch (AmazonClientException ace) {
System.out
.println("Caught an AmazonClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with SNS, such as not "
+ "being able to access the network.");
System.out.println("Error Message: " + ace.getMessage());
}
}
public void demoAndroidAppNotification() {
// TODO: Please fill in following values for your application. You can
// also change the notification payload as per your preferences using
// the method
// com.amazonaws.sns.samples.tools.SampleMessageGenerator.getSampleAndroidMessage()
String serverAPIKey = "REPLACED_WITH_SERVER_API_KEY";
String applicationName = "snspushtest";
String registrationId = "REPLACED_WITH_REG_ID_FROM_AMAZON";
snsClientWrapper.demoNotification(Platform.GCM, "", serverAPIKey,
registrationId, applicationName, attributesMap);
}
public void demoKindleAppNotification() {
// TODO: Please fill in following values for your application. You can
// also change the notification payload as per your preferences using
// the method
// com.amazonaws.sns.samples.tools.SampleMessageGenerator.getSampleKindleMessage()
String clientId = "";
String clientSecret = "";
String applicationName = "";
String registrationId = "";
snsClientWrapper.demoNotification(Platform.ADM, clientId, clientSecret,
registrationId, applicationName, attributesMap);
}
public void demoAppleAppNotification() {
// TODO: Please fill in following values for your application. You can
// also change the notification payload as per your preferences using
// the method
// com.amazonaws.sns.samples.tools.SampleMessageGenerator.getSampleAppleMessage()
String certificate = ""; // This should be in pem format with \n at the
// end of each line.
String privateKey = ""; // This should be in pem format with \n at the
// end of each line.
String applicationName = "";
String deviceToken = ""; // This is 64 hex characters.
snsClientWrapper.demoNotification(Platform.APNS, certificate,
privateKey, deviceToken, applicationName, attributesMap);
}
public void demoAppleSandboxAppNotification() {
// TODO: Please fill in following values for your application. You can
// also change the notification payload as per your preferences using
// the method
// com.amazonaws.sns.samples.tools.SampleMessageGenerator.getSampleAppleMessage()
String certificate = ""; // This should be in pem format with \n at the
// end of each line.
String privateKey = ""; // This should be in pem format with \n at the
// end of each line.
String applicationName = "";
String deviceToken = ""; // This is 64 hex characters.
snsClientWrapper.demoNotification(Platform.APNS_SANDBOX, certificate,
privateKey, deviceToken, applicationName, attributesMap);
}
public void demoBaiduAppNotification() {
/*
* TODO: Please fill in the following values for your application. If
* you wish to change the properties of your Baidu notification, you can
* do so by modifying the attribute values in the method
* addBaiduNotificationAttributes() . You can also change the
* notification payload as per your preferences using the method
* com.amazonaws
* .sns.samples.tools.SampleMessageGenerator.getSampleBaiduMessage()
*/
String userId = "";
String channelId = "";
String apiKey = "";
String secretKey = "";
String applicationName = "";
snsClientWrapper.demoNotification(Platform.BAIDU, apiKey, secretKey,
channelId + "|" + userId, applicationName, attributesMap);
}
public void demoWNSAppNotification() {
/*
* TODO: Please fill in the following values for your application. If
* you wish to change the properties of your WNS notification, you can
* do so by modifying the attribute values in the method
* addWNSNotificationAttributes() . You can also change the notification
* payload as per your preferences using the method
* com.amazonaws.sns.samples
* .tools.SampleMessageGenerator.getSampleWNSMessage()
*/
String notificationChannelURI = "";
String packageSecurityIdentifier = "";
String secretKey = "";
String applicationName = "";
snsClientWrapper.demoNotification(Platform.WNS,
packageSecurityIdentifier, secretKey, notificationChannelURI,
applicationName, attributesMap);
}
public void demoMPNSAppNotification() {
/*
* TODO: Please fill in the following values for your application. If
* you wish to change the properties of your MPNS notification, you can
* do so by modifying the attribute values in the method
* addMPNSNotificationAttributes() . You can also change the
* notification payload as per your preferences using the method
* com.amazonaws
* .sns.samples.tools.SampleMessageGenerator.getSampleMPNSMessage ()
*/
String notificationChannelURI = "";
String applicationName = "";
snsClientWrapper.demoNotification(Platform.MPNS, "", "",
notificationChannelURI, applicationName, attributesMap);
}
private static Map<String, MessageAttributeValue> addBaiduNotificationAttributes() {
Map<String, MessageAttributeValue> notificationAttributes = new HashMap<String, MessageAttributeValue>();
notificationAttributes.put("AWS.SNS.MOBILE.BAIDU.DeployStatus",
new MessageAttributeValue().withDataType("String")
.withStringValue("1"));
notificationAttributes.put("AWS.SNS.MOBILE.BAIDU.MessageKey",
new MessageAttributeValue().withDataType("String")
.withStringValue("default-channel-msg-key"));
notificationAttributes.put("AWS.SNS.MOBILE.BAIDU.MessageType",
new MessageAttributeValue().withDataType("String")
.withStringValue("0"));
return notificationAttributes;
}
private static Map<String, MessageAttributeValue> addWNSNotificationAttributes() {
Map<String, MessageAttributeValue> notificationAttributes = new HashMap<String, MessageAttributeValue>();
notificationAttributes.put("AWS.SNS.MOBILE.WNS.CachePolicy",
new MessageAttributeValue().withDataType("String")
.withStringValue("cache"));
notificationAttributes.put("AWS.SNS.MOBILE.WNS.Type",
new MessageAttributeValue().withDataType("String")
.withStringValue("wns/badge"));
return notificationAttributes;
}
private static Map<String, MessageAttributeValue> addMPNSNotificationAttributes() {
Map<String, MessageAttributeValue> notificationAttributes = new HashMap<String, MessageAttributeValue>();
notificationAttributes.put("AWS.SNS.MOBILE.MPNS.Type",
new MessageAttributeValue().withDataType("String")
.withStringValue("token")); // This attribute is required.
notificationAttributes.put("AWS.SNS.MOBILE.MPNS.NotificationClass",
new MessageAttributeValue().withDataType("String")
.withStringValue("realtime")); // This attribute is required.
return notificationAttributes;
}
}
EDIT 2:
EDIT 3:
I changed the following code to:
AmazonSNS sns = new AmazonSNSClient(new PropertiesCredentials(
SNSMobilePush.class
.getResourceAsStream("AwsCredentials.properties")));
to
AmazonSNS sns = new AmazonSNSClient(new BasicAWSCredentials("ACCESS_KEY_REPLACED",
"SECRET_KEY_REPLACED"));
Now, there is a different error: Logcat
===========================================
Getting Started with Amazon SNS
===========================================
Exception in thread "main" java.lang.NoClassDefFoundError: org/xmlpull/v1/XmlPullParserException
at com.amazonaws.services.sns.AmazonSNSClient.invoke(AmazonSNSClient.java:2263)
at com.amazonaws.services.sns.AmazonSNSClient.createPlatformApplication(AmazonSNSClient.java:358)
at com.test.tools.AmazonSNSClientWrapper.createPlatformApplication(AmazonSNSClientWrapper.java:49)
at com.test.tools.AmazonSNSClientWrapper.demoNotification(AmazonSNSClientWrapper.java:119)
at com.test.SNSMobilePush.demoAndroidAppNotification(SNSMobilePush.java:104)
at com.test.SNSMobilePush.main(SNSMobilePush.java:71)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
Caused by: java.lang.ClassNotFoundException: org.xmlpull.v1.XmlPullParserException
at java.net.URLClassLoader$1.run(URLClassLoader.java:372)
at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:360)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 11 more
Process finished with exit code 1
I'm using sns v2.2.5 :
build.gradle > compile 'com.amazonaws:aws-android-sdk-sns:2.2.5'
Here is my solution for subscribe/unsubscribe:
public class AmazonPushClient {
private static final String TAG = "AmazonPushClient";
private static final String PLATFORM_APPLICATION_ARN = "*****";
private static final String IDENTITY_POOL_ID = "******";
private AmazonSNSClient mClient;
private boolean isUnregistering;
private Application mApp;
private NotifPreferencesHelper mNotifPreferencesHelper;
public AmazonPushClient(Application application) {
try {
mApp = application;
mClient = createPushClient(application);
mNotifPreferencesHelper = new NotifPreferencesHelper(application);
} catch (Exception e) {
LOGE(TAG, "AmazonPushClient", e);
}
}
#Nullable
private String token() {
try {
return InstanceID.getInstance(mApp).getToken(mApp.getString(R.string.gcm_defaultSenderId),
GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
} catch (Exception e) {
LOGW(TAG, "token", e);
return null;
}
}
private CognitoCachingCredentialsProvider cognitoCachingCredentialsProvider(Application application) {
return new CognitoCachingCredentialsProvider(
application,
IDENTITY_POOL_ID,
Regions.EU_WEST_1 // if your identity_pool_id start with : eu-west-1
);
}
private AmazonSNSClient createPushClient(Application application) {
AmazonSNSClient client = new AmazonSNSClient(cognitoCachingCredentialsProvider(application));
client.setRegion(Region.getRegion(Regions.EU_WEST_1));
client.addRequestHandler(mHandler);
return client;
}
public void pRegister() {
synchronized (TAG) {
LOGD(TAG, "registering");
isUnregistering = true;
String token = token();
if(TextUtils.isEmpty(token)) {
return;
}
mNotifPreferencesHelper.saveNotificationPreferences(true);
CreatePlatformEndpointRequest platformEndpointRequest = new CreatePlatformEndpointRequest();
platformEndpointRequest.setToken(token());
platformEndpointRequest.setPlatformApplicationArn(PLATFORM_APPLICATION_ARN);
CreatePlatformEndpointResult result = mClient.createPlatformEndpoint(platformEndpointRequest);
mNotifPreferencesHelper.storeEndpointArn(result.getEndpointArn());
}
}
public void pUnregister() {
synchronized (TAG) {
LOGD(TAG, "unregistering");
isUnregistering = false;
mNotifPreferencesHelper.saveNotificationPreferences(false);
DeleteEndpointRequest deletePlatformApplicationRequest = new DeleteEndpointRequest();
deletePlatformApplicationRequest.setEndpointArn(mNotifPreferencesHelper.getEndpointArn());
mClient.deleteEndpoint(deletePlatformApplicationRequest);
}
}
private RequestHandler2 mHandler = new RequestHandler2() {
#Override
public void beforeRequest(Request<?> request) {
}
#Override
public void afterResponse(Request<?> request, Response<?> response) {
if (isUnregistering) {
mNotifPreferencesHelper.storeEndpointArn(null);
}
}
#Override
public void afterError(Request<?> request, Response<?> response, Exception e) {
}
};
}
NotifPreferencesHelper is just something to store the EndpointARN. You have to use this class in a background thread
In association you have to implements GcmListenerService etc.. SNS is just for subscribe, not receive.
https://developers.google.com/cloud-messaging/
With respect to the Properties Credentials
A. Are you sure you are exporting the file in the build? Have you made sure you can access the file using regular file I/O outside of the credentials provider? Are you sure the file is formatted correctly (see https://github.com/aws/aws-sdk-android/blob/master/aws-android-sdk-core/src/main/java/com/amazonaws/auth/PropertiesCredentials.java)
accessKey=KEY
secretKey=SECRET
Also looking at the source you should be able to load this file yourself using http://developer.android.com/reference/java/util/Properties.html.
However, I highly recommend not using this credentials provider. It is extremely unsafe in a mobile applications. Anyone could decompile your app and steal your credentials. A much safer approach is to use Amazon Cognito, which there is a plethora of examples. (Bottom of https://docs.aws.amazon.com/mobile/sdkforandroid/developerguide/setup.html , any of the examples here: https://docs.aws.amazon.com/mobile/sdkforandroid/developerguide/getting-started-android.html as well as samples in the GitHub repo https://github.com/awslabs/aws-sdk-android-samples
Cognito requires a little bit of set-up but the guides are tested, and it really doesn't take much more than a few minutes to be much more secure.
Don't think you should import 'SNSMobilePush' to a module of your android application
In the same application, i created a new module called snspush and
imported SNSMobilePush.java file into it. Also imported the
AwsCredentials.properties file to the same path as that of
SNSMobilePush.java. Added the keys in AwsCredentials.properties file.
SNSMobilePush is just a Java app provided by AWS to do tasks like
upload (bulkupload package) several tokens (device tokens or registration IDs) to Amazon SNS or
send a push notification.
You need to register your mobile app with AWS (using AndroidMobilePushApp android app). You should obtain below information (refer this link)
Client ID and client secret
API key
Device token or Registration ID (per device)
Then you can use SNSMobilePush java app or even a AWS SNS console as described here to send push notification to your registered device.
I would suggest you to try out sending push notification from the console instead of java app. You can register tokens from devices that will install your app in the future as described in the one of the options (preferably the last option) as described here

Access browser url from running background service?

In Android is it possible for a background service to access the url of the web page a user is currently looking at in their Chrome browser? From what ive read so far this is not possible without root access. Im just asking to see if anyone knows if maybe there is some other standard way of doing it?
No, it is not possible if you're not a Chrome developer.
yes you can.
you can use accessibility service
note: if you're not an accessibility app, Google Play will not allow you on the app store if you use this API. If you're writing a personal app its fine.
example:
How to get url from browser using accessibility service
The implementation:
public class UrlInterceptorService extends AccessibilityService {
private HashMap<String, Long> previousUrlDetections = new HashMap<>();
#Override
protected void onServiceConnected() {
AccessibilityServiceInfo info = getServiceInfo();
info.eventTypes = AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED;
info.packageNames = packageNames();
info.feedbackType = AccessibilityServiceInfo.FEEDBACK_VISUAL;
//throttling of accessibility event notification
info.notificationTimeout = 300;
//support ids interception
info.flags = AccessibilityServiceInfo.FLAG_REPORT_VIEW_IDS |
AccessibilityServiceInfo.FLAG_RETRIEVE_INTERACTIVE_WINDOWS;
this.setServiceInfo(info);
}
private String captureUrl(AccessibilityNodeInfo info, SupportedBrowserConfig config) {
List<AccessibilityNodeInfo> nodes = info.findAccessibilityNodeInfosByViewId(config.addressBarId);
if (nodes == null || nodes.size() <= 0) {
return null;
}
AccessibilityNodeInfo addressBarNodeInfo = nodes.get(0);
String url = null;
if (addressBarNodeInfo.getText() != null) {
url = addressBarNodeInfo.getText().toString();
}
addressBarNodeInfo.recycle();
return url;
}
#Override
public void onAccessibilityEvent(#NonNull AccessibilityEvent event) {
AccessibilityNodeInfo parentNodeInfo = event.getSource();
if (parentNodeInfo == null) {
return;
}
String packageName = event.getPackageName().toString();
SupportedBrowserConfig browserConfig = null;
for (SupportedBrowserConfig supportedConfig: getSupportedBrowsers()) {
if (supportedConfig.packageName.equals(packageName)) {
browserConfig = supportedConfig;
}
}
//this is not supported browser, so exit
if (browserConfig == null) {
return;
}
String capturedUrl = captureUrl(parentNodeInfo, browserConfig);
parentNodeInfo.recycle();
//we can't find a url. Browser either was updated or opened page without url text field
if (capturedUrl == null) {
return;
}
long eventTime = event.getEventTime();
String detectionId = packageName + ", and url " + capturedUrl;
//noinspection ConstantConditions
long lastRecordedTime = previousUrlDetections.containsKey(detectionId) ? previousUrlDetections.get(detectionId) : 0;
//some kind of redirect throttling
if (eventTime - lastRecordedTime > 2000) {
previousUrlDetections.put(detectionId, eventTime);
analyzeCapturedUrl(capturedUrl, browserConfig.packageName);
}
}
private void analyzeCapturedUrl(#NonNull String capturedUrl, #NonNull String browserPackage) {
String redirectUrl = "your redirect url is here";
if (capturedUrl.contains("facebook.com")) {
performRedirect(redirectUrl, browserPackage);
}
}
/** we just reopen the browser app with our redirect url using service context
* We may use more complicated solution with invisible activity to send a simple intent to open the url */
private void performRedirect(#NonNull String redirectUrl, #NonNull String browserPackage) {
try {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(redirectUrl));
intent.setPackage(browserPackage);
intent.putExtra(Browser.EXTRA_APPLICATION_ID, browserPackage);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);
}
catch(ActivityNotFoundException e) {
// the expected browser is not installed
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(redirectUrl));
startActivity(i);
}
}
#Override
public void onInterrupt() { }
#NonNull
private static String[] packageNames() {
List<String> packageNames = new ArrayList<>();
for (SupportedBrowserConfig config: getSupportedBrowsers()) {
packageNames.add(config.packageName);
}
return packageNames.toArray(new String[0]);
}
private static class SupportedBrowserConfig {
public String packageName, addressBarId;
public SupportedBrowserConfig(String packageName, String addressBarId) {
this.packageName = packageName;
this.addressBarId = addressBarId;
}
}
/** #return a list of supported browser configs
* This list could be instead obtained from remote server to support future browser updates without updating an app */
#NonNull
private static List<SupportedBrowserConfig> getSupportedBrowsers() {
List<SupportedBrowserConfig> browsers = new ArrayList<>();
browsers.add( new SupportedBrowserConfig("com.android.chrome", "com.android.chrome:id/url_bar"));
browsers.add( new SupportedBrowserConfig("org.mozilla.firefox", "org.mozilla.firefox:id/url_bar_title"));
return browsers;
}
}
and accessibility service config:
<accessibility-service
xmlns:android="http://schemas.android.com/apk/res/android"
android:description="#string/accessibility_service_description"
android:canRetrieveWindowContent="true"
android:settingsActivity=".ServiceSettingsActivity" />

How to read text from an image using OCR in android

I want to implement OCR in Android. I.e. getting texts from a business card image. I used code from here.
But when I run this code I got the following error:
java.lang.NoClassDefFoundError:
org.apache.http.entity.mime.content.FileBody
I think it points to the following line:
final FileBody image = new FileBody(new File(filePath));
of the OCRServiceAPI class. How can I fix this?
Can't guess about your above error but I have done this task in Blackberry by using third party application ABBYY product of OCR on PHP server.
During my long R & D I have also worked on the below link of Github_Abbyy.
For using this code you should create a free account here: ocrsdk.com
Not all the Apache packages are available by default in Android, so you will have to download them from the Apache repositories and include those yourself. See the question Android libraries not found and the links provided in the answer there.
Edit: Specifically the sub-packages of org.apache.http.entity are not included, only the entity package itself.
In the example project given by the OCR API they have placed the mime package in a jar in the lib folder.
Checkout that whether you are getting correct path of the image which are selecting from the gallery.
I have also tried this demo and its working fine for me.
Here I'm posting my code:
OCRServiceAPI.java
public class OCRServiceAPI {
public final String m_serviceUrl = "http://api.ocrapiservice.com/1.0/rest/ocr";
private final String m_paramImage = "image";
private final String m_paramLanguage = "language";
private final String m_paramApiKey = "apikey";
private String m_apiKey, m_responseText;
private int m_responseCode;
public OCRServiceAPI(final String p_apiKey) {
this.m_apiKey = p_apiKey;
}
/*
* Convert image to text.
*
* #param language The image text language.
*
* #param filePath The image absolute file path.
*
* #return true if everything went okay and false if there is an error with
* sending and receiving data.
*/
public boolean convertToText(final String p_language,
final String p_filePath) {
try {
sendImage(p_language, p_filePath);
return true;
} catch (ClientProtocolException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
/*
* Send image to OCR service and read response.
*
* #param language The image text language.
*
* #param filePath The image absolute file path.
*/
private void sendImage(final String p_language, final String p_filePath)
throws ClientProtocolException, IOException {
final HttpClient m_httpclient = new DefaultHttpClient();
final HttpPost m_httppost = new HttpPost(m_serviceUrl);
final FileBody m_image = new FileBody(new File(p_filePath));
final MultipartEntity m_reqEntity = new MultipartEntity();
m_reqEntity.addPart(m_paramImage, m_image);
m_reqEntity.addPart(m_paramLanguage, new StringBody(p_language));
m_reqEntity.addPart(m_paramApiKey, new StringBody(getApiKey()));
m_httppost.setEntity(m_reqEntity);
final HttpResponse m_response = m_httpclient.execute(m_httppost);
final HttpEntity m_resEntity = m_response.getEntity();
final StringBuilder m_sb = new StringBuilder();
if (m_resEntity != null) {
final InputStream m_stream = m_resEntity.getContent();
byte m_bytes[] = new byte[4096];
int m_numBytes;
while ((m_numBytes = m_stream.read(m_bytes)) != -1) {
if (m_numBytes != 0) {
m_sb.append(new String(m_bytes, 0, m_numBytes));
}
}
}
setResponseCode(m_response.getStatusLine().getStatusCode());
setResponseText(m_sb.toString());
}
public int getResponseCode() {
return m_responseCode;
}
public void setResponseCode(int p_responseCode) {
this.m_responseCode = p_responseCode;
}
public String getResponseText() {
return m_responseText;
}
public void setResponseText(String p_responseText) {
this.m_responseText = p_responseText;
}
public String getApiKey() {
return m_apiKey;
}
public void setApiKey(String p_apiKey) {
this.m_apiKey = p_apiKey;
} }
SampleActivity.java
public class SampleActivity extends Activity implements OnClickListener {
private final int RESPONSE_OK = 200;
private final int IMAGE_PICKER_REQUEST = 1;
private TextView m_tvPicNameText;
private EditText m_etLangCodeField, m_etApiKeyFiled;
private String m_apiKey; // T7GNRh7VmH
private String m_langCode; // en
private String m_fileName;
#Override
public void onCreate(Bundle p_savedInstanceState) {
super.onCreate(p_savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
m_tvPicNameText = (TextView) findViewById(R.id.imageName);
m_etLangCodeField = (EditText) findViewById(R.id.lanuageCode);
m_etApiKeyFiled = (EditText) findViewById(R.id.apiKey);
m_etApiKeyFiled.setText("T7GNRh7VmH");
final Button m_btnPickImage = (Button) findViewById(R.id.picImagebutton);
m_btnPickImage.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Starting image picker activity
startActivityForResult(
new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI),
IMAGE_PICKER_REQUEST);
}
});
final Button m_btnConvertText = (Button) findViewById(R.id.convert);
m_btnConvertText.setOnClickListener(this);
}
public void onClick(View p_v) {
m_apiKey = m_etApiKeyFiled.getText().toString();
m_langCode = m_etLangCodeField.getText().toString();
// Checking are all fields set
if (m_fileName != null && !m_apiKey.equals("")
&& !m_langCode.equals("")) {
final ProgressDialog m_prgDialog = ProgressDialog.show(
SampleActivity.this, "Loading ...", "Converting to text.",
true, false);
final Thread m_thread = new Thread(new Runnable() {
public void run() {
final OCRServiceAPI m_apiClient = new OCRServiceAPI(
m_apiKey);
m_apiClient.convertToText(m_langCode, m_fileName);
// Doing UI related code in UI thread
runOnUiThread(new Runnable() {
public void run() {
m_prgDialog.dismiss();
// Showing response dialog
final AlertDialog.Builder m_alert = new AlertDialog.Builder(
SampleActivity.this);
m_alert.setMessage(m_apiClient.getResponseText());
m_alert.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface p_dialog,
int p_id) {
}
});
// Setting dialog title related from response code
if (m_apiClient.getResponseCode() == RESPONSE_OK) {
m_alert.setTitle("Success");
} else {
m_alert.setTitle("Faild");
}
m_alert.show();
}
});
}
});
m_thread.start();
} else {
Toast.makeText(SampleActivity.this, "All data are required.",
Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onActivityResult(int p_requestCode, int p_resultCode,
Intent p_data) {
super.onActivityResult(p_requestCode, p_resultCode, p_data);
if (p_requestCode == IMAGE_PICKER_REQUEST && p_resultCode == RESULT_OK) {
m_fileName = getRealPathFromURI(p_data.getData());
m_tvPicNameText.setText("Selected: en"
+ getStringNameFromRealPath(m_fileName));
}
}
/*
* Returns image real path.
*/
private String getRealPathFromURI(final Uri p_contentUri) {
final String[] m_proj = { MediaStore.Images.Media.DATA };
final Cursor m_cursor = managedQuery(p_contentUri, m_proj, null, null,
null);
int m_columnIndex = m_cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
m_cursor.moveToFirst();
return m_cursor.getString(m_columnIndex);
}
/*
* Cuts selected file name from real path to show in screen.
*/
private String getStringNameFromRealPath(final String bucketName) {
return bucketName.lastIndexOf('/') > 0 ? bucketName
.substring(bucketName.lastIndexOf('/') + 1) : bucketName;
} }

Categories

Resources