getApplicationContext error - android

I'm trying to store my device token from my android app programmatically to AWS SNS platform application.
I'm getting an error in getApplicationContext() method. Anyone with a solution for this error?
This is my code:
public class RegisterIdForAWS extends AsyncTask<String, Void, Void> {
private Exception exception;
#Override
protected Void doInBackground(String... strings) {
try {
String pushNotificationRegId = FirebaseInstanceId.getInstance().getToken();
if (pushNotificationRegId != null) {
CognitoCachingCredentialsProvider provider = new CognitoCachingCredentialsProvider(
getApplicationContext(),
"us-west-2:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
Regions.US_WEST_2);
String platformApplicationArn = "arn:aws:sns:us-west-2:11111111111:app/GCM/123";
AmazonSNSClient pushClient = new AmazonSNSClient(provider);
pushClient.setRegion(Region.getRegion(Regions.US_WEST_2));
String customPushData = "";
CreatePlatformEndpointRequest platformEndpointRequest = new CreatePlatformEndpointRequest();
platformEndpointRequest.setCustomUserData(customPushData);
platformEndpointRequest.setToken(pushNotificationRegId);
platformEndpointRequest.setPlatformApplicationArn(platformApplicationArn);
CreatePlatformEndpointResult result = pushClient.createPlatformEndpoint(platformEndpointRequest);
Log.w(TAG, "Amazon Push reg result: " + result);
}
} catch (Exception e) {
this.exception = e;
}
return null;
}
protected void onPostExecute(String text) {
Log.w(TAG, "Amazon Push reg Finished");
}
}

In constructor of your async class, pass Context
private Context mContext;
public RegisterIdForAWS (Context context){
mContext = context;
}
And instantiate class like this:
RegisterIdForAWS task = new RegisterIdForAWS (context);
Hope it helps.

Related

Null pointer exception running connected test in Android studio

I am trying to execute connected test for P4, however I am reciing an "Null pointer exception error" for P4
Error message:
:00:02 PM null
java.lang.NullPointerException
at com.android.ddmlib.Client.read(Client.java:692)
at com.android.ddmlib.MonitorThread.processClientActivity(MonitorThread.java:304)
at com.android.ddmlib.MonitorThread.run(MonitorThread.java:256)
It is a standard test, verifying non-empty string in the Async task
Test function:
public void runCloudModuleTest() {
String joke = null;
JokesAsyncTask jokesAsyncTask = new JokesAsyncTask(getContext(), null);
jokesAsyncTask.execute();
try {
joke = jokesAsyncTask.get();
Log.d("CloudModuleTest", "Retrieved a non-empty string successfully: " + joke);
} catch (Exception e) {
e.printStackTrace();
}
assertNotNull(joke);
}
Can someone help me understand what the issue is?
AsyncTask: The Async task pulls data from google cloud engine
public class JokesAsyncTask extends AsyncTask, Void, String> {
private static JokeApi myApiService = null;
private Context mContext;
private String mResult;
private ProgressBar mProgressBar;
public JokesAsyncTask(Context context, ProgressBar progressBar) {
this.mContext = context;
this.mProgressBar = progressBar;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
if (mProgressBar != null) {
mProgressBar.setVisibility(View.VISIBLE);
}
}
#Override
protected String doInBackground(Pair<Context, String>... pairs) {
if (myApiService == null) {
JokeApi.Builder builder = new JokeApi.Builder(AndroidHttp.newCompatibleTransport(),
new AndroidJsonFactory(), null)
.setRootUrl("https://testandroiddevelopment.appspot.com/_ah/api/");
myApiService = builder.build();
}
try {
return myApiService.sendJoke(new JokeBean()).execute().getJoke();
} catch (IOException e) {
return e.getMessage();
}
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (mProgressBar != null) {
mProgressBar.setVisibility(View.GONE);
}
mResult = result;
startJokeDisplayActivity();
}
private void startJokeDisplayActivity() {
Intent intent = new Intent(mContext, JokeViewActivity.class);
intent.putExtra(JokeViewActivity.JOKE_KEY, mResult);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(intent);
}
}
I have referenced the variable and it is not an issue due due to the below post, however I did investigate and finally cleaned up and rebuild the project that helped resolved the issue
I have referenced the variable and it is not an issue due due to the post #AxelH, however I did investigate and finally cleaned up and rebuild the project that helped resolved the issue

Google App Engine Unable to Send GCM Token

I am working with Google App Engine .I want to Send GCM toke(RegID) to App Engine Server.But Problem is that when i pass RegId as a parameter Nothing happen and when i pass normal string like"abcefghi" the string is passed to server
my code is shown below
public class SendInstanceidAsync extends AsyncTask<Void, Void, UpdateInstanceIdResult> {
private UpdateinstanceidAPI updateinstanceidAPIservice;
private String token;
private String scholarNumber;
private String schoolId;
private RegistrationIntentService registrationIntentService;
public SendInstanceidAsync(RegistrationIntentService registrationIntentService, String token, String schoolId, String scholarNumber) {
this.token = token;
this.scholarNumber = scholarNumber;
this.schoolId = schoolId;
this.registrationIntentService = registrationIntentService;
}
#Override
protected UpdateInstanceIdResult doInBackground(Void... params) {
UpdateInstanceIdResult updateInstanceIdResult = new UpdateInstanceIdResult();
if (updateinstanceidAPIservice == null) {
UpdateinstanceidAPI.Builder builder = new UpdateinstanceidAPI.Builder(AndroidHttp.newCompatibleTransport(),
new AndroidJsonFactory(), null)
.setRootUrl("http://xxx.xxx.x.x:xxxx/_xx/api/")
.setGoogleClientRequestInitializer(new UpdateinstanceidAPIRequestInitializer() {
#Override
protected void initializeUpdateinstanceidAPIRequest(UpdateinstanceidAPIRequest<?> request) throws IOException {
request.setDisableGZipContent(true);
}
});
updateinstanceidAPIservice = builder.build();
}
try {
updateInstanceIdResult = updateinstanceidAPIservice.updateInstanceID(schoolId, scholarNumber, token).execute();
} catch (IOException e) {
e.printStackTrace();
}
return updateInstanceIdResult;
}

Asynchronous call to server being blocked by bluetooth LE Scan

I have an Activity which constructs a RESTManager class (used to make an asynchronous call to the server and return data to the Activity).
However, after I construct my RESTManager and call the server using
//Retrieve data from server
RESTManager m = new RESTManager(this,getApplicationContext());
//Set the data list
m.delegate=this;
m.retrieveRoomData();
the server call does not go through until I turn off bluetooth scanning.
However, I start my bluetooth scan immediately after the RESTManager as such:
beaconManager = BeaconManager.getInstanceForApplication(this);
beaconManager.setBackgroundScanPeriod(1100l);
beaconManager.setBackgroundBetweenScanPeriod(100l);
beaconManager.setForegroundScanPeriod(1100l);
beaconManager.setForegroundBetweenScanPeriod(100l);
//Set the custom BeaconLayout for iBeacons
if (myPref.getBoolean("layoutSet", true)) {
beaconManager.getBeaconParsers().add(new BeaconParser().setBeaconLayout("m:0-3=4c000215,i:4-19,i:20-21,i:22-23,p:24-24"));
backgroundPowerSaver = new BackgroundPowerSaver(this);
Log.v("Beacon Layout", "Beacon Layout Set");
myPref.edit().putBoolean("layoutSet", false).apply();
myPref.edit().commit();
}
beaconManager.bind(this);
I am not getting any error.
Is there any reason why my AsyncTask from RESTManager would hang from the bluetooth scans?
Relevant code:
RESTManager class
public class RESTManager {
private DateTime lastUpdate = DateTime.now();
public AsyncResponse delegate=null;
private SharedPreferences mPrefs;
private SharedPreferences.Editor preferenceEditor;
private ArrayList<RoomData> roomDataList = new ArrayList<RoomData>();
private ArrayList<MeetingData> meetingDataList = new ArrayList<MeetingData>();
private Activity currentActivity;
private Context context;
public RESTManager(Activity currentActivity, Context context) {
this.currentActivity = currentActivity;
this.context = context;
mPrefs = PreferenceManager.getDefaultSharedPreferences(context);
}
//Todo update meeting data logic
public ArrayList<MeetingData> retrieveMeetingDataFromServer() {
return null;
}
public void retrieveRoomData() {
new CallServerForRoomData().execute();
}
//TODO add timestamping logic.
private class CallServerForRoomData extends AsyncTask<String, Void, String> {
String myJsonData = "";
#Override
protected String doInBackground(String... params) {
//If the data isn't cached, call the server.
if (!mPrefs.contains("RoomData")) {
try {
setupHttpClient();
HttpClient myClient = new HttpClient(RequestMethod.GET, "http://10.184.46.217:9012/v1/rooms", new HttpHeaders(), null, null);
myClient.connect();
HttpResponse mR = myClient.processResponse();
myJsonData = mR.getServerResponseAsString();
System.out.println(myJsonData);
preferenceEditor = mPrefs.edit();
preferenceEditor.putString("RoomData", myJsonData);
preferenceEditor.commit();
setRoomDataList(convertRoomDataJson(myJsonData));
return "server";
} catch (HttpClientException e) {
e.printStackTrace();
}
}
//If it is cached, retrieve the data locally.
else {
setRoomDataList(convertRoomDataJson(mPrefs.getString("RoomData", "NULL")));
return "local";
}
return "Done";
}
protected void onPostExecute(final String result) {
delegate.dataFinishedRetrieving(getRoomDataList());
// setRoomDataList(convertRoomDataJson(myJsonData));
currentActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(context, "Data retrieved on " + result + " storage", Toast.LENGTH_SHORT).show();
}
});
}
}
/**
* AsyncTask for retrieving a room's meeting data.
* Pass in the room's unique identifier as a parameter of the execute method.
*/
//TODO add timestamping logic
private class CallServerForMeetingData extends AsyncTask<String, Void, String> {
String myJsonData = "";
#Override
protected String doInBackground(String... params) {
try {
setupHttpClient();
HttpClient myClient = new HttpClient(RequestMethod.GET, "http://10.184.146.217:9012/v1/room/" + params[0] + "/schedule", new HttpHeaders(), null, null);
myClient.connect();
HttpResponse mR = myClient.processResponse();
myJsonData = mR.getServerResponseAsString();
} catch (HttpClientException e) {
e.printStackTrace();
}
//Set the converted MeetingData to the RoomData object
for (RoomData e : roomDataList) {
if (e.getObjectId() == params[0]) {
e.setMeetingData(convertMeetingDataJson(myJsonData));
}
}
return "Done";
}
}
//Initializes the HTTPClient and attaches it to the application lifecycle.
public void setupHttpClient() {
HttpCacheManager.init(Application.getAppContext());
}
public ArrayList<MeetingData> convertMeetingDataJson(String JsonData) {
final Gson gson = initCustomGSON();
Type MeetingDataListType = null;
if (JsonData != "") {
MeetingDataListType = new TypeToken<ArrayList<MeetingData>>() {
}.getType();
}
return (gson.fromJson(JsonData, MeetingDataListType));
}
public ArrayList<RoomData> convertRoomDataJson(String JsonData) {
final Gson gson = initCustomGSON();
Type RoomDataListType = null;
if (!JsonData.equals("")) {
RoomDataListType = new TypeToken<ArrayList<RoomData>>() {
}.getType();
roomDataList = (gson.fromJson(JsonData, RoomDataListType));
}
roomDataList = (gson.fromJson(JsonData, RoomDataListType));
for (RoomData e : roomDataList) {
Log.v("RoomData name", e.getName());
Log.v("RoomData roomId", e.getObjectId());
//Log.v("RoomData imageUrl", e.getImageUrl());
if (e.getBeacons() != null) {
Log.v("Number of beacons", e.getBeacons().toString());
}
}
return roomDataList;
}
/**
* Initializes the GSON Json Decoder with the custom JodaTime serializers.
*
* #return
*/
public Gson initCustomGSON() {
final GsonBuilder builder = new GsonBuilder();
JodaTimeConverters converter = new JodaTimeConverters();
converter.registerAll(builder);
return builder.create();
}
public ArrayList<RoomData> getRoomDataList() {
return roomDataList;
}
public void setRoomDataList(ArrayList<RoomData> roomDataList) {
this.roomDataList = roomDataList;
}
public void setMeetingDataListForRoom(RoomData whichRoom) {
new CallServerForMeetingData().execute(whichRoom.getObjectId());
}
}

How to use implicit intent from non activity class and in fragment

public class HomeFragment extends Fragment {
ShareLink statLoc;
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
statLoc = new ShareLink();
statLoc.execute();
}
The above code is my fragment and am executing a class named ShareLink().
In that ShareLink class I used implicit intent to send data like below
public class ShareLink extends AsyncTask<String, String, String> {
String urlShare = DeviceIdGen.hmUrl;
String statusLoc = null;
public static String locLink = null;
private static String loc = null;
Context context;
String locUrl;
protected String doInBackground(String... params) {
WebServiceTasks wstShare = new WebServiceTasks();
return wstShare.getMethod(urlShare);
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONObject jResult = new JSONObject(result);
statusLoc = jResult.getString("status");
if (statusLoc.equals("success")) {
loc = jResult.getString("link");
locUrl = "My Current Location :" + locLink + "\n\n"
+ "My Key : " + loc;
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.setType("text/plain");
startActivity((emailIntent).putExtra(
android.content.Intent.EXTRA_TEXT, locUrl));
}
} catch (JSONException e) {
e.printStackTrace();
}}}
But am not able to achieve it. Please help as am a newbie
Just Edit your AsyncTask,
Add a constructor to it
public class ShareLink extends AsyncTask<String, String, String> {
String urlShare = DeviceIdGen.hmUrl;
String statusLoc = null;
public static String locLink = null;
private static String loc = null;
String locUrl;
private Context context = null;
public ShareLink(Context context) {
this.context = context;
}
protected String doInBackground(String... params) {
WebServiceTasks wstShare = new WebServiceTasks();
return wstShare.getMethod(urlShare);
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONObject jResult = new JSONObject(result);
statusLoc = jResult.getString("status");
if (statusLoc.equals("success")) {
loc = jResult.getString("link");
locUrl = "My Current Location :" + locLink + "\n\n"
+ "My Key : " + loc;
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.setType("text/plain");
context.startActivity((emailIntent).putExtra(
android.content.Intent.EXTRA_TEXT, locUrl));
}
} catch (JSONException e) {
e.printStackTrace();
}}}
And invoke your AsyncTask as
statLoc = new ShareLink(getActivity());
statLoc.execute();
you could pass a context or an activity to your ShareLink class and use that instance to start your intent.
for example
private Context context;
public ShareLink (Context context){
this.context = context;
}
and then in your onPostExecute you can use context.startActivity() or whatever you wanna do with the intent.

OAuth token with Google Play Game Services

Is there a way to get the token that was used to log in the user with Google Play Game Services?
I'm looking for something like:
#Override
public void onSignInSucceeded() {
String email = getGamesClient().getCurrentAccountName();
String token = getGamesClient().getToken();
}
I need this to authenticate the user when they are contacting my own server.
This is how I managed to get the token:
#Override
public void onSignInSucceeded() {
String email = getGamesClient().getCurrentAccountName();
String scopes = getScopes();
new registerBackground(getApplicationContext()).execute(email, scopes);
}
private class registerBackground extends AsyncTask<String, Void, Void> {
Context context;
registerBackground (Context context) {
this.context = context;
}
#Override
protected Void doInBackground(String... params) {
try {
String oAuthToken = GoogleAuthUtil.getToken(context, params[0], params[1]);
...
catch (Exception e) {
e.printStackTrace();
}
}
...
}

Categories

Resources