How to create in-app billing in application? - java

I use example from Android developers, and have created code:
package com.nda.quizapp;
import com.nda.dungeons.BillingService;
import com.nda.dungeons.Consts;
import com.nda.dungeons.ResponseHandler;
import com.nda.dungeons.Consts.PurchaseState;
import com.nda.dungeons.Consts.ResponseCode;
import com.nda.dungeons.PurchaseObserver;
import com.nda.dungeons.Consts.PurchaseState;
import com.nda.dungeons.Consts.ResponseCode;
import com.nda.dungeons.BillingService.RequestPurchase;
import com.nda.dungeons.BillingService.RestoreTransactions;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class QuizappUpgradeActivity extends Activity implements OnClickListener{
private class QuestionsPurchaseObserver extends PurchaseObserver {
public QuestionsPurchaseObserver(Handler handler) {
super(QuizappUpgradeActivity.this, handler);
}
public QuestionsPurchaseObserver(Activity activity, Handler handler) {
super(activity, handler);
// TODO Auto-generated constructor stub
}
#Override
public void onBillingSupported(boolean supported) {
// TODO Auto-generated method stub
Log.e("method", "onBillingSupported");
}
#Override
public void onPurchaseStateChange(PurchaseState purchaseState,
String itemId, int quantity, long purchaseTime,
String developerPayload) {
// TODO Auto-generated method stub
Log.e("method", "onPurchaseStateChange");
}
#Override
public void onRequestPurchaseResponse(RequestPurchase request,
ResponseCode responseCode) {
Log.e("method", "onRequestPurchaseResponse");
// TODO Auto-generated method stub
if (responseCode == ResponseCode.RESULT_OK) {
Log.e("RESULT", "OK");
} else if (responseCode == ResponseCode.RESULT_USER_CANCELED) {
Log.e("RESULT", "CANCEL");
} else {
Log.e("RESULT", "ERROR");
}
}
#Override
public void onRestoreTransactionsResponse(RestoreTransactions request,
ResponseCode responseCode) {
// TODO Auto-generated method stub
Log.e("method", "onRestoreTransactionsResponse");
}
}
private QuestionsPurchaseObserver mObserver;
private Handler mHandler;
private BillingService mBillingService;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.upgrade);
initialize();
mHandler = new Handler();
mObserver = new QuestionsPurchaseObserver(mHandler);
mBillingService = new BillingService();
mBillingService.setContext(this);
ResponseHandler.register(mObserver);
if (!mBillingService.checkBillingSupported()) {
Toast.makeText(this, "Paying isn't support", Toast.LENGTH_LONG).show();
}
}
private void initialize() {
Button bronze=(Button)findViewById(R.id.buttonBuyBronze);
Button silver=(Button)findViewById(R.id.buttonBuySilver);
Button gold=(Button)findViewById(R.id.buttonBuyGold);
bronze.setOnClickListener(this);
silver.setOnClickListener(this);
gold.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (mBillingService.requestPurchase("bronze_q", null)) {
Log.e("1", "bronze yes");
}
else {
Log.e("1", "bronze no");
}
}
#Override
protected void onStart() {
super.onStart();
ResponseHandler.register(mObserver);
}
#Override
protected void onStop() {
super.onStop();
//ResponseHandler.unregister(mObserver);
}
}
The window for paying is shown sucessfully, but I have problem - if I close this window than I don't get any events in onRequestPurchaseResponse method. Where have I made mistake? Thank you.

You should add this lines to manifest file:
<receiver android:name="BillingReceiver">
<intent-filter>
<action android:name="com.android.vending.billing.IN_APP_NOTIFY" />
<action android:name="com.android.vending.billing.RESPONSE_CODE" />
<action android:name="com.android.vending.billing.PURCHASE_STATE_CHANGED" />
</intent-filter>
</receiver>
You can find it here

Related

Mapbox navigation useroffroute function override not working

Offroute not triggered
I am using navigation launcher.I have tried using navigation view too.But the useroffroute function is not getting triggered.
package com.example.lenovo.offroutetest;
import java.io.File;
import java.io.FileOutputStream;
import java.util.List;
import android.os.Bundle;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
// classes needed to initialize map
import com.mapbox.mapboxsdk.Mapbox;
import com.mapbox.mapboxsdk.maps.MapView;
// classes needed to add the location component
import com.mapbox.geojson.Point;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.mapboxsdk.maps.OnMapReadyCallback;
import android.location.Location;
import android.widget.Toast;
import com.mapbox.mapboxsdk.geometry.LatLng;
import android.support.annotation.NonNull;
import com.mapbox.mapboxsdk.location.LocationComponent;
import com.mapbox.mapboxsdk.location.modes.CameraMode;
import com.mapbox.services.android.navigation.ui.v5.NavigationLauncherOptions;
import com.mapbox.android.core.permissions.PermissionsListener;
import com.mapbox.android.core.permissions.PermissionsManager;
// classes needed to add a marker
import com.mapbox.mapboxsdk.annotations.Marker;
import com.mapbox.mapboxsdk.annotations.MarkerOptions;
// classes to calculate a route
import com.mapbox.services.android.navigation.ui.v5.NavigationView;
import com.mapbox.services.android.navigation.ui.v5.NavigationViewOptions;
import com.mapbox.services.android.navigation.ui.v5.route.NavigationMapRoute;
import com.mapbox.services.android.navigation.v5.instruction.Instruction;
import com.mapbox.services.android.navigation.v5.milestone.BannerInstructionMilestone;
import com.mapbox.services.android.navigation.v5.milestone.Milestone;
import com.mapbox.services.android.navigation.v5.milestone.MilestoneEventListener;
import com.mapbox.services.android.navigation.v5.milestone.RouteMilestone;
import com.mapbox.services.android.navigation.v5.milestone.Trigger;
import com.mapbox.services.android.navigation.v5.milestone.TriggerProperty;
import com.mapbox.services.android.navigation.v5.navigation.MapboxNavigation;
import com.mapbox.services.android.navigation.v5.navigation.MapboxNavigationOptions;
import com.mapbox.services.android.navigation.v5.navigation.NavigationRoute;
import com.mapbox.api.directions.v5.models.DirectionsResponse;
import com.mapbox.api.directions.v5.models.DirectionsRoute;
import com.mapbox.services.android.navigation.v5.offroute.OffRouteListener;
import com.mapbox.services.android.navigation.v5.routeprogress.RouteProgress;
import com.mapbox.services.android.navigation.v5.routeprogress.ProgressChangeListener;
import com.mapbox.services.android.navigation.v5.routeprogress.RouteProgress;
import com.mapbox.services.android.navigation.v5.navigation.NavigationEventListener;
import okhttp3.Route;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import android.util.Log;
// classes needed to launch navigation UI
import android.view.View;
import android.widget.Button;
import com.mapbox.services.android.navigation.ui.v5.NavigationLauncher;
import org.intellij.lang.annotations.Identifier;
public class MainActivity extends AppCompatActivity implements OnMapReadyCallback, MapboxMap.OnMapClickListener, OffRouteListener,PermissionsListener,MilestoneEventListener, ProgressChangeListener,NavigationEventListener{
private MapView mapView;
// variables for adding location layer
private MapboxMap mapboxMap;
private PermissionsManager permissionsManager;
private Location originLocation;
// variables for adding a marker
private Marker destinationMarker;
private LatLng originCoord;
private LatLng destinationCoord;
// variables for calculating and drawing a route
private Point originPosition;
private Point destinationPosition;
private DirectionsRoute currentRoute;
private static final String TAG = "DirectionsActivity";
private NavigationMapRoute navigationMapRoute;
private Button button;
private MapboxNavigation navigation;
private NavigationView navigationView;
private CoordinatorLayout coordinatorLayout;
private boolean running;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Mapbox.getInstance(this,"pk.eyJ1IjoicHJpeWFuZ2EiLCJhIjoiY2pwYzQ1OGxpMGgybTNscGhsbjA0cXlvcSJ9.MJD97KhqBQifpKRrPGtomg");
//MapboxNavigationOptions options = MapboxNavigationOptions.builder().isDebugLoggingEnabled(true).build();
//MapboxNavigationOptions opt=MapboxNavigationOptions.builder().build()
navigation=new MapboxNavigation(MainActivity.this,"pk.eyJ1IjoicHJpeWFuZ2EiLCJhIjoiY2pwYzQ1OGxpMGgybTNscGhsbjA0cXlvcSJ9.MJD97KhqBQifpKRrPGtomg");
//navigation.addOffRouteListener(offRouteListener);
//navigation.addMilestoneEventListener(this);
navigation.addMilestone(new BannerInstructionMilestone.Builder().setIdentifier(1).setTrigger(Trigger.all(Trigger.eq(TriggerProperty.LAST_STEP, TriggerProperty.TRUE))).setInstruction(new Instruction() {
#Override
public String buildInstruction(RouteProgress routeProgress) {
return "I AM HERE";
}
}).build());
setContentView(R.layout.activity_main);
mapView = findViewById(R.id.mapView);
//navigationView=findViewById(R.id.navigationView);
//navigationView.onCreate(savedInstanceState);
//navigationView.initialize(this);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
}
#Override
public void onMilestoneEvent(RouteProgress routeProgress, String instruction, Milestone milestone) {
//exampleInstructionPlayer.play(instruction);
Log.e("milestone","reached");
Toast.makeText(getApplicationContext(),"Milestone triggered",Toast.LENGTH_SHORT).show();
}
#Override
public void onMapReady(MapboxMap mapboxMap) {
this.mapboxMap = mapboxMap;
enableLocationComponent();
originCoord = new LatLng(originLocation.getLatitude(), originLocation.getLongitude());
mapboxMap.addOnMapClickListener(this);
button = findViewById(R.id.startButton);
/*navigation.addOffRouteListener(new OffRouteListener() {
#Override
public void userOffRoute(Location location) {
Snackbar snackbar = Snackbar
.make(coordinatorLayout, "User rerouting", Snackbar.LENGTH_LONG);
snackbar.show();
Toast.makeText(getApplicationContext(), "Off route", Toast.LENGTH_SHORT).show();
//File path = getApplicationContext().getFilesDir();
//File path=getApplicationContext().getExternalFilesDir(null);
try {
File path=getApplicationContext().getFilesDir();
Toast.makeText(getApplicationContext(),String.valueOf(path),Toast.LENGTH_SHORT).show();
File file = new File(path, "off_route.txt");
FileOutputStream stream = new FileOutputStream(file);
stream.write(("Offroute"+location.toString()).getBytes());
stream.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
});*/
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//NavigationViewOptions navopt=NavigationViewOptions.builder().directionsRoute(currentRoute).shouldSimulateRoute(false).build();
boolean simulateRoute = false;
NavigationLauncherOptions options = NavigationLauncherOptions.builder()
.directionsRoute(currentRoute)
.shouldSimulateRoute(simulateRoute)
.build();
// Call this method with Context from within an Activity
NavigationLauncher.startNavigation(MainActivity.this, options);
//navigation.startNavigation(currentRoute);
//navigation.startNavigation(currentRoute);
//navigationView.startNavigation(navopt);
}
});
}
#Override
public void onProgressChange(Location location, RouteProgress routeProgress)
{
}
#Override
public void onMapClick(#NonNull LatLng point){
if (destinationMarker != null) {
mapboxMap.removeMarker(destinationMarker);
}
destinationCoord = point;
destinationMarker = mapboxMap.addMarker(new MarkerOptions()
.position(destinationCoord)
);
destinationPosition = Point.fromLngLat(destinationCoord.getLongitude(), destinationCoord.getLatitude());
originPosition = Point.fromLngLat(originCoord.getLongitude(), originCoord.getLatitude());
getRoute(originPosition, destinationPosition);
button.setEnabled(true);
button.setBackgroundResource(R.color.mapboxBlue);
/*try {
//File path=getApplicationContext().getFilesDir();
File path=getApplicationContext().getExternalFilesDir(null);
Toast.makeText(getApplicationContext(),String.valueOf(path.getAbsolutePath()),Toast.LENGTH_SHORT).show();
//File path = getApplicationContext().getExternalFilesDir(null);
File file = new File(path, "off_route.txt");
//Log.e("Writing to file","file");
FileOutputStream stream = new FileOutputStream(file);
stream.write("Offroute am there".getBytes());
Toast.makeText(getApplicationContext(),"I ma here",Toast.LENGTH_LONG).show();
stream.close();
}
catch (Exception e)
{
Toast.makeText(getApplicationContext(),e.toString(),Toast.LENGTH_LONG).show();
e.printStackTrace();
}*/
}
#Override
public void userOffRoute(Location location) {
//Snackbar snackbar = Snackbar
// .make(coordinatorLayout, "User rerouting", Snackbar.LENGTH_LONG);
//snackbar.show();
Toast.makeText(getApplicationContext(), "Off route detected.........", Toast.LENGTH_SHORT).show();
//File path = getApplicationContext().getFilesDir();
//File path=getApplicationContext().getExternalFilesDir(null);
try {
File path=getApplicationContext().getExternalFilesDir(null);
Toast.makeText(getApplicationContext(),String.valueOf(path),Toast.LENGTH_SHORT).show();
File file = new File(path, "useroff.txt");
FileOutputStream stream = new FileOutputStream(file);
stream.write(("Offroute"+location.toString()).getBytes());
stream.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
#Override
public void onRunning(boolean running)
{
this.running=running;
if(running)
{
//navigation.addOffRouteListener(this);
//navigation.addProgressChangeListener(this);
}
}
private void getRoute(Point origin, Point destination) {
NavigationRoute.builder(this)
.accessToken(Mapbox.getAccessToken())
.origin(origin)
.destination(destination)
.build()
.getRoute(new Callback<DirectionsResponse>() {
#Override
public void onResponse(Call<DirectionsResponse> call, Response<DirectionsResponse> response) {
// You can get the generic HTTP info about the response
Log.d(TAG, "Response code: " + response.code());
if (response.body() == null) {
Log.e(TAG, "No routes found, make sure you set the right user and access token.");
return;
} else if (response.body().routes().size() < 1) {
Log.e(TAG, "No routes found");
return;
}
currentRoute = response.body().routes().get(0);
// Draw the route on the map
if (navigationMapRoute != null) {
navigationMapRoute.removeRoute();
} else {
navigationMapRoute = new NavigationMapRoute(navigation, mapView, mapboxMap, R.style.NavigationMapRoute);
}
navigationMapRoute.addRoute(currentRoute);
}
#Override
public void onFailure(Call<DirectionsResponse> call, Throwable throwable) {
Log.e(TAG, "Error: " + throwable.getMessage());
}
});
}
#SuppressWarnings( {"MissingPermission"})
private void enableLocationComponent() {
// Check if permissions are enabled and if not request
if (PermissionsManager.areLocationPermissionsGranted(this)) {
// Activate the MapboxMap LocationComponent to show user location
// Adding in LocationComponentOptions is also an optional parameter
LocationComponent locationComponent = mapboxMap.getLocationComponent();
locationComponent.activateLocationComponent(this);
locationComponent.setLocationComponentEnabled(true);
// Set the component's camera mode
locationComponent.setCameraMode(CameraMode.TRACKING);
originLocation = locationComponent.getLastKnownLocation();
} else {
permissionsManager = new PermissionsManager(this);
permissionsManager.requestLocationPermissions(this);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
permissionsManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
#Override
public void onExplanationNeeded(List<String> permissionsToExplain) {
Toast.makeText(this, R.string.user_location_permission_explanation, Toast.LENGTH_LONG).show();
}
#Override
public void onPermissionResult(boolean granted) {
if (granted) {
enableLocationComponent();
} else {
Toast.makeText(this, R.string.user_location_permission_not_granted, Toast.LENGTH_LONG).show();
finish();
}
}
#Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
#Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
#Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
#Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
#Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
}
I expect the function useroffroute overridden by me gets triggered.But no trigger happens as in am not able to see the toast message and file creation when the user goes offroute.
So the first thing to address here is that this will definitely not work with NavigationLauncher. That object is really meant to be a full-featured solution to get nav up and running quickly with minimal customization. So it is not quite as flexible and doesn't allow you to modify your offRoute listeners. This is only possible with NavigationView.
It's easy to miss, but the documentation for how to override the default reroute behavior is actually outlined in the Map Matching docs: https://docs.mapbox.com/android/navigation/overview/map-matching/#map-matching-with-mapboxnavigation
With that in mind, it looks like you're missing one crucial step in your code. When you add an offRouteListener to you navigation object, you need to carry through and override the userOffRoute function. Which would end up looking like this:
navigation.addOffRouteListener(new OffRouteListener() {
#Override
public void userOffRoute(Location location) {
Toast.makeText(getApplicationContext(), "Off route detected.........", Toast.LENGTH_SHORT).show();
// Make sure you call for a new DirectionsRoute object
// and end by calling MapboxNavigation#startNavigation on a successful
}
});

Android Remote Service does not work on Real device

Remote Service
I'm doing a test for Android remote Service.
In the first app module, I make a service, complete as below:
AppService
package com.hqyj.dev.aidltest;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
public class AppService extends Service {
public AppService() {
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
return new IAppServiceRemoteBinder.Stub() {
#Override
public void basicTypes(
int anInt, long aLong,
boolean aBoolean, float aFloat,
double aDouble, String aString)
throws RemoteException {
}
#Override
public void setData(String data)
throws RemoteException {
setRealData(data);
}
#Override
public void registerCallback(IRemoteServiceCallback cb)
throws RemoteException {
AppService.this.callback = cb;
}
#Override
public void unregisterCallback(IRemoteServiceCallback cb)
throws RemoteException {
AppService.this.callback = null;
}
};
}
private IRemoteServiceCallback callback;
#Override
public void onCreate() {
super.onCreate();
System.out.println("Service started");
}
#Override
public void onDestroy() {
super.onDestroy();
System.out.println("Service stop");
}
public void setRealData(String data) {
this.data = data;
System.out.println("data = " + data);
try {
Thread.sleep(1000);
if (callback != null) {
callback.vlueChanged(data);
}
} catch (InterruptedException | RemoteException e) {
e.printStackTrace();
}
}
private String data = "default date";
}
And their are two AIDL files:
IAppServiceRemoteBinder.aild
// IAppServiceRemoteBinder.aidl
package com.hqyj.dev.aidltest;
// Declare any non-default types here with import statements
import com.hqyj.dev.aidltest.IRemoteServiceCallback;
interface IAppServiceRemoteBinder {
/**
* Demonstrates some basic types that you can use as parameters
* and return values in AIDL.
*/
void basicTypes(int anInt,
long aLong,
boolean aBoolean, float aFloat,
double aDouble, String aString);
void setData(String data);
void registerCallback(IRemoteServiceCallback cb);
void unregisterCallback(IRemoteServiceCallback cb);
}
IRemoteServiceCallback.aild
// IRemoteServiceCallback.aidl
package com.hqyj.dev.aidltest;
// Declare any non-default types here with import statements
interface IRemoteServiceCallback {
/**
* return from server
*/
void vlueChanged(String value);
}
And in AndroidManifest.xml, this Server decleared as below:
AndroidManifest.xml
<service
android:name="com.hqyj.dev.aidltest.AppService"
android:enabled="true"
android:exported="true"
android:process=":remote">
</service>
And then, the in second module, copies all these aidl files with package name, as below:
And in MainActivity in anotherapp, complete as below:
package com.hqyj.dev.anotherapp;
import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import com.hqyj.dev.aidltest.IAppServiceRemoteBinder;
import com.hqyj.dev.aidltest.IRemoteServiceCallback;
public class MainActivity extends AppCompatActivity
implements View.OnClickListener, ServiceConnection {
private final String TAG = MainActivity.class.getSimpleName();
private Intent intent;
private IAppServiceRemoteBinder binder;
private int count = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.btn_start).setOnClickListener(this);
findViewById(R.id.btn_stop).setOnClickListener(this);
findViewById(R.id.btn_set).setOnClickListener(this);
intent = new Intent();
intent.setComponent(new
ComponentName("com.hqyj.dev.aidltest",
"com.hqyj.dev.aidltest.AppService"));
}
#SuppressLint("DefaultLocale")
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_start:
bindService(intent, this,
Context.BIND_AUTO_CREATE);
break;
case R.id.btn_set:
if (binder != null) {
try {
binder.setData(
String.format("the %d times",
++count));
} catch (RemoteException e) {
e.printStackTrace();
}
}
break;
case R.id.btn_stop:
try {
binder.unregisterCallback(callback);
} catch (RemoteException e) {
e.printStackTrace();
}
unbindService(this);
break;
}
}
#Override
public void onServiceConnected(
ComponentName name, IBinder service) {
binder =
IAppServiceRemoteBinder.Stub.asInterface(service);
Log.d(TAG, "onServiceConnected: " + 1);
try {
binder.registerCallback(callback);
} catch (RemoteException e) {
e.printStackTrace();
}
}
#Override
public void onServiceDisconnected(ComponentName name) {
}
private IRemoteServiceCallback.Stub callback =
new IRemoteServiceCallback.Stub() {
#Override
public void
vlueChanged(String value) throws RemoteException {
Log.e(TAG, "vlueChanged: " + value);
}
};
}
As you see, I called the remote service by using bindService();
It works well, when I push these two apps into an emulator which using Android 7.0 as platform.
But
When I push these app into an real device(using Android 6.0), the flowing mistake happened:
AIDL failed!!
Why??

Memory leak in service android

I am implementing the bound service for the socket.io implementation in android for single socket maintenance to connect with nodejs server by this Gottox library. When I implementing this the memory of the service is not stable like while on starting of the service it takes around 30MB to 40MB, after some time it also leads to 200MB. So I thought it may be memory leak. But i don't get any single clue to find it.
Codes
DemoActivity.java
import org.json.JSONException;
import org.json.JSONObject;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import com.actionbarsherlock.app.SherlockActivity;
import com.devspark.appmsg.AppMsg;
import com.devspark.appmsg.AppMsg.Style;
import com.nuappz.Demo.DemoService.MyLocalBinder;
import com.nuappz.Demo.handler.ResponseHandler;
import com.nuappz.Demo.helper.MySharedPreferences;
public class DemoActivity extends SherlockActivity {
MySharedPreferences pref;
DemoService socketService;
boolean isBound;
EditText name, mobile_no, email, password;
Button Demo;
Style style_alert, style_success;
JSONObject json_Demo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_Demo);
isBound = false;
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
// start the bind service
if (!isBound) {
bindService(new Intent(DemoActivity.this,
DemoService.class), myConnection,
Context.BIND_AUTO_CREATE);
isBound = true;
startService(new Intent(this, DemoService.class));
socketService = DemoService.getInstance();
}
}
public ServiceConnection myConnection = new ServiceConnection() {
#Override
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
isBound = false;
}
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
// TODO Auto-generated method stub
socketService = ((MyLocalBinder) service).getService();
isBound = true;
}
};
protected void onDestroy() {
if (isBound) {
// Disconnect from an application service. You will no longer
// receive calls as the service is restarted, and the service is
// now allowed to stop at any time.
unbindService(myConnection);
isBound = false;
}
stopService(new Intent(DemoActivity.this, DemoService.class));
super.onDestroy();
}
}
DemoService.java
import io.socket.IOAcknowledge;
import io.socket.IOCallback;
import io.socket.SocketIO;
import io.socket.SocketIOException;
import java.net.MalformedURLException;
import java.security.NoSuchAlgorithmException;
import javax.net.ssl.SSLContext;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import com.nuappz.Demo.handler.ResponseHandler;
import com.nuappz.Demo.helper.MySharedPreferences;
/*
* This class is Background service for the Blood Drop application
*/
public class DemoService extends Service {
private static final String serverUrl = "http://nuappzdev.hello.com:8080/";
private static SocketIO socket;
private static DemoService instance;
private static ResponseHandler handler;
public boolean bound;
JSONObject jobj_in = new JSONObject();
#Override
public void onCreate() {
// TODO Auto-generated method stub
Log.d("Service", "Started");
super.onCreate();
// connecting socket
try {
DemoService.initInstance();
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
public DemoService() {
}
public static DemoService getInstance() {
return instance;
}
// start the service to handle the functions
public int onStartCommand(Intent intent, int flags, int startId) {
// HandleReceiveRequest();
return START_STICKY;
}
// Stop the services
public void onDestroy() {
Log.d("Service", "Stopped");
getSocket().disconnect();
}
// Binder class initialize
public class MyLocalBinder extends Binder {
DemoService getService() {
return DemoService.this;
}
}
private final IBinder myBinder = new MyLocalBinder();
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
bound = true;
return myBinder;
}
// initiate the socket connection
public static void initInstance() throws MalformedURLException {
if (instance == null) {
instance = new DemoService();
if (DemoService.getSocket() == null) {
DemoService.setSocket(new SocketIO());
}
DemoService.connectIO();
}
}
// Method to get socket
public static SocketIO getSocket() {
return socket;
}
// Method to set socket
public static void setSocket(SocketIO socket) {
DemoService.socket = socket;
}
// Method to ConnectIO to server
public static void connectIO() throws MalformedURLException {
try {
SocketIO.setDefaultSSLSocketFactory(SSLContext.getDefault());
} catch (NoSuchAlgorithmException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
DemoService.getSocket().connect(serverUrl, new IOCallback() {
#Override
public void onMessage(JSONObject json, IOAcknowledge ack) {
// TODO Auto-generated method stub
}
#Override
public void onMessage(String data, IOAcknowledge ack) {
}
#Override
public void onError(SocketIOException socketIOException) {
Log.d("Connection:", "Error in Connection");
}
#Override
public void onDisconnect() {
// TODO Auto-generated method stub
Log.d("Connection:", "disConnected");
}
#Override
public void onConnect() {
Log.d("Connection:", "Connected");
}
#Override
// Method to getting response from server
public void on(String event, IOAcknowledge ack, Object... args) {
JSONArray jarr_args = new JSONArray();
JSONObject jobj_in = new JSONObject();
try {
jarr_args.put(args[0]);
jobj_in = jarr_args.getJSONObject(0);
jobj_in.put("event", event);
Log.d("jobject: event", jobj_in.getString("event"));
try {
handler.handleObject(jobj_in);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
}
// Method to send request to server
public static void emit(String event, Object args,
ResponseHandler responseHandler) throws MalformedURLException {
handler = responseHandler;
if (DemoService.getSocket().isConnected() == false) {
DemoService.getSocket().reconnect();
}
DemoService.getSocket().emit(event, args);
}
// Method to send request to server with Acknowledge
public static void emitWithAcknowledge(String event, Object args)
throws MalformedURLException {
if (DemoService.getSocket().isConnected() == false) {
DemoService.getSocket().reconnect();
}
DemoService.getSocket().emit(event, new IOAcknowledge() {
#Override
public void ack(Object... args) {
// TODO Auto-generated method stub
}
}, args);
}
}
}
What are the chances of memory leak in this code.
You needs to unbind service in onStop of your activity and you should never call stopService from your activity. Let Android do the handling of life cycle of your service.

Null Pointer Exception after some code moved to a custom Application class

Getting NullPointerException after I moved some of the code to a separate, custom application class called YambaApplication. This application posts to a Twitter enabled service. I checked the code 3 times, and cleaned the project 5 times:
Exception:
06-16 14:08:22.723: E/AndroidRuntime(392): Caused by:
java.lang.NullPointerException 06-16 14:08:22.723:
E/AndroidRuntime(392): at
com.user.yamba.StatusActivity$PostToTwitter.doInBackground(StatusActivity.java:70)
YambaApplication.java (here we initialize and return a twitter object):
package com.user.yamba;
import winterwell.jtwitter.Twitter;
import android.app.Application;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;
public class YambaApplication extends Application implements
OnSharedPreferenceChangeListener {
private static final String TAG = YambaApplication.class.getSimpleName();
public Twitter twitter;
private SharedPreferences prefs;
#Override
public void onCreate() {
super.onCreate();
this.prefs = PreferenceManager.getDefaultSharedPreferences(this);
this.prefs.registerOnSharedPreferenceChangeListener(this);
Log.i(TAG, "onCreated");
}
#Override
public void onTerminate() {
super.onTerminate();
Log.i(TAG, "onTerminated");
}
#Override
public synchronized void onSharedPreferenceChanged(
SharedPreferences sharedPreferences, String key) {
this.twitter = null;
}
public synchronized Twitter getTwitter() {
if (this.twitter == null) {
String username, password, apiRoot;
username = this.prefs.getString("username", "");
password = this.prefs.getString("password", "");
apiRoot = this.prefs.getString("apiRoot",
"http://yamba.marakana.com/api");
if (!TextUtils.isEmpty(username) && !TextUtils.isEmpty(password)
&& !TextUtils.isEmpty(apiRoot)) {
this.twitter = new Twitter(username, password);
this.twitter.setAPIRootUrl(apiRoot);
}
}
return this.twitter;
}
}
StatusActivity.java (the first activity user sees with an EditText and an update button. Most of the code from YambaApplication class was inside this class.):
package com.user.yamba;
import winterwell.jtwitter.Twitter;
import winterwell.jtwitter.TwitterException;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class StatusActivity extends Activity implements OnClickListener,
TextWatcher {
private static final String TAG = "StatusActivity";
EditText editTextStatusUpdate;
Button buttonStatusUpdate;
TextView textViewCharacterCounter;
//SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_status);
// Find views
editTextStatusUpdate = (EditText) findViewById(R.id.editStatus);
buttonStatusUpdate = (Button) findViewById(R.id.buttonUpdate);
buttonStatusUpdate.setOnClickListener(this);
textViewCharacterCounter = (TextView) findViewById(R.id.editTextUpdateStatusCounter);
textViewCharacterCounter.setText(Integer.toString(140));
textViewCharacterCounter.setTextColor(Color.GREEN);
editTextStatusUpdate.addTextChangedListener(this);
//prefs = PreferenceManager.getDefaultSharedPreferences(this);
//prefs.registerOnSharedPreferenceChangeListener(this);
// Initialize twitter
// twitter = new Twitter("student", "password");
// twitter.setAPIRootUrl("http://yamba.marakana.com/api");
}
#Override
public void onClick(View v) {
String statusUpdate = editTextStatusUpdate.getText().toString();
new PostToTwitter().execute(statusUpdate);
Log.d(TAG, "onClicked");
}
// Async class to post of twitter
class PostToTwitter extends AsyncTask<String, Integer, String> {
// Async post status to twitter
#Override
protected String doInBackground(String... params) {
try {
YambaApplication yamba = ((YambaApplication) getApplication());
Twitter.Status status = yamba.getTwitter().updateStatus(params[0]); // EXCEPTION FIRED HERE
return status.text;
} catch (TwitterException e) {
Log.e(TAG, "Failed to connect to twitter service");
return "Failed to post";
}
}
// Called when there's status to be updated
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
// Not used
}
// Called once async task completed
#Override
protected void onPostExecute(String result) {
Toast.makeText(StatusActivity.this, result, Toast.LENGTH_LONG)
.show();
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// Not in use
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// Not in use
}
// Update characters counter after text
// is changed(entered or deleted)
#Override
public void afterTextChanged(Editable statusText) {
int count = 140 - statusText.length();
textViewCharacterCounter.setText(Integer.toString(count));
textViewCharacterCounter.setTextColor(Color.GREEN);
if (count < 10) {
textViewCharacterCounter.setTextColor(Color.YELLOW);
}
if (count < 0) {
textViewCharacterCounter.setTextColor(Color.RED);
}
}
// When user taps on the menu hardware button inflate
// the menu resource
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
// Determine what item user tapped on the menu
// and start the item's activity
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.itemPrefs:
startActivity(new Intent(this, PrefsActivity.class));
break;
}
return true;
}
// private Twitter getTwitter() {
// if (twitter == null) {
// String username, password, apiRoot;
// username = prefs.getString("username", "");
// password = prefs.getString("password", "");
// apiRoot = prefs.getString("apiRoot",
// "http://yamba.marakana.com/api");
//
// // Connect to twitter
// twitter = new Twitter(username, password);
// twitter.setAPIRootUrl(apiRoot);
// }
// return twitter;
// }
// #Override
// public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
// String key) {
// // invalidate twitter
// twitter = null;
//
// }
}
Manifest (added this line to the application tag in the manifest):
android:name=".YambaApplication"
The first thing I saw were the new checks for the username and password to contain text.
Maybe try to debug if they both are set correctly and if a Twitter Object is returned from the Application, or simply null, because of those checks.
Null is because in YambaApplication you check:
if (!TextUtils.isEmpty(username) && !TextUtils.isEmpty(password)
&& !TextUtils.isEmpty(apiRoot)) {
...
}
If any field is empty you get twiter == null.

Linkedin Integration Android [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am building an Android application which requires LinkedIn integration.The main job of application will be Login via native app and saving of LinkedIn access token.
I went through online projects, most of them were using external libraries.
How can i get LinkedIn access token using LinkedIn android library only and using simple Java class
?
Hope this code helps you out...this consist of all functionality that one can do with linkedin api:)
package com.mypackage.linkedin;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.List;
import java.util.Set;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory.Options;
import android.net.Uri;
import android.net.http.SslError;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.preference.PreferenceManager;
import android.provider.ContactsContract.Profile;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.webkit.SslErrorHandler;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.code.linkedinapi.client.LinkedInApiClient;
import com.google.code.linkedinapi.client.LinkedInApiClientException;
import com.google.code.linkedinapi.client.LinkedInApiClientFactory;
import com.google.code.linkedinapi.client.LinkedInAuthenticationClient;
import com.google.code.linkedinapi.client.enumeration.NetworkUpdateType;
import com.google.code.linkedinapi.client.enumeration.ProfileField;
import com.google.code.linkedinapi.client.oauth.LinkedInAccessToken;
import com.google.code.linkedinapi.client.oauth.LinkedInOAuthService;
import com.google.code.linkedinapi.client.oauth.LinkedInOAuthServiceFactory;
import com.google.code.linkedinapi.client.oauth.LinkedInRequestToken;
import com.google.code.linkedinapi.schema.Connections;
import com.google.code.linkedinapi.schema.Network;
import com.google.code.linkedinapi.schema.NetworkStats;
import com.google.code.linkedinapi.schema.Person;
import com.google.code.linkedinapi.schema.Updates;
import com.mypackage.R;
import com.mypackage.account.Account;
import com.mypackage.account.AccountManagerClass;
import com.mypackage.fragment.SyncContactsFragment;
import com.mypackage.imageloader.ImageLoader;
import com.mypackage.user.User;
import com.mypackage.utils.PreferncesManagerClass;
import com.mypackage.utils.Utility;
import com.mypackage.widgets.CustomPopUpSocialMedia;
import com.mypackage.widgets.CustomToast;
/**
* #author harshalb
*This is main class of linkedin.
*/
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
public class LinkedinWebviewDialog {
private Context mContext;
private WebView mWebView;
private final String TAG = "LinkedinWebviewDialog";
private static final EnumSet<ProfileField> ProfileParameters = EnumSet.allOf(ProfileField.class);
private final LinkedInOAuthService oAuthService =
LinkedInOAuthServiceFactory.getInstance().createLinkedInOAuthService(Config.LINKEDIN_KEY, Config.LINKED_SECRET);
private final LinkedInApiClientFactory factory =
LinkedInApiClientFactory.newInstance(Config.LINKEDIN_KEY, Config.LINKED_SECRET);
public LinkedInRequestToken linkedinToken;
public LinkedInApiClient linkedinClient;
private String callFrom="";
public final static String SYNC_FRIENDS="SYNC_FRIENDS",SHARE_STATUS="SHARE_STATUS";
private String statusText="";
/**
* #param context
* #param callFrom
*/
public LinkedinWebviewDialog(Context context, String callFrom) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
this.mContext=context;
this.callFrom=callFrom;
operations();
}
/**
* #param context
* #param callFrom
* #param shareStatus
*/
public LinkedinWebviewDialog(Context context, String callFrom, String shareStatus) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
this.mContext=context;
this.callFrom=callFrom;
this.statusText=shareStatus;
operations();
}
/**
* This method is used for using share preference.
*/
protected void operations() {
final SharedPreferences pref = mContext.getSharedPreferences(Config.OAUTH_PREF, Context.MODE_PRIVATE);
final String token = pref.getString(Config.PREF_TOKEN, null);
final String tokenSecret = pref.getString(Config.PREF_TOKENSECRET, null);
fetchInfo(token, tokenSecret);
}
/**
* This method is used for access token and webview dialog show.
*/
void authenticationStart() {
if(Utility.isConnected(mContext)==true)
{
final LinkedInRequestToken liToken = oAuthService.getOAuthRequestToken(Config.OAUTH_CALLBACK_URL);
final String url = liToken.getAuthorizationUrl();
mContext.getSharedPreferences(Config.OAUTH_PREF, Context.MODE_PRIVATE)
.edit()
.putString(Config.PREF_REQTOKENSECRET, liToken.getTokenSecret())
.commit();
WebviewDialog webviewDialog=new WebviewDialog(mContext,url);
webviewDialog.show();
}
else
{
CustomToast.makeText(mContext,"No Internet Connection",CustomToast.LENGTH_SHORT).show();
}
}
/**
* #param token
* #param tokenSecret
* This method is used for verification of tokens.
*/
private void fetchInfo(String token, String tokenSecret) {
if (token == null || tokenSecret == null) {
authenticationStart();
} else {
new AsyncGetCurrentUserInfo().execute(new LinkedInAccessToken(token, tokenSecret));
}
}
/**
* #param uri
* This method is used for access token and asyn task execution.
*/
void authenticationFinish(final Uri uri) {
if (uri != null && uri.getScheme().equals(Config.OAUTH_CALLBACK_SCHEME)) {
final String problem = uri.getQueryParameter(Config.OAUTH_QUERY_PROBLEM);
if (problem == null) {
final SharedPreferences pref = mContext.getSharedPreferences(Config.OAUTH_PREF, Context.MODE_PRIVATE);
final LinkedInAccessToken accessToken = oAuthService
.getOAuthAccessToken(
new LinkedInRequestToken(
uri.getQueryParameter(Config.OAUTH_QUERY_TOKEN),
pref.getString(Config.PREF_REQTOKENSECRET, null)),
uri.getQueryParameter(Config.OAUTH_QUERY_VERIFIER));
pref.edit()
.putString(Config.PREF_TOKEN, accessToken.getToken())
.putString(Config.PREF_TOKENSECRET, accessToken.getTokenSecret())
.remove(Config.PREF_REQTOKENSECRET).commit();
new AsyncGetCurrentUserInfo().execute(accessToken);
} else {
}
}else{
//error
}
}
/**
* #author harshalb
*
*This is asyntask for linkedin.
*/
class AsyncGetCurrentUserInfo extends AsyncTask<LinkedInAccessToken, Integer, Person> {
ProgressDialog dialog;
private LinkedInAccessToken accessToken;
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(mContext);
dialog.setMessage("Please wait...");
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.show();
}
#Override
protected Person doInBackground(LinkedInAccessToken... arg0) {
try{
accessToken=arg0[0];
linkedinClient = factory.createLinkedInApiClient(accessToken);
// networkUpdatesApiClient = factory.createNetworkUpdatesApiClient(accessToken);
// networkUpdatesApiClient.setAccessToken(accessToken);
linkedinClient.setAccessToken(accessToken);
return linkedinClient.getProfileForCurrentUser(ProfileParameters);
} catch (LinkedInApiClientException ex){
Log.e(TAG, "LinkedInApiClientException: ", ex);
return null;
}
}
#Override
protected void onPostExecute(Person person) {
if(person == null){
CustomToast.makeText(mContext,"application_down_due_to_linkedinapiclientexception", CustomToast.LENGTH_SHORT).show();
dialog.dismiss();
}else{
System.out.println("person info :");
System.out.println("person name"+person.getFirstName() +" "+person.getLastName());
// mCurrentPerson = person;
// populateAll(person);
/*SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(mContext);
Editor editor = sharedPreferences.edit();
editor.putString("sync_linkedin_data","Your account synced with: "+person.getFirstName()+" "+person.getLastName());
editor.commit();*/
PreferncesManagerClass preferncesManagerClass=new PreferncesManagerClass(mContext);
preferncesManagerClass.addLinkedInData("Your account synced with: "+person.getFirstName()+" "+person.getLastName());
System.out.println("hello name:"+person.getFirstName());
if(callFrom.equalsIgnoreCase(SHARE_STATUS)){
new AsyncTask<String, String, String>() {
ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog=new ProgressDialog(mContext);
}
#Override
protected String doInBackground(String... params) {
try {
Person person = linkedinClient.getProfileForCurrentUser(EnumSet
.of(ProfileField.FIRST_NAME,
ProfileField.LAST_NAME,
ProfileField.PICTURE_URL));
// String fullName=person.getFirstName()+" "+person.getLastName();
String urlMyappsco="www.myappsco.com";
AccountManagerClass accountManagerClass=new AccountManagerClass();
Account account=accountManagerClass.getAccountInfo(mContext);
linkedinClient.updateCurrentStatus(urlMyappsco+" "+account.rank+"(Id #"+accountManagerClass.getAboId(mContext)+")"+" "+mContext.getResources().getString(R.string.abo_url)+account.userName);
// linkedinClient.updateCurrentStatus("Promoter (Id #"+accountManagerClass.getAboId(mContext)+")"+" "+accountManagerClass.getAccountInfo(mContext).aboDescription);
// linkedinClient.updateCurrentStatus("This is Myappsco website1:"+"www.myappsco.com");
// linkedinClient.postNetworkUpdate("This is Myappsco website2:"+"www.myappsco.com");
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
System.out.println("throttle::"+e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(String result) {
CustomToast.makeText(mContext,"Posted successfully", CustomToast.LENGTH_SHORT).show();
super.onPostExecute(result);
}
}.execute("");
}else if (callFrom.equalsIgnoreCase(SYNC_FRIENDS)) {
LinkedInFriends friends=new LinkedInFriends(mContext,accessToken);
friends.show();
}
dialog.dismiss();
}
}
}
/**
* List of listener.
*/
private List<OnVerifyListener> listeners = new ArrayList<OnVerifyListener>();
/**
* Register a callback to be invoked when authentication have finished.
*
* #param data
* The callback that will run
*/
public void setVerifierListener(OnVerifyListener data) {
listeners.add(data);
}
/**
*
*/
public void doOprations() {
if(callFrom.equalsIgnoreCase(SYNC_FRIENDS)){
setVerifierListener(new OnVerifyListener() {
#Override
public void onVerify(String verifier) {
try {
Log.i("LinkedinSample", "verifier: " + verifier);
LinkedInAccessToken accessToken = oAuthService.getOAuthAccessToken(linkedinToken,
verifier);
linkedinClient = factory.createLinkedInApiClient(accessToken);
LinkedInFriends linkedInFriends=new LinkedInFriends(mContext,accessToken);
linkedInFriends.show();
}catch (Exception e) {
// TODO: handle exception
}
}
});
}else if(callFrom.equalsIgnoreCase(SHARE_STATUS)){
setVerifierListener(new OnVerifyListener() {
#Override
public void onVerify(String verifier) {
try {
Log.i("LinkedinSample", "verifier: " + verifier);
LinkedInAccessToken accessToken = oAuthService.getOAuthAccessToken(linkedinToken,
verifier);
linkedinClient = factory.createLinkedInApiClient(accessToken);
// linkedinClient.updateCurrentStatus(status);
// currentStatus.setText("");
linkedinClient.postNetworkUpdate(statusText);
Person profile = linkedinClient.getProfileForCurrentUser(EnumSet
.of(ProfileField.FIRST_NAME,
ProfileField.LAST_NAME,
ProfileField.PICTURE_URL));
Log.e("Name:",
"" + profile.getFirstName() + " "
+ profile.getLastName());
Log.e("Headline:", "" + profile.getHeadline());
Log.e("Summary:", "" + profile.getSummary());
Log.e("Industry:", "" + profile.getIndustry());
Log.e("Picture url:", "" + profile.getPictureUrl());
String stringUrl = profile.getPictureUrl().toString();
System.out.println("url test" + stringUrl);
Connections connections =linkedinClient.getConnectionsForCurrentUser();
List<String> list = new ArrayList<String>();
for(Person p :connections.getPersonList()) {
Log.e("Name", "" + p.getLastName() + " " +p.getFirstName());
Log.e("Industry ", "" + p.getIndustry());
Log.e(" ", "" + "*****************");
Log.e("currentStatus ",""+p.getCurrentStatus());
Log.e("link ",""+p.getPublicProfileUrl());
Log.e("position ",""+p.getEducations());
Log.e("id","" +p.getId());
list.add(p.getId());
}
System.out.println("list::"+list);
} catch (Exception e) {
e.printStackTrace();
}
}
});
// LinkedinWebviewDialog.this.dismiss();
}
}
/**
* Listener for oauth_verifier.
*/
public interface OnVerifyListener {
/**
* invoked when authentication have finished.
*
* #param verifier
* oauth_verifier code.
*/
public void onVerify(String verifier);
}
/**
* #author harshalb
*This class is used for firends and message.
*/
public class LinkedInFriends extends Dialog{
//Activity activity;
LayoutInflater inflater;
ListView listViewFriends;
List<Person> arraylistFriends;
Connections connections;
ImageLoader imageLoader;
LinkedInFriendsAdapter linkedInFriendsAdapter;
private Context context;
public LinkedInFriends(Context context, LinkedInAccessToken arg0) {
super(context);
this.context=context;
linkedinClient = factory.createLinkedInApiClient(arg0);
linkedinClient.setAccessToken(arg0);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
// activity=getOwnerActivity();
setContentView(R.layout.friends_dialog_main);
listViewFriends=(ListView)findViewById(R.id.listview_friends);
arraylistFriends=new ArrayList<Person>();
connections = linkedinClient.getConnectionsForCurrentUser();
arraylistFriends=connections.getPersonList();
setAdapter();
}
public void setAdapter() {
linkedInFriendsAdapter=new LinkedInFriendsAdapter(arraylistFriends);
listViewFriends.setAdapter(linkedInFriendsAdapter);
listViewFriends.setOnItemClickListener(linkedInFriendsAdapter);
}
/**
* #author harshalb
*This class is adapter class used for friends.
*/
public class LinkedInFriendsAdapter extends BaseAdapter implements OnItemClickListener{
List<Person> arrayList;
public LinkedInFriendsAdapter(List<Person> arraylistFriends) {
// TODO Auto-generated constructor stub
arrayList=arraylistFriends;
inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return arrayList.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return arrayList.get(arg0);
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
/**
* #author harshalb
*This is holder class.
*/
class ViewHolder
{
ImageView friendImage;
TextView friendText;
Button friendSendMessage;
}
/**
* #author harshalb
*This class is used for sending message from dialog list.
*/
class SendMessageOnClick implements android.view.View.OnClickListener{
int position;
SendMessageOnClick(int position){
this.position=position;
}
#Override
public void onClick(View v) {
dismiss();
System.out.println("send message click..."+position);
Person p=(Person) v.getTag();
String idValue =p.getId();
System.out.println("id array list" +Arrays.asList(idValue));
final CustomPopUpSocialMedia customPopUpSocialMedia = new CustomPopUpSocialMedia(context,"Message");
customPopUpSocialMedia.setEditText();
customPopUpSocialMedia.setSocialMediaTitle("Visit MyAppsCo");
customPopUpSocialMedia.setSocialMediaMessage("Message");
customPopUpSocialMedia.setSocialMediaUsername(p.getFirstName()+" "+p.getLastName());
String storeUrl=mContext.getResources().getString(R.string.abo_url);
AccountManagerClass accountManagerClass=new AccountManagerClass();
final Account account=accountManagerClass.getAccountInfo(mContext);
customPopUpSocialMedia.setSocialMediaUrl("Visit my MyAppsCo App Store at"+" "+storeUrl+account.userName);
customPopUpSocialMedia.setFirstButton("OK");
customPopUpSocialMedia.mFirstButton.setTag(p);
customPopUpSocialMedia.setFirstButtonOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String shareStatus=customPopUpSocialMedia.getEditText();
System.out.println("shareStatus ok"+shareStatus);
System.out.println("DoneOnClick... ok"+position);
Person p=(Person) v.getTag();
String idValue =p.getId();
System.out.println("DoneOnClick...id array list" +Arrays.asList(idValue));
// linkedinClient.sendMessage(Collections.addAll(arrayList, person.getId()), "HARSHAL BENAKE DEMO", "my app demo HELLO");
try
{
String linkAppStore=mContext.getResources().getString(R.string.abo_url);
linkedinClient.sendMessage(Arrays.asList(idValue),"Visit MyAppsCo-Abo",p.getFirstName()+" "+p.getLastName()+System.getProperty("line.separator")+shareStatus+System.getProperty("line.separator")+"Visit my MyAppsCo App Store at"+" "+linkAppStore+account.userName);
//linkedinClient.sendMessage(Arrays.asList(idValue),"Visit MyAppsCo-Abo",account.fullName+System.getProperty("line.separator")+visitAppStore+" "+linkAppStore+accountManagerClass.getAboId(mContext)+".html"+" "+System.getProperty("line.separator")+"Visit at"+" "+urlMyappsco+" "+"site");
CustomToast.makeText(mContext,"Sent message successfully", CustomToast.LENGTH_SHORT).show();
}
catch (Exception e) {
// TODO: handle exception
System.out.println("throttle::"+e);
CustomToast.makeText(mContext,"Throttle limit for calls to this resource is reached", CustomToast.LENGTH_SHORT).show();
}
customPopUpSocialMedia.dismiss();
}
});
customPopUpSocialMedia.show();
}
}
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
// TODO Auto-generated method stub
Person person = arrayList.get(position);
//arrayList = arrayList.get(position);
ViewHolder viewHolder;
if(view==null){
view=inflater.inflate(R.layout.friends_list, null);
viewHolder=new ViewHolder();
viewHolder.friendImage=(ImageView)view.findViewById(R.id.friend_image);
viewHolder.friendText=(TextView)view.findViewById(R.id.friend_text);
viewHolder.friendSendMessage=(Button)view.findViewById(R.id.friend_sendmessage);
viewHolder.friendSendMessage.setOnClickListener(new SendMessageOnClick(position));
view.setTag(viewHolder);
}
else{
viewHolder=(ViewHolder)view.getTag();
}
viewHolder.friendText.setText(person.getFirstName());
imageLoader=new ImageLoader(context,person.getPictureUrl());
imageLoader.displayImage(person.getPictureUrl(), viewHolder.friendImage, false);
viewHolder.friendSendMessage.setTag(person);
// imageLoader.bind(viewHolder.friendImage, person.getPictureUrl(), callback);
return view;
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
arrayList.get(arg2);
}
}
}
/**
* #author harshalb
*This class is main webview dialog.
*/
class WebviewDialog extends Dialog {
private Context mContext;
private String mUrl;
/**
* #param context
* #param url
*/
public WebviewDialog(Context context, String url) {
super(context);
this.mContext=context;
this.mUrl=url;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);// must call before super.
super.onCreate(savedInstanceState);
setContentView(R.layout.linkedin_webview);
setWebView(mUrl);
}
/**
* set webview.
* #param url
*/
#SuppressLint({ "SetJavaScriptEnabled", "NewApi" })
public void setWebView(String url) {
mWebView = (WebView) findViewById(R.id.linkedin_webview);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setAppCacheEnabled(true);
mWebView.getSettings().setBuiltInZoomControls(true);
mWebView.loadUrl(url);
mWebView.setWebViewClient(new LinkedInWebViewClient());
}
/**
* #author harshalb
*This class is webview client.
*/
class LinkedInWebViewClient extends WebViewClient {
ProgressDialog dialog;
LinkedInWebViewClient(){
dialog=new ProgressDialog(mContext);
dialog.setMessage("Please wait...");
dialog.setCancelable(false);
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
dialog.show();
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if(dialog!=null && dialog.isShowing())
dialog.dismiss();
System.out.println("onPageFinished URL :"+url);
authenticationFinish(Uri.parse(url));
// doOprations();
}
#Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
if(dialog!=null && dialog.isShowing())
dialog.dismiss();
System.out.println("onReceivedError errorCode :"+errorCode +" description : "+description);
System.out.println("onReceivedError failingUrl :"+failingUrl);
super.onReceivedError(view, errorCode, description, failingUrl);
}
#Override
public void onReceivedSslError(WebView view, SslErrorHandler handler,
SslError error) {
if(dialog!=null && dialog.isShowing())
dialog.dismiss();
System.out.println("onReceivedSslError error :"+error.getPrimaryError());
super.onReceivedSslError(view, handler, error);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.contains(Config.OAUTH_CALLBACK_URL)) {
Uri uri = Uri.parse(url);
String verifier = uri.getQueryParameter("oauth_verifier");
for (OnVerifyListener d : listeners) {
// call listener method
d.onVerify(verifier);
}
cancel();
} else if (url
.contains("www.mypackage.com")) {
cancel();
} else {
Log.i("LinkedinSample", "url: " + url);
view.loadUrl(url);
}
return true;
}
}
}
}

Categories

Resources