Create QBPrivateChatManager getting error nullpointer in android - quickblox

create Quickblox chat but createdialog time geting nullpointer.
QBPrivateChatManager privateChatManager = QBChatService.getInstance().getPrivateChatManager();
privateChatManager.createDialog(sub_arr.get(position).getOccupentId(), new QBEntityCallbackImpl<QBDialog>() {
#Override
public void onSuccess(QBDialog dialog, Bundle args) {
Log.d("dialog1", dialog+"");
}
#Override
public void onError(List<String> errors) {
}
});

If you didn't call
QBChatService.getInstance().login(qbUser);
then next line will be returning null:
QBPrivateChatManager privateChatManager = QBChatService.getInstance().getPrivateChatManager();
So the right way is to login to chat and then obtain QBPrivateChatManager

Related

How to block popups in cefsharp browser in vb.net project/ NOT c sharp

i have been looking for a while now, i have found a solution in csharp , but i couldn't translate it (implement it in my vb.net app).
My only aim is that when the user clicks a link no popups appear.
thank you for your help.
My vb.net coding skill is beginner level, c sharp no knowledge.
the working solution in c sharp:
using CefSharp;
using CefSharp.WinForms;
namespace popup_cefsharp
{
public partial class frm_main : Form
{
public frm_main()
{
InitializeComponent();
}
//variable
ChromiumWebBrowser chrome, chrome_popup;
private void initialize_browser()
{
try
{
CefSettings settings = new CefSettings();
Cef.Initialize(settings);
//main browser
chrome = new ChromiumWebBrowser(this.txt_url.Text.Trim());
LifespanHandler life = new LifespanHandler();
chrome.LifeSpanHandler = life;
life.popup_request += life_popup_request;
this.pan_container.Controls.Add(chrome);
chrome.Dock = DockStyle.Fill;
//second browser (popup browser)
chrome_popup = new ChromiumWebBrowser("");
this.pan_container_popup.Controls.Add(chrome_popup);
chrome_popup.Dock = DockStyle.Fill;
}
catch (Exception ex)
{
MessageBox.Show("Error in initializing the browser. Error: " + ex.Message);
}
}
private void carregar_popup_new_browser(string url)
{
//open pop up in second browser
chrome_popup.Load(url);
}
private void frm_main_FormClosing(object sender, FormClosingEventArgs e)
{
//close o object cef
Cef.Shutdown();
Application.Exit();
}
private void frm_main_Load(object sender, EventArgs e)
{
//initialize the browser
this.initialize_browser();
}
private void life_popup_request(string obj)
{
//function for open pop up in a new browser
this.carregar_popup_new_browser(obj);
}
}
}
link original post: https://www.codeproject.com/Articles/1194609/Capturing-a-pop-up-window-using-LifeSpanHandler-an
finally found the solution , if anyone is interested
here is the link, you will need to install the cefsharp nuggets packages, add lifespanhandler as a new class, the file is in the link, then copy the method to call the function from the mainform...
cheers...
https://github.com/messi06/vb.net_CefSharp_popup

Accessing activity 2 while foreground is activity 1 (either using OOP or Service in XAMARIN)

i code this from a tutorial for locating your location (but I already made some changes)
using Android.App;
using Android.Widget;
using Android.OS;
using Android.Locations;
using System.Collections.Generic;
using Android.Util;
using System.Linq;
using Java.Lang;
using System.Threading.Tasks;
using System;
using Android.Views;
using Android.Content;
namespace LocatorApp
{
[Activity(Label = "Locator", MainLauncher = true, Icon = "#drawable/locator_ico")]
public class LocatorApp : Activity, ILocationListener
{
static readonly string TAG = "X:" + typeof(LocatorApp).Name;
TextView _addressText;
Location _currentLocation;
LocationManager _locationManager;
Address address;
string _locationProvider;
TextView _locationText;
private double latitude = 0;
private double longitude = 0;
public Location getCurrentLocation() { return _currentLocation; }
public double getLatitude() { return latitude; }
public double getLongitude() { return longitude; }
public Address getAddress() { return address; }
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.Main);
_addressText = FindViewById<TextView>(Resource.Id.address_text);
_locationText = FindViewById<TextView>(Resource.Id.location_text);
FindViewById<TextView>(Resource.Id.get_address_button).Click += AddressButton_OnClick;
InitializeLocationManager();
}
public void InitializeLocationManager()
{
_locationManager = (LocationManager)GetSystemService(LocationService);
Criteria criteriaForLocationService = new Criteria
{
Accuracy = Accuracy.Coarse,
PowerRequirement = Power.Medium
};
IList<string> acceptableLocationProviders = _locationManager.GetProviders(criteriaForLocationService, true);
if (acceptableLocationProviders.Any())
{
_locationProvider = acceptableLocationProviders.First();
}
else
{
_locationProvider = string.Empty;
}
Log.Debug(TAG, "Using " + _locationProvider + ".");
}
async void AddressButton_OnClick(object sender, EventArgs eventArgs)
{
if (_currentLocation == null)
{
Toast.MakeText(this, "Still waiting for location.", ToastLength.Short).Show();
}
else
{
try
{
var geoUri = Android.Net.Uri.Parse("geo:" + _currentLocation.Latitude + "," + _currentLocation.Longitude);
var mapIntent = new Intent(Intent.ActionView, geoUri);
StartActivity(mapIntent);
}
catch (System.Exception e)
{
Toast.MakeText(this, "Sorry, there is a problem with geomapping.", ToastLength.Short).Show();
}
}
}
async Task<Address> ReverseGeocodeCurrentLocation()
{
try
{
Geocoder geocoder = new Geocoder(this);
IList<Address> addressList =
await geocoder.GetFromLocationAsync(_currentLocation.Latitude, _currentLocation.Longitude, 10);
Address address = addressList.FirstOrDefault();
return address;
}
catch (System.Exception e)
{
throw;
}
return null;
}
void DisplayAddress(Address address)
{
if (address != null)
{
StringBuilder deviceAddress = new StringBuilder();
for (int i = 0; i < address.MaxAddressLineIndex; i++)
{
deviceAddress.Append(address.GetAddressLine(i));
}
// Remove the last comma from the end of the address.
_addressText.Text = "Address: "+deviceAddress.ToString();
}
else
{
_addressText.Text = "Unable to determine the address. Try again in a few minutes.";
}
}
public async void OnLocationChanged(Location location)
{
Toast.MakeText(this, "Location changed.", ToastLength.Short).Show();
_currentLocation = location;
if (_currentLocation == null)
{
_locationText.Text = "Unable to determine your location. Try again in a short while.";
}
else
{
try
{
_locationText.Text = "Location: " + string.Format("{0:f6},{1:f6}", _currentLocation.Latitude, _currentLocation.Longitude);
Address address = await ReverseGeocodeCurrentLocation();
DisplayAddress(address);
var nMgr = (NotificationManager)GetSystemService(NotificationService);
var notification = new Notification(Resource.Drawable.Icon, "Message from LocatorApp");
var pendingIntent = PendingIntent.GetActivity(this, 0, new Intent(this, typeof(LocatorApp)), 0);
notification.SetLatestEventInfo(this, "LocatorApp", "Location changed!", pendingIntent);
nMgr.Notify(0, notification);
}
catch (Java.Lang.Exception e)
{
_addressText.Text = "Unable to determine the address. Try again in a few minutes.";
Toast.MakeText(this, "Error Occured On Geocoder!", ToastLength.Short).Show();
Log.Error(TAG, e.Message);
}
}
}
public void OnProviderDisabled(string provider) { }
public void OnProviderEnabled(string provider) { }
public void OnStatusChanged(string provider, Availability status, Bundle extras) { }
protected override void OnResume()
{
base.OnResume();
if (_locationManager.IsProviderEnabled(_locationProvider))
{
_locationManager.RequestLocationUpdates(_locationProvider, 100, 0, this);
Toast.MakeText(this, _locationProvider.ToString(), ToastLength.Short).Show();
}
else
{
Toast.MakeText(this, "There is a problem with "+_locationProvider.ToString()+" provider.", ToastLength.Short).Show();
}
}
protected override void OnPause()
{
base.OnPause();
_locationManager.RemoveUpdates(this);
}
}
}
(i'm just having my experiment)
what I want is to run activity B while foreground is in activity A, just like a basic OOP . but my problem is, I don't know how to make it run. I can't also jump to activity B since it has an oncreate method. I instantiated it and can get the variables values but they are null (seems there is no process happened) . What can be a best solution for this.
note: I am currently looking how to use service for background processing but also i don't know how to run this code after I typed it from a tutorial :( there is only a tutorial for creating a service part but no tutorial for buttons to access it :(
using System;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Util;
using System.Threading;
namespace LocatorApp
{
[Service]
class SimpleService : Service
{
static readonly string TAG = "X:" + typeof(SimpleService).Name;
static readonly int TimerWait = 4000;
Timer _timer;
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
{
Log.Debug(TAG, "OnStartCommand called at {2}, flags={0}, startid={1}", flags, startId, DateTime.UtcNow);
_timer = new Timer(o => { Log.Debug(TAG, "Hello from SimpleService. {0}", DateTime.UtcNow); },
null,
0,
TimerWait);
return StartCommandResult.NotSticky;
}
public override void OnDestroy()
{
base.OnDestroy();
_timer.Dispose();
_timer = null;
Log.Debug(TAG, "SimpleService destroyed at {0}.", DateTime.UtcNow);
}
public override IBinder OnBind(Intent intent)
{
// This example isn't of a bound service, so we just return NULL.
return null;
}
}
}
I want to know both (OOP way and service way) since not at all time we are required to use the service.
what I want is to run activity B while foreground is in activity A, just like a basic OOP . but my problem is, I don't know how to make it run. I can't also jump to activity B since it has an oncreate method.
You can call Context.StartActivity inside your Activity with following codes:
StartActivity(new Android.Content.Intent(this, typeof(ActivityB)));
And StartActivity will call OnCreate method in ActivityB to create a new instance of ActivityB.
For details about Starting Activities, please refer to Starting Activities and Getting Results.
I am currently looking how to use service for background processing but also i don't know how to run this code after I typed it from a tutorial :( there is only a tutorial for creating a service part but no tutorial for buttons to access it :(
Similar like Activity Context.StartService offers a way to start a Service:
StartService (new Intent (this, typeof(DemoService)));
This will call the OnStartCommand method inside your Service class.
For details about usage of Service, please refer to Implementing a Service.

Quickblox not delivering GCM notifications immediately

QuickBlox not delivering GCM notifications to subscribed devices. I tried sending notification message from Admin Panel too, but it isn't delivered to device, but still in Admin Panel it shows it as "sent". But no history available.
And also what could be the reason for this ? How to mitigate this ?
How to view sent GCM notifications.
The admin panel is not good enough - it lies sometime by saying 'send successfully' but it never reaches the other end.
Try sending the GCM notification by using the code snippet provided in the documentation. It works always.
public void sendMessageOnClick() {
// Send Push: create QuickBlox Push Notification Event
QBEvent qbEvent = new QBEvent();
qbEvent.setNotificationType(QBNotificationType.PUSH);
qbEvent.setEnvironment(QBEnvironment.DEVELOPMENT);
// generic push - will be delivered to all platforms (Android, iOS, WP, Blackberry..)
qbEvent.setMessage("how are you doing");
StringifyArrayList<Integer> userIds = new StringifyArrayList<Integer>();
userIds.add(6132691);
qbEvent.setUserIds(userIds);
QBMessages.createEvent(qbEvent, new QBEntityCallbackImpl<QBEvent>() {
#Override
public void onSuccess(QBEvent qbEvent, Bundle bundle) {
}
#Override
public void onError(List<String> strings) {
// errors
}
});
}
//OR the below:--
private void sendPushNotifications(){
// recipients
StringifyArrayList<Integer> userIds = new StringifyArrayList<Integer>();
userIds.add(6114793);
//userIds.add(960);
QBEvent event = new QBEvent();
event.setUserIds(userIds);
event.setEnvironment(QBEnvironment.DEVELOPMENT);
event.setNotificationType(QBNotificationType.PUSH);
event.setPushType(QBPushType.GCM);
HashMap<String, String> data = new HashMap<String, String>();
data.put("data.message", "Hello");
data.put("data.type", "welcome message");
event.setMessage(data);
QBMessages.createEvent(event, new QBEntityCallbackImpl<QBEvent>() {
#Override
public void onSuccess(QBEvent qbEvent, Bundle args) {
// sent
}
#Override
public void onError(List<String> errors) {
}
});
}

Parse | Push Notification Straight Into Web View, How?

I've searched in the web, parse docs and ask many people but no one can point me how to do it.
I have an RSS app who getting the articles into a UITableView.
when I'm sending a Push it's open the app itself but not the article I want to (well obviously since I don't know how to code that) .
Can anyone please give me ideas how to do it ?
(code sample will be useful as well) .
First of all you have to implement your own Receiver class instead of default Parse push receiver and put it into AndroidManifest.xml as follows :
<receiver android:name="net.blabla.notification.PushNotifHandler" android:exported="false">
<intent-filter>
<action android:name="net.bla.PUSH_MESSAGE" />
</intent-filter>
</receiver>
In your PushNotifHandler.java class you should put some parameters to Intent you will throw as follows :
public class PushNotifHandler extends BroadcastReceiver{
private static final String TAG = PushNotifHandler.class.getSimpleName();
private static int nextNotifID = (int)(System.currentTimeMillis()/1000);
private static final long VIBRATION_DURATION = 500;
#Override
public void onReceive(Context context, Intent intent) {
try {
String action = intent.getAction();
Intent resultIntent = new Intent(context, ToBeOpenedActivity.class);
JSONObject jsonData = new JSONObject(intent.getExtras().getString("com.parse.Data"));
fillNotificationData(jsonData, action, resultIntent);
String title = jsonData.getString("messageTitle") + "";
String message = jsonData.getString("messageText") + "";
TaskStackBuilder stackBuilder = TaskStackBuilder.from(context);
stackBuilder.addParentStack(ToBeOpenedActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
Notification notification;
NotificationCompat.Builder builder = new NotificationCompat.Builder(context).
setSmallIcon(R.drawable.icon).
setContentTitle(title).
setContentText(message).
setAutoCancel(true);
builder.setContentIntent(resultPendingIntent);
notification = builder.getNotification();
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(TAG, nextNotifID++, notification);
vibratePhone(context);
} catch (Exception e) {
Log.d(TAG, "Exception: " + e.getMessage());
}
}
private void vibratePhone(Context context) {
Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(VIBRATION_DURATION);
}
private void fillNotificationData(JSONObject json, String action, Intent resultIntent)
throws JSONException {
Log.d(TAG, "ACTION : " + action);
resultIntent.putExtra("paramString", json.getString("paramFromServer"));
}
}
With key "com.parse.Data" you will get parameters sent from your server code as json format.After getting paramString and paramBoolean parameters from this json, you will put these parameters into new Intent you hav created as seen in fillNotificationData method.
Other parts of onReceive method creates a local notification and vibrates the device.
Finally on your activity class onResume() method you will check intent parameters to realize if you are opening the app from push notification or not.
#Override
public void onResume() {
super.onResume();
checkPushNotificationCase(getIntent());
}
private void checkPushNotificationCase(Intent intent) {
Bundle extraParameters = intent.getExtras();
Log.d("checking push notifications intent extras : " + extraParameters);
if (extraParameters != null) {
if(extraParameters.containsKey("paramString")) {
// doSomething
}
}
}
I hope you have asked this question for Android :))

how to make my flashlight not o open instantly when i open the program?

// Get the camera
private void getCamera() {
if (camera == null) {
try {
camera = Camera.open();
params = camera.getParameters();
} catch (RuntimeException e) {
Log.e("Camera Error. Failed to Open. Error: ", e.getMessage());
}
}
}
// Turning On flash
private void turnOnFlash() {
if (!isFlashOn) {
if (camera == null || params == null) {
return;
}
// play sound
playSound();
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
isFlashOn = true;
// changing button/switch image
toggleButtonImage();
}
}
My code that gets involved with flash on is above, any suggestions,how to make the flash not open the moment my app opens but only when i press the button
I would guess you are calling turnFlashOn() in onCreate() and don't have a button ClickListener. But it is possible you could be calling turnFlashOn() in onStart() or onResume().
To have it turn on with a button press you should do something like
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_view);
flashlight_button = (Button) findViewById(R.id.your_button);
flashlight_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
getCamera();
turnOnFlash();
}
});
}
I built an open source flashlight for Android that you can check out at Flashlight by Joe github.