Related
I'm using sample demo of
https://github.com/aosp-mirror/platform_development/tree/master/samples/SipDemo
the programing is ok, it doesn´t show issues, but when I configure this, it shows message Registration failed.
I´m programing with android studio, and the server is asterisk.
I tried with soiper and and it works.
public class WalkieTalkieActivity extends Activity implements View.OnTouchListener {
public String sipAddress = null;
public SipManager manager = null;
public SipProfile me = null;
public SipAudioCall call = null;
public IncomingCallReceiver callReceiver;
private static final int CALL_ADDRESS = 1;
private static final int SET_AUTH_INFO = 2;
private static final int UPDATE_SETTINGS_DIALOG = 3;
private static final int HANG_UP = 4;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_walkie_talkie);
ToggleButton pushToTalkButton = (ToggleButton) findViewById(R.id.pushToTalk);
pushToTalkButton.setOnTouchListener(this);
// Set up the intent filter. This will be used to fire an
// IncomingCallReceiver when someone calls the SIP address used by this
// application.
IntentFilter filter = new IntentFilter();
filter.addAction("android.SipDemo.INCOMING_CALL");
callReceiver = new IncomingCallReceiver();
this.registerReceiver(callReceiver, filter);
// "Push to talk" can be a serious pain when the screen keeps turning off.
// Let's prevent that.
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
initializeManager();
}
#Override
public void onStart() {
super.onStart();
// When we get back from the preference setting Activity, assume
// settings have changed, and re-login with new auth info.
initializeManager();
}
#Override
public void onDestroy() {
super.onDestroy();
if (call != null) {
call.close();
}
closeLocalProfile();
if (callReceiver != null) {
this.unregisterReceiver(callReceiver);
}
}
public void initializeManager() {
if(manager == null) {
manager = SipManager.newInstance(this);
}
initializeLocalProfile();
}
/**
* Logs you into your SIP provider, registering this device as the location to
* send SIP calls to for your SIP address.
*/
public void initializeLocalProfile() {
if (manager == null) {
return;
}
if (me != null) {
closeLocalProfile();
}
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
/* String username = prefs.getString("namePref", "");
String domain = prefs.getString("domainPref", "");
String password = prefs.getString("passPref", ""); */
String username = "12";
String domain = "192.168.1.37";
String password = "1234";
if (username.length() == 0 || domain.length() == 0 || password.length() == 0) {
showDialog(UPDATE_SETTINGS_DIALOG);
return;
}
try {
SipProfile.Builder builder = new SipProfile.Builder(username, domain);
builder.setAuthUserName("12");
builder.setDisplayName("12");
builder.setProfileName("12");
builder.setPassword(password);
me = builder.build();
Intent i = new Intent();
i.setAction("android.SipDemo.INCOMING_CALL");
PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, Intent.FILL_IN_DATA);
manager.open(me, pi, null);
// This listener must be added AFTER manager.open is called,
// Otherwise the methods aren't guaranteed to fire.
manager.setRegistrationListener(me.getUriString(), new SipRegistrationListener() {
public void onRegistering(String localProfileUri) {
updateStatus("Registering with SIP Server...");
}
public void onRegistrationDone(String localProfileUri, long expiryTime) {
updateStatus("Ready");
}
public void onRegistrationFailed(String localProfileUri, int errorCode,
String errorMessage) {
updateStatus("Registration failed. Please check settings.");
}
});
} catch (ParseException pe) {
updateStatus("Connection Error.");
} catch (SipException se) {
updateStatus("Connection error.");
}
}
/**
* Closes out your local profile, freeing associated objects into memory
* and unregistering your device from the server.
*/
public void closeLocalProfile() {
if (manager == null) {
return;
}
try {
if (me != null) {
manager.close(me.getUriString());
}
} catch (Exception ee) {
// Log.d("WalkieTalkieActivity/onDestroy", "Failed to close local profile.", ee);
}
}
/**
* Make an outgoing call.
*/
public void initiateCall() {
updateStatus(sipAddress);
try {
SipAudioCall.Listener listener = new SipAudioCall.Listener() {
// Much of the client's interaction with the SIP Stack will
// happen via listeners. Even making an outgoing call, don't
// forget to set up a listener to set things up once the call is established.
#Override
public void onCallEstablished(SipAudioCall call) {
call.startAudio();
call.setSpeakerMode(true);
call.toggleMute();
updateStatus(call);
}
#Override
public void onCallEnded(SipAudioCall call) {
updateStatus("Ready.");
}
};
call = manager.makeAudioCall(me.getUriString(), sipAddress, listener, 30);
}
catch (Exception e) {
// Log.i("WalkieTalkieActivity/InitiateCall", "Error when trying to close manager.", e);
if (me != null) {
try {
manager.close(me.getUriString());
} catch (Exception ee) {
// Log.i("WalkieTalkieActivity/InitiateCall",
// "Error when trying to close manager.", ee);
ee.printStackTrace();
}
}
if (call != null) {
call.close();
}
}
}
/**
* Updates the status box at the top of the UI with a messege of your choice.
* #param status The String to display in the status box.
*/
public void updateStatus(final String status) {
// Be a good citizen. Make sure UI changes fire on the UI thread.
this.runOnUiThread(new Runnable() {
public void run() {
TextView labelView = (TextView) findViewById(R.id.sipLabel);
labelView.setText(status);
}
});
}
/**
* Updates the status box with the SIP address of the current call.
* #param call The current, active call.
*/
public void updateStatus(SipAudioCall call) {
String useName = call.getPeerProfile().getDisplayName();
if(useName == null) {
useName = call.getPeerProfile().getUserName();
}
updateStatus(useName + "#" + call.getPeerProfile().getSipDomain());
}
/**
* Updates whether or not the user's voice is muted, depending on whether the button is pressed.
* #param v The View where the touch event is being fired.
* #param event The motion to act on.
* #return boolean Returns false to indicate that the parent view should handle the touch event
* as it normally would.
*/
public boolean onTouch(View v, MotionEvent event) {
if (call == null) {
return false;
} else if (event.getAction() == MotionEvent.ACTION_DOWN && call != null && call.isMuted()) {
call.toggleMute();
} else if (event.getAction() == MotionEvent.ACTION_UP && !call.isMuted()) {
call.toggleMute();
}
return false;
}
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, CALL_ADDRESS, 0, "Call someone");
menu.add(0, SET_AUTH_INFO, 0, "Edit your SIP Info.");
menu.add(0, HANG_UP, 0, "End Current Call.");
return true;
}
}
Think that should be user#domain ...and an IP address is not a domain.
I'm trying to create a location and set latitude and longitude, but when I write
location.setLatitude
I'm getting
cannot resolve symbol
error. Anyone can help?
Location location = new Location("");
location.setLatitude(0.0d);
If I change code like this:
Location location = new Location("")
.setLatitude(0.0d)
I'm getting error
Incopatible types. ;
Required: android.location.Location ;
Found: void
Edit: Here's the class. It's literally code from Google tutorial. I deleted some unnecessary parts, and added few i needed.
public class MapsActivity extends AppCompatActivity
implements OnMapReadyCallback {
private static final String TAG = MapsActivity.class.getSimpleName();
private GoogleMap mMap;
private CameraPosition mCameraPosition;
// The entry points to the Places API.
private GeoDataClient mGeoDataClient;
private PlaceDetectionClient mPlaceDetectionClient;
// The entry point to the Fused Location Provider.
private FusedLocationProviderClient mFusedLocationProviderClient;
// A default location (Sydney, Australia) and default zoom to use when location permission is
// not granted.
private final LatLng mDefaultLocation = new LatLng(49.656639, 19.636917);
private static final int DEFAULT_ZOOM = 15;
private static final int PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 1;
private boolean mLocationPermissionGranted;
// The geographical location where the device is currently located. That is, the last-known
// location retrieved by the Fused Location Provider.
private Location mLastKnownLocation;
// Keys for storing activity state.
private static final String KEY_CAMERA_POSITION = "camera_position";
private static final String KEY_LOCATION = "location";
// Used for selecting the current place.
private static final int M_MAX_ENTRIES = 5;
private String[] mLikelyPlaceNames;
private String[] mLikelyPlaceAddresses;
private String[] mLikelyPlaceAttributions;
private LatLng[] mLikelyPlaceLatLngs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Retrieve location and camera position from saved instance state.
if (savedInstanceState != null) {
mLastKnownLocation = savedInstanceState.getParcelable(KEY_LOCATION);
mCameraPosition = savedInstanceState.getParcelable(KEY_CAMERA_POSITION);
}
// Retrieve the content view that renders the map.
setContentView(R.layout.activity_maps);
// Construct a GeoDataClient.
mGeoDataClient = Places.getGeoDataClient(this, null);
// Construct a PlaceDetectionClient.
mPlaceDetectionClient = Places.getPlaceDetectionClient(this, null);
// Construct a FusedLocationProviderClient.
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
// Build the map.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
/**
* Saves the state of the map when the activity is paused.
*/
#Override
protected void onSaveInstanceState(Bundle outState) {
if (mMap != null) {
outState.putParcelable(KEY_CAMERA_POSITION, mMap.getCameraPosition());
outState.putParcelable(KEY_LOCATION, mLastKnownLocation);
super.onSaveInstanceState(outState);
}
}
LatLng centPoint = new LatLng(49.656639, 19.636917);
int kolStrefa = Color.argb(40, 255, 0, 0);
Location location = new Location("");
location.setLatitude(0.0d); //Cannot resolve symbol
#Override
public void onMapReady(GoogleMap map) {
mMap = map;
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
// Use a custom info window adapter to handle multiple lines of text in the
// info window contents.
// Prompt the user for permission.
getLocationPermission();
// Turn on the My Location layer and the related control on the map.
updateLocationUI();
// Get the current location of the device and set the position of the map.
getDeviceLocation();
CircleOptions strefa = new CircleOptions()
.center(centPoint)
.radius(200)
.strokeColor(Color.RED)
.fillColor(kolStrefa);
Circle circle = mMap.addCircle(strefa);
}
double distance = mLastKnownLocation.distanceTo(krzCent);
/**
* Gets the current location of the device, and positions the map's camera.
*/
private void getDeviceLocation() {
/*
* Get the best and most recent location of the device, which may be null in rare
* cases when a location is not available.
*/
try {
if (mLocationPermissionGranted) {
Task<Location> locationResult = mFusedLocationProviderClient.getLastLocation();
locationResult.addOnCompleteListener(this, new OnCompleteListener<Location>() {
#Override
public void onComplete(#NonNull Task<Location> task) {
if (task.isSuccessful()) {
// Set the map's camera position to the current location of the device.
mLastKnownLocation = task.getResult();
} else {
Log.d(TAG, "Current location is null. Using defaults.");
Log.e(TAG, "Exception: %s", task.getException());
mMap.moveCamera(CameraUpdateFactory
.newLatLngZoom(mDefaultLocation, DEFAULT_ZOOM));
mMap.getUiSettings().setMyLocationButtonEnabled(false);
}
}
});
}
} catch (SecurityException e) {
Log.e("Exception: %s", e.getMessage());
}
}
/**
* Prompts the user for permission to use the device location.
*/
private void getLocationPermission() {
/*
* Request location permission, so that we can get the location of the
* device. The result of the permission request is handled by a callback,
* onRequestPermissionsResult.
*/
if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mLocationPermissionGranted = true;
} else {
ActivityCompat.requestPermissions(this,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
}
}
/**
* Handles the result of the request for location permissions.
*/
#Override
public void onRequestPermissionsResult(int requestCode,
#NonNull String permissions[],
#NonNull int[] grantResults) {
mLocationPermissionGranted = false;
switch (requestCode) {
case PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
mLocationPermissionGranted = true;
}
}
}
updateLocationUI();
}
/**
* Prompts the user to select the current place from a list of likely places, and shows the
* current place on the map - provided the user has granted location permission.
*/
private void showCurrentPlace() {
if (mMap == null) {
return;
}
if (mLocationPermissionGranted) {
// Get the likely places - that is, the businesses and other points of interest that
// are the best match for the device's current location.
#SuppressWarnings("MissingPermission") final
Task<PlaceLikelihoodBufferResponse> placeResult =
mPlaceDetectionClient.getCurrentPlace(null);
placeResult.addOnCompleteListener
(new OnCompleteListener<PlaceLikelihoodBufferResponse>() {
#Override
public void onComplete(#NonNull Task<PlaceLikelihoodBufferResponse> task) {
if (task.isSuccessful() && task.getResult() != null) {
PlaceLikelihoodBufferResponse likelyPlaces = task.getResult();
// Set the count, handling cases where less than 5 entries are returned.
int count;
if (likelyPlaces.getCount() < M_MAX_ENTRIES) {
count = likelyPlaces.getCount();
} else {
count = M_MAX_ENTRIES;
}
int i = 0;
mLikelyPlaceNames = new String[count];
mLikelyPlaceAddresses = new String[count];
mLikelyPlaceAttributions = new String[count];
mLikelyPlaceLatLngs = new LatLng[count];
for (PlaceLikelihood placeLikelihood : likelyPlaces) {
// Build a list of likely places to show the user.
mLikelyPlaceNames[i] = (String) placeLikelihood.getPlace().getName();
mLikelyPlaceAddresses[i] = (String) placeLikelihood.getPlace()
.getAddress();
mLikelyPlaceAttributions[i] = (String) placeLikelihood.getPlace()
.getAttributions();
mLikelyPlaceLatLngs[i] = placeLikelihood.getPlace().getLatLng();
i++;
if (i > (count - 1)) {
break;
}
}
// Release the place likelihood buffer, to avoid memory leaks.
likelyPlaces.release();
// Show a dialog offering the user the list of likely places, and add a
// marker at the selected place.
openPlacesDialog();
} else {
Log.e(TAG, "Exception: %s", task.getException());
}
}
});
} else {
// The user has not granted permission.
Log.i(TAG, "The user did not grant location permission.");
// Add a default marker, because the user hasn't selected a place.
mMap.addMarker(new MarkerOptions()
.title("DEF")
.position(mDefaultLocation)
.snippet("DEFfd"));
// Prompt the user for permission.
getLocationPermission();
}
}
/**
* Displays a form allowing the user to select a place from a list of likely places.
*/
private void openPlacesDialog() {
// Ask the user to choose the place where they are now.
DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// The "which" argument contains the position of the selected item.
LatLng markerLatLng = mLikelyPlaceLatLngs[which];
String markerSnippet = mLikelyPlaceAddresses[which];
if (mLikelyPlaceAttributions[which] != null) {
markerSnippet = markerSnippet + "\n" + mLikelyPlaceAttributions[which];
}
// Add a marker for the selected place, with an info window
// showing information about that place.
mMap.addMarker(new MarkerOptions()
.title(mLikelyPlaceNames[which])
.position(markerLatLng)
.snippet(markerSnippet));
// Position the map's camera at the location of the marker.
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(markerLatLng,
DEFAULT_ZOOM));
}
};
// Display the dialog.
}
/**
* Updates the map's UI settings based on whether the user has granted location permission.
*/
private void updateLocationUI() {
if (mMap == null) {
return;
}
try {
if (mLocationPermissionGranted) {
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(true);
} else {
mMap.setMyLocationEnabled(false);
mMap.getUiSettings().setMyLocationButtonEnabled(false);
mLastKnownLocation = null;
getLocationPermission();
}
} catch (SecurityException e) {
Log.e("Exception: %s", e.getMessage());
}
}
}
First, you should try to create a completely new class and create this Location there to see if the error lies within the rest of the code.
And finally,
Location location = new Location("").setLatitude(0.0d); will not work because you first create your Location and then instantly set the latitude. Java thinks that you want to assign the return value of #setLatitude to the variable (which of course is not possible since it returns void).
I clicked on the class NotificationManagerCompat and I cannot find the public methods
areNotificationsEnabled()
getImportance()
They are also both the only methods that return variables. I need to use the method areNotificationsEnabled() does anyone have any ideas how this could be possible?
Currently my import line is as follows
import android.support.v4.app.NotificationManagerCompat;
Not sure if it helps for me to post the entire class but here it is
/*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.support.v4.app;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.DeadObjectException;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.provider.Settings;
import android.util.Log;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Compatibility library for NotificationManager with fallbacks for older platforms.
*
* <p>To use this class, call the static function {#link #from} to get a
* {#link NotificationManagerCompat} object, and then call one of its
* methods to post or cancel notifications.
*/
public class NotificationManagerCompat {
private static final String TAG = "NotifManCompat";
/**
* Notification extras key: if set to true, the posted notification should use
* the side channel for delivery instead of using notification manager.
*/
public static final String EXTRA_USE_SIDE_CHANNEL =
NotificationCompatJellybean.EXTRA_USE_SIDE_CHANNEL;
/**
* Intent action to register for on a service to receive side channel
* notifications. The listening service must be in the same package as an enabled
* {#link android.service.notification.NotificationListenerService}.
*/
public static final String ACTION_BIND_SIDE_CHANNEL =
"android.support.BIND_NOTIFICATION_SIDE_CHANNEL";
/**
* Maximum sdk build version which needs support for side channeled notifications.
* Currently the only needed use is for side channeling group children before KITKAT_WATCH.
*/
static final int MAX_SIDE_CHANNEL_SDK_VERSION = 19;
/** Base time delay for a side channel listener queue retry. */
private static final int SIDE_CHANNEL_RETRY_BASE_INTERVAL_MS = 1000;
/** Maximum retries for a side channel listener before dropping tasks. */
private static final int SIDE_CHANNEL_RETRY_MAX_COUNT = 6;
/** Hidden field Settings.Secure.ENABLED_NOTIFICATION_LISTENERS */
private static final String SETTING_ENABLED_NOTIFICATION_LISTENERS =
"enabled_notification_listeners";
private static final int SIDE_CHANNEL_BIND_FLAGS;
/** Cache of enabled notification listener components */
private static final Object sEnabledNotificationListenersLock = new Object();
/** Guarded by {#link #sEnabledNotificationListenersLock} */
private static String sEnabledNotificationListeners;
/** Guarded by {#link #sEnabledNotificationListenersLock} */
private static Set<String> sEnabledNotificationListenerPackages = new HashSet<String>();
private final Context mContext;
private final NotificationManager mNotificationManager;
/** Lock for mutable static fields */
private static final Object sLock = new Object();
/** Guarded by {#link #sLock} */
private static SideChannelManager sSideChannelManager;
/** Get a {#link NotificationManagerCompat} instance for a provided context. */
public static NotificationManagerCompat from(Context context) {
return new NotificationManagerCompat(context);
}
private NotificationManagerCompat(Context context) {
mContext = context;
mNotificationManager = (NotificationManager) mContext.getSystemService(
Context.NOTIFICATION_SERVICE);
}
private static final Impl IMPL;
interface Impl {
void cancelNotification(NotificationManager notificationManager, String tag, int id);
void postNotification(NotificationManager notificationManager, String tag, int id,
Notification notification);
int getSideChannelBindFlags();
}
static class ImplBase implements Impl {
#Override
public void cancelNotification(NotificationManager notificationManager, String tag,
int id) {
notificationManager.cancel(id);
}
#Override
public void postNotification(NotificationManager notificationManager, String tag, int id,
Notification notification) {
notificationManager.notify(id, notification);
}
#Override
public int getSideChannelBindFlags() {
return Service.BIND_AUTO_CREATE;
}
}
static class ImplEclair extends ImplBase {
#Override
public void cancelNotification(NotificationManager notificationManager, String tag,
int id) {
NotificationManagerCompatEclair.cancelNotification(notificationManager, tag, id);
}
#Override
public void postNotification(NotificationManager notificationManager, String tag, int id,
Notification notification) {
NotificationManagerCompatEclair.postNotification(notificationManager, tag, id,
notification);
}
}
static class ImplIceCreamSandwich extends ImplEclair {
#Override
public int getSideChannelBindFlags() {
return NotificationManagerCompatIceCreamSandwich.SIDE_CHANNEL_BIND_FLAGS;
}
}
static {
if (Build.VERSION.SDK_INT >= 14) {
IMPL = new ImplIceCreamSandwich();
} else if (Build.VERSION.SDK_INT >= 5) {
IMPL = new ImplEclair();
} else {
IMPL = new ImplBase();
}
SIDE_CHANNEL_BIND_FLAGS = IMPL.getSideChannelBindFlags();
}
/**
* Cancel a previously shown notification.
* #param id the ID of the notification
*/
public void cancel(int id) {
cancel(null, id);
}
/**
* Cancel a previously shown notification.
* #param tag the string identifier of the notification.
* #param id the ID of the notification
*/
public void cancel(String tag, int id) {
IMPL.cancelNotification(mNotificationManager, tag, id);
if (Build.VERSION.SDK_INT <= MAX_SIDE_CHANNEL_SDK_VERSION) {
pushSideChannelQueue(new CancelTask(mContext.getPackageName(), id, tag));
}
}
/** Cancel all previously shown notifications. */
public void cancelAll() {
mNotificationManager.cancelAll();
if (Build.VERSION.SDK_INT <= MAX_SIDE_CHANNEL_SDK_VERSION) {
pushSideChannelQueue(new CancelTask(mContext.getPackageName()));
}
}
/**
* Post a notification to be shown in the status bar, stream, etc.
* #param id the ID of the notification
* #param notification the notification to post to the system
*/
public void notify(int id, Notification notification) {
notify(null, id, notification);
}
/**
* Post a notification to be shown in the status bar, stream, etc.
* #param tag the string identifier for a notification. Can be {#code null}.
* #param id the ID of the notification. The pair (tag, id) must be unique within your app.
* #param notification the notification to post to the system
*/
public void notify(String tag, int id, Notification notification) {
if (useSideChannelForNotification(notification)) {
pushSideChannelQueue(new NotifyTask(mContext.getPackageName(), id, tag, notification));
// Cancel this notification in notification manager if it just transitioned to being
// side channelled.
IMPL.cancelNotification(mNotificationManager, tag, id);
} else {
IMPL.postNotification(mNotificationManager, tag, id, notification);
}
}
/**
* Get the set of packages that have an enabled notification listener component within them.
*/
public static Set<String> getEnabledListenerPackages(Context context) {
final String enabledNotificationListeners = Settings.Secure.getString(
context.getContentResolver(),
SETTING_ENABLED_NOTIFICATION_LISTENERS);
// Parse the string again if it is different from the last time this method was called.
if (enabledNotificationListeners != null
&& !enabledNotificationListeners.equals(sEnabledNotificationListeners)) {
final String[] components = enabledNotificationListeners.split(":");
Set<String> packageNames = new HashSet<String>(components.length);
for (String component : components) {
ComponentName componentName = ComponentName.unflattenFromString(component);
if (componentName != null) {
packageNames.add(componentName.getPackageName());
}
}
synchronized (sEnabledNotificationListenersLock) {
sEnabledNotificationListenerPackages = packageNames;
sEnabledNotificationListeners = enabledNotificationListeners;
}
}
return sEnabledNotificationListenerPackages;
}
/**
* Returns true if this notification should use the side channel for delivery.
*/
private static boolean useSideChannelForNotification(Notification notification) {
Bundle extras = NotificationCompat.getExtras(notification);
return extras != null && extras.getBoolean(EXTRA_USE_SIDE_CHANNEL);
}
/**
* Push a notification task for distribution to notification side channels.
*/
private void pushSideChannelQueue(Task task) {
synchronized (sLock) {
if (sSideChannelManager == null) {
sSideChannelManager = new SideChannelManager(mContext.getApplicationContext());
}
}
sSideChannelManager.queueTask(task);
}
/**
* Helper class to manage a queue of pending tasks to send to notification side channel
* listeners.
*/
private static class SideChannelManager implements Handler.Callback, ServiceConnection {
private static final int MSG_QUEUE_TASK = 0;
private static final int MSG_SERVICE_CONNECTED = 1;
private static final int MSG_SERVICE_DISCONNECTED = 2;
private static final int MSG_RETRY_LISTENER_QUEUE = 3;
private static final String KEY_BINDER = "binder";
private final Context mContext;
private final HandlerThread mHandlerThread;
private final Handler mHandler;
private final Map<ComponentName, ListenerRecord> mRecordMap =
new HashMap<ComponentName, ListenerRecord>();
private Set<String> mCachedEnabledPackages = new HashSet<String>();
public SideChannelManager(Context context) {
mContext = context;
mHandlerThread = new HandlerThread("NotificationManagerCompat");
mHandlerThread.start();
mHandler = new Handler(mHandlerThread.getLooper(), this);
}
/**
* Queue a new task to be sent to all listeners. This function can be called
* from any thread.
*/
public void queueTask(Task task) {
mHandler.obtainMessage(MSG_QUEUE_TASK, task).sendToTarget();
}
#Override
public boolean handleMessage(Message msg) {
switch (msg.what) {
case MSG_QUEUE_TASK:
handleQueueTask((Task) msg.obj);
return true;
case MSG_SERVICE_CONNECTED:
ServiceConnectedEvent event = (ServiceConnectedEvent) msg.obj;
handleServiceConnected(event.componentName, event.iBinder);
return true;
case MSG_SERVICE_DISCONNECTED:
handleServiceDisconnected((ComponentName) msg.obj);
return true;
case MSG_RETRY_LISTENER_QUEUE:
handleRetryListenerQueue((ComponentName) msg.obj);
return true;
}
return false;
}
private void handleQueueTask(Task task) {
updateListenerMap();
for (ListenerRecord record : mRecordMap.values()) {
record.taskQueue.add(task);
processListenerQueue(record);
}
}
private void handleServiceConnected(ComponentName componentName, IBinder iBinder) {
ListenerRecord record = mRecordMap.get(componentName);
if (record != null) {
record.service = INotificationSideChannel.Stub.asInterface(iBinder);
record.retryCount = 0;
processListenerQueue(record);
}
}
private void handleServiceDisconnected(ComponentName componentName) {
ListenerRecord record = mRecordMap.get(componentName);
if (record != null) {
ensureServiceUnbound(record);
}
}
private void handleRetryListenerQueue(ComponentName componentName) {
ListenerRecord record = mRecordMap.get(componentName);
if (record != null) {
processListenerQueue(record);
}
}
#Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "Connected to service " + componentName);
}
mHandler.obtainMessage(MSG_SERVICE_CONNECTED,
new ServiceConnectedEvent(componentName, iBinder))
.sendToTarget();
}
#Override
public void onServiceDisconnected(ComponentName componentName) {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "Disconnected from service " + componentName);
}
mHandler.obtainMessage(MSG_SERVICE_DISCONNECTED, componentName).sendToTarget();
}
/**
* Check the current list of enabled listener packages and update the records map
* accordingly.
*/
private void updateListenerMap() {
Set<String> enabledPackages = getEnabledListenerPackages(mContext);
if (enabledPackages.equals(mCachedEnabledPackages)) {
// Short-circuit when the list of enabled packages has not changed.
return;
}
mCachedEnabledPackages = enabledPackages;
List<ResolveInfo> resolveInfos = mContext.getPackageManager().queryIntentServices(
new Intent().setAction(ACTION_BIND_SIDE_CHANNEL), PackageManager.GET_SERVICES);
Set<ComponentName> enabledComponents = new HashSet<ComponentName>();
for (ResolveInfo resolveInfo : resolveInfos) {
if (!enabledPackages.contains(resolveInfo.serviceInfo.packageName)) {
continue;
}
ComponentName componentName = new ComponentName(
resolveInfo.serviceInfo.packageName, resolveInfo.serviceInfo.name);
if (resolveInfo.serviceInfo.permission != null) {
Log.w(TAG, "Permission present on component " + componentName
+ ", not adding listener record.");
continue;
}
enabledComponents.add(componentName);
}
// Ensure all enabled components have a record in the listener map.
for (ComponentName componentName : enabledComponents) {
if (!mRecordMap.containsKey(componentName)) {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "Adding listener record for " + componentName);
}
mRecordMap.put(componentName, new ListenerRecord(componentName));
}
}
// Remove listener records that are no longer for enabled components.
Iterator<Map.Entry<ComponentName, ListenerRecord>> it =
mRecordMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<ComponentName, ListenerRecord> entry = it.next();
if (!enabledComponents.contains(entry.getKey())) {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "Removing listener record for " + entry.getKey());
}
ensureServiceUnbound(entry.getValue());
it.remove();
}
}
}
/**
* Ensure we are already attempting to bind to a service, or start a new binding if not.
* #return Whether the service bind attempt was successful.
*/
private boolean ensureServiceBound(ListenerRecord record) {
if (record.bound) {
return true;
}
Intent intent = new Intent(ACTION_BIND_SIDE_CHANNEL).setComponent(record.componentName);
record.bound = mContext.bindService(intent, this, SIDE_CHANNEL_BIND_FLAGS);
if (record.bound) {
record.retryCount = 0;
} else {
Log.w(TAG, "Unable to bind to listener " + record.componentName);
mContext.unbindService(this);
}
return record.bound;
}
/**
* Ensure we have unbound from a service.
*/
private void ensureServiceUnbound(ListenerRecord record) {
if (record.bound) {
mContext.unbindService(this);
record.bound = false;
}
record.service = null;
}
/**
* Schedule a delayed retry to communicate with a listener service.
* After a maximum number of attempts (with exponential back-off), start
* dropping pending tasks for this listener.
*/
private void scheduleListenerRetry(ListenerRecord record) {
if (mHandler.hasMessages(MSG_RETRY_LISTENER_QUEUE, record.componentName)) {
return;
}
record.retryCount++;
if (record.retryCount > SIDE_CHANNEL_RETRY_MAX_COUNT) {
Log.w(TAG, "Giving up on delivering " + record.taskQueue.size() + " tasks to "
+ record.componentName + " after " + record.retryCount + " retries");
record.taskQueue.clear();
return;
}
int delayMs = SIDE_CHANNEL_RETRY_BASE_INTERVAL_MS * (1 << (record.retryCount - 1));
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "Scheduling retry for " + delayMs + " ms");
}
Message msg = mHandler.obtainMessage(MSG_RETRY_LISTENER_QUEUE, record.componentName);
mHandler.sendMessageDelayed(msg, delayMs);
}
/**
* Perform a processing step for a listener. First check the bind state, then attempt
* to flush the task queue, and if an error is encountered, schedule a retry.
*/
private void processListenerQueue(ListenerRecord record) {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "Processing component " + record.componentName + ", "
+ record.taskQueue.size() + " queued tasks");
}
if (record.taskQueue.isEmpty()) {
return;
}
if (!ensureServiceBound(record) || record.service == null) {
// Ensure bind has started and that a service interface is ready to use.
scheduleListenerRetry(record);
return;
}
// Attempt to flush all items in the task queue.
while (true) {
Task task = record.taskQueue.peek();
if (task == null) {
break;
}
try {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "Sending task " + task);
}
task.send(record.service);
record.taskQueue.remove();
} catch (DeadObjectException e) {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "Remote service has died: " + record.componentName);
}
break;
} catch (RemoteException e) {
Log.w(TAG, "RemoteException communicating with " + record.componentName, e);
break;
}
}
if (!record.taskQueue.isEmpty()) {
// Some tasks were not sent, meaning an error was encountered, schedule a retry.
scheduleListenerRetry(record);
}
}
/** A per-side-channel-service listener state record */
private static class ListenerRecord {
public final ComponentName componentName;
/** Whether the service is currently bound to. */
public boolean bound = false;
/** The service stub provided by onServiceConnected */
public INotificationSideChannel service;
/** Queue of pending tasks to send to this listener service */
public LinkedList<Task> taskQueue = new LinkedList<Task>();
/** Number of retries attempted while connecting to this listener service */
public int retryCount = 0;
public ListenerRecord(ComponentName componentName) {
this.componentName = componentName;
}
}
}
private static class ServiceConnectedEvent {
final ComponentName componentName;
final IBinder iBinder;
public ServiceConnectedEvent(ComponentName componentName,
final IBinder iBinder) {
this.componentName = componentName;
this.iBinder = iBinder;
}
}
private interface Task {
public void send(INotificationSideChannel service) throws RemoteException;
}
private static class NotifyTask implements Task {
final String packageName;
final int id;
final String tag;
final Notification notif;
public NotifyTask(String packageName, int id, String tag, Notification notif) {
this.packageName = packageName;
this.id = id;
this.tag = tag;
this.notif = notif;
}
#Override
public void send(INotificationSideChannel service) throws RemoteException {
service.notify(packageName, id, tag, notif);
}
public String toString() {
StringBuilder sb = new StringBuilder("NotifyTask[");
sb.append("packageName:").append(packageName);
sb.append(", id:").append(id);
sb.append(", tag:").append(tag);
sb.append("]");
return sb.toString();
}
}
private static class CancelTask implements Task {
final String packageName;
final int id;
final String tag;
final boolean all;
public CancelTask(String packageName) {
this.packageName = packageName;
this.id = 0;
this.tag = null;
this.all = true;
}
public CancelTask(String packageName, int id, String tag) {
this.packageName = packageName;
this.id = id;
this.tag = tag;
this.all = false;
}
#Override
public void send(INotificationSideChannel service) throws RemoteException {
if (all) {
service.cancelAll(packageName);
} else {
service.cancel(packageName, id, tag);
}
}
public String toString() {
StringBuilder sb = new StringBuilder("CancelTask[");
sb.append("packageName:").append(packageName);
sb.append(", id:").append(id);
sb.append(", tag:").append(tag);
sb.append(", all:").append(all);
sb.append("]");
return sb.toString();
}
}
}
I am working with Microsoft Azure Cloud Database, inserting data from Android Application.
i referred below mentioned link code,for insert and fetch data from azure using my android App. its Works fine.
Problem:
I have added two more columns in Azure database. I am not able to interact that columns using demo code.its little complicated for me.
Please help me,how to add few more columns in android code,Insert and Fetching data from cloud Database.
Link i referred
ToDoActivity.java
public class ToDoActivity extends Activity {
/**
* Mobile Service Client reference
*/
private MobileServiceClient mClient;
/**
* Mobile Service Table used to access data
*/
private MobileServiceTable<ToDoItem> mToDoTable;
//Offline Sync
/**
* Mobile Service Table used to access and Sync data
*/
//private MobileServiceSyncTable<ToDoItem> mToDoTable;
/**
* Adapter to sync the items list with the view
*/
private ToDoItemAdapter mAdapter;
/**
* EditText containing the "New To Do" text
*/
private EditText mTextNewToDo;
/**
* Progress spinner to use for table operations
*/
private ProgressBar mProgressBar;
/**
* Initializes the activity
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_to_do);
mProgressBar = (ProgressBar) findViewById(R.id.loadingProgressBar);
// Initialize the progress bar
mProgressBar.setVisibility(ProgressBar.GONE);
try {
// Create the Mobile Service Client instance, using the provided
// Mobile Service URL and key
mClient = new MobileServiceClient(
"https://newapk.azure-mobile.net/",
"****************************",
this).withFilter(new ProgressFilter());
// Get the Mobile Service Table instance to use
mToDoTable = mClient.getTable(ToDoItem.class);
// Offline Sync
//mToDoTable = mClient.getSyncTable("ToDoItem", ToDoItem.class);
//Init local storage
initLocalStore().get();
mTextNewToDo = (EditText) findViewById(R.id.textNewToDo);
// Create an adapter to bind the items with the view
mAdapter = new ToDoItemAdapter(this, R.layout.row_list_to_do);
ListView listViewToDo = (ListView) findViewById(R.id.listViewToDo);
listViewToDo.setAdapter(mAdapter);
// Load the items from the Mobile Service
refreshItemsFromTable();
} catch (MalformedURLException e) {
createAndShowDialog(new Exception("There was an error creating the Mobile Service. Verify the URL"), "Error");
} catch (Exception e){
createAndShowDialog(e, "Error");
}
}
/**
* Initializes the activity menu
*/
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
/**
* Select an option from the menu
*/
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.menu_refresh) {
refreshItemsFromTable();
}
return true;
}
/**
* Mark an item as completed
*
* #param item
* The item to mark
*/
public void checkItem(final ToDoItem item) {
if (mClient == null) {
return;
}
// Set the item as completed and update it in the table
item.setComplete(true);
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>(){
#Override
protected Void doInBackground(Void... params) {
try {
checkItemInTable(item);
runOnUiThread(new Runnable() {
#Override
public void run() {
if (item.isComplete()) {
mAdapter.remove(item);
}
}
});
} catch (final Exception e) {
createAndShowDialogFromTask(e, "Error");
}
return null;
}
};
runAsyncTask(task);
}
/**
* Mark an item as completed in the Mobile Service Table
*
* #param item
* The item to mark
*/
public void checkItemInTable(ToDoItem item) throws ExecutionException, InterruptedException {
mToDoTable.update(item).get();
}
/**
* Add a new item
*
* #param view
* The view that originated the call
*/
public void addItem(View view) {
if (mClient == null) {
return;
}
// Create a new item
final ToDoItem item = new ToDoItem();
item.setText(mTextNewToDo.getText().toString());
item.setComplete(false);
// Insert the new item
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>(){
#Override
protected Void doInBackground(Void... params) {
try {
final ToDoItem entity = addItemInTable(item);
runOnUiThread(new Runnable() {
#Override
public void run() {
if(!entity.isComplete()){
mAdapter.add(entity);
}
}
});
} catch (final Exception e) {
createAndShowDialogFromTask(e, "Error");
}
return null;
}
};
runAsyncTask(task);
mTextNewToDo.setText("");
}
/**
* Add an item to the Mobile Service Table
*
* #param item
* The item to Add
*/
public ToDoItem addItemInTable(ToDoItem item) throws ExecutionException, InterruptedException {
ToDoItem entity = mToDoTable.insert(item).get();
return entity;
}
/**
* Refresh the list with the items in the Table
*/
private void refreshItemsFromTable() {
// Get the items that weren't marked as completed and add them in the
// adapter
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>(){
#Override
protected Void doInBackground(Void... params) {
try {
final List<ToDoItem> results = refreshItemsFromMobileServiceTable();
//Offline Sync
//final List<ToDoItem> results = refreshItemsFromMobileServiceTableSyncTable();
runOnUiThread(new Runnable() {
#Override
public void run() {
mAdapter.clear();
for (ToDoItem item : results) {
mAdapter.add(item);
}
}
});
} catch (final Exception e){
createAndShowDialogFromTask(e, "Error");
}
return null;
}
};
runAsyncTask(task);
}
/**
* Refresh the list with the items in the Mobile Service Table
*/
private List<ToDoItem> refreshItemsFromMobileServiceTable() throws ExecutionException, InterruptedException {
return mToDoTable.where().field("complete").
eq(val(false)).execute().get();
}
//Offline Sync
/**
* Refresh the list with the items in the Mobile Service Sync Table
*/
/*private List<ToDoItem> refreshItemsFromMobileServiceTableSyncTable() throws ExecutionException, InterruptedException {
//sync the data
sync().get();
Query query = QueryOperations.field("complete").
eq(val(false));
return mToDoTable.read(query).get();
}*/
/**
* Initialize local storage
* #return
* #throws MobileServiceLocalStoreException
* #throws ExecutionException
* #throws InterruptedException
*/
private AsyncTask<Void, Void, Void> initLocalStore() throws MobileServiceLocalStoreException, ExecutionException, InterruptedException {
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
try {
MobileServiceSyncContext syncContext = mClient.getSyncContext();
if (syncContext.isInitialized())
return null;
SQLiteLocalStore localStore = new SQLiteLocalStore(mClient.getContext(), "OfflineStore", null, 1);
Map<String, ColumnDataType> tableDefinition = new HashMap<String, ColumnDataType>();
tableDefinition.put("id", ColumnDataType.String);
tableDefinition.put("text", ColumnDataType.String);
tableDefinition.put("complete", ColumnDataType.Boolean);
localStore.defineTable("ToDoItem", tableDefinition);
SimpleSyncHandler handler = new SimpleSyncHandler();
syncContext.initialize(localStore, handler).get();
} catch (final Exception e) {
createAndShowDialogFromTask(e, "Error");
}
return null;
}
};
return runAsyncTask(task);
}
//Offline Sync
/**
* Sync the current context and the Mobile Service Sync Table
* #return
*/
/*
private AsyncTask<Void, Void, Void> sync() {
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>(){
#Override
protected Void doInBackground(Void... params) {
try {
MobileServiceSyncContext syncContext = mClient.getSyncContext();
syncContext.push().get();
mToDoTable.pull(null).get();
} catch (final Exception e) {
createAndShowDialogFromTask(e, "Error");
}
return null;
}
};
return runAsyncTask(task);
}
*/
/**
* Creates a dialog and shows it
*
* #param exception
* The exception to show in the dialog
* #param title
* The dialog title
*/
private void createAndShowDialogFromTask(final Exception exception, String title) {
runOnUiThread(new Runnable() {
#Override
public void run() {
createAndShowDialog(exception, "Error");
}
});
}
/**
* Creates a dialog and shows it
*
* #param exception
* The exception to show in the dialog
* #param title
* The dialog title
*/
private void createAndShowDialog(Exception exception, String title) {
Throwable ex = exception;
if(exception.getCause() != null){
ex = exception.getCause();
}
createAndShowDialog(ex.getMessage(), title);
}
/**
* Creates a dialog and shows it
*
* #param message
* The dialog message
* #param title
* The dialog title
*/
private void createAndShowDialog(final String message, final String title) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(message);
builder.setTitle(title);
builder.create().show();
}
/**
* Run an ASync task on the corresponding executor
* #param task
* #return
*/
private AsyncTask<Void, Void, Void> runAsyncTask(AsyncTask<Void, Void, Void> task) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
return task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} else {
return task.execute();
}
}
private class ProgressFilter implements ServiceFilter {
#Override
public ListenableFuture<ServiceFilterResponse> handleRequest(ServiceFilterRequest request, NextServiceFilterCallback nextServiceFilterCallback) {
final SettableFuture<ServiceFilterResponse> resultFuture = SettableFuture.create();
runOnUiThread(new Runnable() {
#Override
public void run() {
if (mProgressBar != null) mProgressBar.setVisibility(ProgressBar.VISIBLE);
}
});
ListenableFuture<ServiceFilterResponse> future = nextServiceFilterCallback.onNext(request);
Futures.addCallback(future, new FutureCallback<ServiceFilterResponse>() {
#Override
public void onFailure(Throwable e) {
resultFuture.setException(e);
}
#Override
public void onSuccess(ServiceFilterResponse response) {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (mProgressBar != null) mProgressBar.setVisibility(ProgressBar.GONE);
}
});
resultFuture.set(response);
}
});
return resultFuture;
}
}
}
ToDoItemAdapter.java
public class ToDoItemAdapter extends ArrayAdapter<ToDoItem> {
/**
* Adapter context
*/
Context mContext;
/**
* Adapter View layout
*/
int mLayoutResourceId;
public ToDoItemAdapter(Context context, int layoutResourceId) {
super(context, layoutResourceId);
mContext = context;
mLayoutResourceId = layoutResourceId;
}
/**
* Returns the view for a specific item on the list
*/
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
final ToDoItem currentItem = getItem(position);
if (row == null) {
LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
row = inflater.inflate(mLayoutResourceId, parent, false);
}
row.setTag(currentItem);
final CheckBox checkBox = (CheckBox) row.findViewById(R.id.checkToDoItem);
checkBox.setText(currentItem.getText());
checkBox.setChecked(false);
checkBox.setEnabled(true);
checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if (checkBox.isChecked()) {
checkBox.setEnabled(false);
if (mContext instanceof ToDoActivity) {
ToDoActivity activity = (ToDoActivity) mContext;
activity.checkItem(currentItem);
}
}
}
});
return row;
}
}
ToDoItem.java
public class ToDoItem {
/**
* Item text
*/
#com.google.gson.annotations.SerializedName("text")
private String mText;
/**
* Item Id
*/
#com.google.gson.annotations.SerializedName("id")
private String mId;
/**
* Indicates if the item is completed
*/
#com.google.gson.annotations.SerializedName("complete")
private boolean mComplete;
/**
* ToDoItem constructor
*/
public ToDoItem() {
}
#Override
public String toString() {
return getText();
}
/**
* Initializes a new ToDoItem
*
* #param text
* The item text
* #param id
* The item id
*/
public ToDoItem(String text, String id) {
this.setText(text);
this.setId(id);
}
/**
* Returns the item text
*/
public String getText() {
return mText;
}
/**
* Sets the item text
*
* #param text
* text to set
*/
public final void setText(String text) {
mText = text;
}
/**
* Returns the item id
*/
public String getId() {
return mId;
}
/**
* Sets the item id
*
* #param id
* id to set
*/
public final void setId(String id) {
mId = id;
}
/**
* Indicates if the item is marked as completed
*/
public boolean isComplete() {
return mComplete;
}
/**
* Marks the item as completed or incompleted
*/
public void setComplete(boolean complete) {
mComplete = complete;
}
#Override
public boolean equals(Object o) {
return o instanceof ToDoItem && ((ToDoItem) o).mId == mId;
}
}
There are a documents https://azure.microsoft.com/en-us/documentation/articles/mobile-services-android-how-to-use-client-library/ that clearly explained how to use the android clinet library to interact with Azure Database for various operations.
I think you can refer to these sample in the document to write own code to implement your needs.
Any other concern, please feel free to let me know.
You have to make changes in your ToDoItem.java
It is the class which corresponds to the table in database.
whenever you make changes to the table in azure.
In ur case, when u are adding new columns to table in azure, say newcol1 and newcol2, You have to add
#com.google.gson.annotations.SerializedName("newcol1")
private boolean newColumnOne;
to your ToDoItem.java file. Only then u could have access to new columns in ToDoActivity.java
public void addItem(View view) {
if (mClient == null) {
return;
}
// Create a new item
final ToDoItem item = new ToDoItem();
item.setText(mTextNewToDo.getText().toString());
item.setComplete(false);
item.setNewColumnOne("dataabc");
item.setNewColumnTwo("dataxyz");
// Insert the new item
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
try {
final ToDoItem entity = addItemInTable(item);
runOnUiThread(new Runnable() {
#Override
public void run() {
if (!entity.isComplete()) {
mAdapter.add(entity);
}
}
});
} catch (final Exception e) {
createAndShowDialogFromTask(e, "Error 3rd");
}
return null;
}
};
runAsyncTask(task);
mTextNewToDo.setText("");
}
just add data through setNewColumnOne(); as i did.
rest of the code should be same.
P.S. dont forget to create getter setter and constructor for TodoItem.Java
The following app upload video to Dropbox when it is start, I added finish() in the end of onCreate to exit the app when its completed the uploading, but I got "Unfortunately, DBRoulette has stopped.".
In the Eclipse LogCat:
Activity com.dropbox.android.sample.DBRoulette has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#42a7ee38 that was originally added here
android.view.WindowLeaked: Activity com.dropbox.android.sample.DBRoulette has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#42a7ee38 that was originally added here
I have Progress viewer which may cause the problem but I don't know how to solve it!
What I want to do is closing the app automatically when the uploading completed.
DBRoulette.java
#SuppressLint("SimpleDateFormat")
public class DBRoulette extends Activity {
private static final String TAG = "DBRoulette";
final static private String APP_KEY = "<My APP_KEY>";
final static private String APP_SECRET = "<My APP_SECRET>";
// You don't need to change these, leave them alone.
final static private String ACCOUNT_PREFS_NAME = "prefs";
final static private String ACCESS_KEY_NAME = "ACCESS_KEY";
final static private String ACCESS_SECRET_NAME = "ACCESS_SECRET";
private static final boolean USE_OAUTH1 = false;
DropboxAPI<AndroidAuthSession> mApi;
private boolean mLoggedIn;
// Android widgets
private Button mSubmit;
private RelativeLayout mDisplay;
private Button mGallery;
private ImageView mImage;
private final String PHOTO_DIR = "/Motion/";
#SuppressWarnings("unused")
final static private int NEW_PICTURE = 50;
private String mCameraFileName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
mCameraFileName = savedInstanceState.getString("mCameraFileName");
}
// We create a new AuthSession so that we can use the Dropbox API.
AndroidAuthSession session = buildSession();
mApi = new DropboxAPI<AndroidAuthSession>(session);
// Basic Android widgets
setContentView(R.layout.main);
checkAppKeySetup();
mSubmit = (Button) findViewById(R.id.auth_button);
mSubmit.setOnClickListener(new OnClickListener() {
#SuppressWarnings("deprecation")
public void onClick(View v) {
// This logs you out if you're logged in, or vice versa
if (mLoggedIn) {
logOut();
} else {
// Start the remote authentication
if (USE_OAUTH1) {
mApi.getSession().startAuthentication(DBRoulette.this);
} else {
mApi.getSession().startOAuth2Authentication(
DBRoulette.this);
}
}
}
});
mDisplay = (RelativeLayout) findViewById(R.id.logged_in_display);
// This is where a photo is displayed
mImage = (ImageView) findViewById(R.id.image_view);
File outFile = new File("/mnt/sdcard/ipwebcam_videos/video.mov");
mCameraFileName = outFile.toString();
UploadPicture upload = new UploadPicture(DBRoulette.this, mApi, PHOTO_DIR,outFile);
upload.execute();
// Display the proper UI state if logged in or not
setLoggedIn(mApi.getSession().isLinked());
finish();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putString("mCameraFileName", mCameraFileName);
super.onSaveInstanceState(outState);
}
#Override
protected void onResume() {
super.onResume();
AndroidAuthSession session = mApi.getSession();
if (session.authenticationSuccessful()) {
try {
session.finishAuthentication();
storeAuth(session);
setLoggedIn(true);
} catch (IllegalStateException e) {
showToast("Couldn't authenticate with Dropbox:"
+ e.getLocalizedMessage());
Log.i(TAG, "Error authenticating", e);
}
}
}
private void logOut() {
// Remove credentials from the session
mApi.getSession().unlink();
clearKeys();
// Change UI state to display logged out version
setLoggedIn(false);
}
#SuppressWarnings("deprecation")
public String getRealPathFromURI(Uri contentUri)
{
String[] proj = { MediaStore.Audio.Media.DATA };
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
private void setLoggedIn(boolean loggedIn) {
mLoggedIn = loggedIn;
if (loggedIn) {
mSubmit.setText("Logout from Dropbox");
mDisplay.setVisibility(View.VISIBLE);
} else {
mSubmit.setText("Login with Dropbox");
mDisplay.setVisibility(View.GONE);
mImage.setImageDrawable(null);
}
}
private void checkAppKeySetup() {
// Check to make sure that we have a valid app key
if (APP_KEY.startsWith("CHANGE") || APP_SECRET.startsWith("CHANGE")) {
showToast("You must apply for an app key and secret from developers.dropbox.com, and add them to the DBRoulette ap before trying it.");
finish();
return;
}
// Check if the app has set up its manifest properly.
Intent testIntent = new Intent(Intent.ACTION_VIEW);
String scheme = "db-" + APP_KEY;
String uri = scheme + "://" + AuthActivity.AUTH_VERSION + "/test";
testIntent.setData(Uri.parse(uri));
PackageManager pm = getPackageManager();
if (0 == pm.queryIntentActivities(testIntent, 0).size()) {
showToast("URL scheme in your app's "
+ "manifest is not set up correctly. You should have a "
+ "com.dropbox.client2.android.AuthActivity with the "
+ "scheme: " + scheme);
finish();
}
}
private void showToast(String msg) {
Toast error = Toast.makeText(this, msg, Toast.LENGTH_LONG);
error.show();
}
/**
* Shows keeping the access keys returned from Trusted Authenticator in a
* local store, rather than storing user name & password, and
* re-authenticating each time (which is not to be done, ever).
*/
private void loadAuth(AndroidAuthSession session) {
SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
String key = prefs.getString(ACCESS_KEY_NAME, null);
String secret = prefs.getString(ACCESS_SECRET_NAME, null);
if (key == null || secret == null || key.length() == 0
|| secret.length() == 0)
return;
if (key.equals("oauth2:")) {
// If the key is set to "oauth2:", then we can assume the token is
// for OAuth 2.
session.setOAuth2AccessToken(secret);
} else {
// Still support using old OAuth 1 tokens.
session.setAccessTokenPair(new AccessTokenPair(key, secret));
}
}
/**
* Shows keeping the access keys returned from Trusted Authenticator in a
* local store, rather than storing user name & password, and
* re-authenticating each time (which is not to be done, ever).
*/
private void storeAuth(AndroidAuthSession session) {
// Store the OAuth 2 access token, if there is one.
String oauth2AccessToken = session.getOAuth2AccessToken();
if (oauth2AccessToken != null) {
SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME,
0);
Editor edit = prefs.edit();
edit.putString(ACCESS_KEY_NAME, "oauth2:");
edit.putString(ACCESS_SECRET_NAME, oauth2AccessToken);
edit.commit();
return;
}
// Store the OAuth 1 access token, if there is one. This is only
// necessary if
// you're still using OAuth 1.
AccessTokenPair oauth1AccessToken = session.getAccessTokenPair();
if (oauth1AccessToken != null) {
SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME,
0);
Editor edit = prefs.edit();
edit.putString(ACCESS_KEY_NAME, oauth1AccessToken.key);
edit.putString(ACCESS_SECRET_NAME, oauth1AccessToken.secret);
edit.commit();
return;
}
}
private void clearKeys() {
SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
Editor edit = prefs.edit();
edit.clear();
edit.commit();
}
private AndroidAuthSession buildSession() {
AppKeyPair appKeyPair = new AppKeyPair(APP_KEY, APP_SECRET);
AndroidAuthSession session = new AndroidAuthSession(appKeyPair);
loadAuth(session);
return session;
}
}
UploadPicture.java
public class UploadPicture extends AsyncTask<Void, Long, Boolean> {
private DropboxAPI<?> mApi;
private String mPath;
private File mFile;
private long mFileLen;
private UploadRequest mRequest;
private Context mContext;
private final ProgressDialog mDialog;
private String mErrorMsg;
private File outFiles;
public UploadPicture(Context context, DropboxAPI<?> api, String dropboxPath,
File file) {
// We set the context this way so we don't accidentally leak activities
mContext = context.getApplicationContext();
mFileLen = file.length();
mApi = api;
mPath = dropboxPath;
mFile = file;
Date dates = new Date();
DateFormat dfs = new SimpleDateFormat("yyyyMMdd-kkmmss");
String newPicFiles = dfs.format(dates) + ".mov";
String outPaths = new File(Environment
.getExternalStorageDirectory(), newPicFiles).getPath();
outFiles = new File(outPaths);
mDialog = new ProgressDialog(context);
mDialog.setMax(100);
mDialog.setMessage("Uploading " + outFiles.getName());
mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mDialog.setProgress(0);
mDialog.setButton(ProgressDialog.BUTTON_POSITIVE, "Cancel", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// This will cancel the putFile operation
mRequest.abort();
}
});
mDialog.show();
}
#Override
protected Boolean doInBackground(Void... params) {
try {
// By creating a request, we get a handle to the putFile operation,
// so we can cancel it later if we want to
FileInputStream fis = new FileInputStream(mFile);
String path = mPath + outFiles.getName();
mRequest = mApi.putFileOverwriteRequest(path, fis, mFile.length(),
new ProgressListener() {
#Override
public long progressInterval() {
// Update the progress bar every half-second or so
return 500;
}
#Override
public void onProgress(long bytes, long total) {
publishProgress(bytes);
}
});
if (mRequest != null) {
mRequest.upload();
return true;
}
} catch (DropboxUnlinkedException e) {
// This session wasn't authenticated properly or user unlinked
mErrorMsg = "This app wasn't authenticated properly.";
} catch (DropboxFileSizeException e) {
// File size too big to upload via the API
mErrorMsg = "This file is too big to upload";
} catch (DropboxPartialFileException e) {
// We canceled the operation
mErrorMsg = "Upload canceled";
} catch (DropboxServerException e) {
// Server-side exception. These are examples of what could happen,
// but we don't do anything special with them here.
if (e.error == DropboxServerException._401_UNAUTHORIZED) {
// Unauthorized, so we should unlink them. You may want to
// automatically log the user out in this case.
} else if (e.error == DropboxServerException._403_FORBIDDEN) {
// Not allowed to access this
} else if (e.error == DropboxServerException._404_NOT_FOUND) {
// path not found (or if it was the thumbnail, can't be
// thumbnailed)
} else if (e.error == DropboxServerException._507_INSUFFICIENT_STORAGE) {
// user is over quota
} else {
// Something else
}
// This gets the Dropbox error, translated into the user's language
mErrorMsg = e.body.userError;
if (mErrorMsg == null) {
mErrorMsg = e.body.error;
}
} catch (DropboxIOException e) {
// Happens all the time, probably want to retry automatically.
mErrorMsg = "Network error. Try again.";
} catch (DropboxParseException e) {
// Probably due to Dropbox server restarting, should retry
mErrorMsg = "Dropbox error. Try again.";
} catch (DropboxException e) {
// Unknown error
mErrorMsg = "Unknown error. Try again.";
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return false;
}
#Override
protected void onProgressUpdate(Long... progress) {
int percent = (int)(100.0*(double)progress[0]/mFileLen + 0.5);
mDialog.setProgress(percent);
}
#Override
protected void onPostExecute(Boolean result) {
mDialog.dismiss();
if (result) {
showToast("Image successfully uploaded");
} else {
showToast(mErrorMsg);
}
}
private void showToast(String msg) {
Toast error = Toast.makeText(mContext, msg, Toast.LENGTH_LONG);
error.show();
}
}
Your problem is that you are trying to update an Activity's UI after the activity has finished.
First, you kick of an AsyncTask which posts progress updates to the UI thread. Then, before the task completes, you call finish(). Any updates to the Activity's UI after finish() is called are liable to throw exceptions, cause window leak issues, etc.
If you want to have any UI behavior as you perform your AsyncTask, you do not want to finish() the Activity until it the task is completed.
To achieve this, you could include a callback in the onPostExecute which tells the activity it is OK to finish once the AsyncTask completes.
This is how I would do it:
Change the signature of UploadPicture:
final Activity callingActivity;
public UploadPicture(final Activity callingActivity, DropboxAPI api, String dropboxPath, File file) {
Context mContext = callingActivity.getApplicationContext();
this.callingActivity = callingActivity;
Add the finish call to onPostExecute:
#Override
protected void onPostExecute(Boolean result) {
mDialog.dismiss();
if (result) {
showToast("Image successfully uploaded");
} else {
showToast(mErrorMsg);
}
callingActivity.finish(); //Finish activity only once you are done
}