"SinchClient not started" The main problem in android studio - android

I am facing this problem for the last two weeks. Can you help me why this problem occurs?
Error occur at this line allClient.callPhoneNumber("+16315192247");
Please check it. Every time it crashes.
package com.eureka.voicecallinapk;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.media.AudioManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.sinch.android.rtc.PushPair;
import com.sinch.android.rtc.Sinch;
import com.sinch.android.rtc.SinchClient;
import com.sinch.android.rtc.SinchError;
import com.sinch.android.rtc.calling.Call;
import com.sinch.android.rtc.calling.CallClient;
import com.sinch.android.rtc.calling.CallClientListener;
import com.sinch.android.rtc.calling.CallListener;
import java.util.List;
public class MainActivity extends AppCompatActivity {
public static final String APP_KEY = "b7258284-f0dnd-4734-afec-210d387d****";
//i do it for security because i am posting here
public static final String APP_SECRET = "k76tOLgz+kSdKL7ULYsH**==";
public static final String ENVIRONMENT = "clientapi.sinch.com";
public Call call;
private TextView callState;
public SinchClient sinchClient;
private Button button;
private String callerId;
private String recipientId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = getIntent();
callerId = intent.getStringExtra("callerId");
recipientId = intent.getStringExtra("recipientId");
sinchClient = Sinch.getSinchClientBuilder()
.context(MainActivity.this)
.userId("172976")
.applicationKey(APP_KEY)
.applicationSecret(APP_SECRET)
.environmentHost(ENVIRONMENT)
.build();
sinchClient.setSupportCalling(true);
sinchClient.startListeningOnActiveConnection();
sinchClient.start();
// sinchClient.getCallClient().addCallClientListener(new SinchCallClientListener());
button = findViewById(R.id.button);
callState = findViewById(R.id.callState);
button.setOnClickListener(view -> {
if (call == null) {
try {
boolean s=isStarted();
Log.d("checksinch", String.valueOf(s));
CallClient callClient = sinchClient.getCallClient();
callClient.callPhoneNumber("+16315192247"); // Error occur at this line "SinchClient not started"
//callClient.callPhoneNumber("+16315192247");
// call = sinchClient.getCallClient().callPhoneNumber("+46000000000.");
// call.addCallListener(new SinchCallListener());
button.setText("Hang Up");
}catch (Exception e){
Log.d("checksinch", e.getMessage());
}
} else {
call.hangup();
button.setText("Call");
}
});
}
private boolean isStarted() {
return (sinchClient != null && sinchClient.isStarted());
}
private class SinchCallListener implements CallListener {
#Override
public void onCallEnded(Call endedCall) {
call = null;
SinchError a = endedCall.getDetails().getError();
button.setText("Call");
callState.setText("");
setVolumeControlStream(AudioManager.USE_DEFAULT_STREAM_TYPE);
}
#Override
public void onCallEstablished(Call establishedCall) {
callState.setText("connected");
setVolumeControlStream(AudioManager.STREAM_VOICE_CALL);
}
#Override
public void onCallProgressing(Call progressingCall) {
callState.setText("ringing");
}
#Override
public void onShouldSendPushNotification(Call call, List<PushPair> pushPairs) {
}
}
private class SinchCallClientListener implements CallClientListener {
#Override
public void onIncomingCall(CallClient callClient, Call incomingCall) {
call = incomingCall;
Toast.makeText(MainActivity.this, "incoming call", Toast.LENGTH_SHORT).show();
call.answer();
call.addCallListener(new SinchCallListener());
button.setText("Hang Up");
}
}
}

Related

I don't understand why 'onResponse()' is not triggered after successful response?

From the log I can see that the web service correctly returns the JSON to me. But for some reason it never enters the onResponse method.
MainActivity.java
OnResponse() method in getaccesstoken() not triggered after successful response
package com.example.alexandra.instagramlogin;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.alexandra.instagramlogin.models.AuthToken;
import com.example.alexandra.instagramlogin.rest.RestClient;
import com.example.alexandra.instagramlogin.rest.services.Auth;
import com.squareup.picasso.Picasso;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class MainActivity extends AppCompatActivity
implements AuthenticationListener {
private static final String TAG = "MainActivity";
private String token = null;
private String code = null;
private AppPreferences appPreferences = null;
private AuthenticationDialog authenticationDialog = null;
private Button button = null;
private View info = null;
AuthToken authToken = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.btn_login);
info = findViewById(R.id.info);
appPreferences = new AppPreferences(this);
//check already have access token
}
public void login() {
button.setText("LOGOUT");
info.setVisibility(View.VISIBLE);
ImageView pic = findViewById(R.id.pic);
Picasso.with(this).load(appPreferences.getString(AppPreferences.PROFILE_PIC)).into(pic);
TextView id = findViewById(R.id.id);
id.setText(appPreferences.getString(AppPreferences.USER_ID));
TextView name = findViewById(R.id.name);
name.setText(appPreferences.getString(AppPreferences.USER_NAME));
}
public void logout() {
button.setText("INSTAGRAM LOGIN");
token = null;
info.setVisibility(View.GONE);
appPreferences.clear();
}
#Override
public void onTokenReceived(String auth_code) {
Log.d(TAG, auth_code);
appPreferences.putString(AppPreferences.CODE, auth_code);
code = auth_code;
getAccessToken(code);
}
//getting access token
private void getAccessToken(final String code) {
Auth auth = RestClient.getInstance();
Call<AuthToken>authTokenCall = auth.getAuthToken(getString(R.string.client_id),getString(R.string.client_secret),"authorization_code",getString(R.string.redirect_url),
code);
authTokenCall.enqueue(new Callback<AuthToken>() {
#Override
public void onResponse(Call<AuthToken> call, Response<AuthToken> response) {
Log.d(TAG, "onResponse: ");
}
#Override
public void onFailure(Call<AuthToken> call, Throwable t) {
}
});
}
public void onClick(View view) {
if(token!=null)
{
logout();
}
else {
authenticationDialog = new AuthenticationDialog(this, this);
authenticationDialog.setCancelable(true);
authenticationDialog.show();
}
}
}
pojo(AuthToken)
package com.example.alexandra.instagramlogin.models;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class AuthToken {
#SerializedName("access_token")
#Expose
private String access_token;
#SerializedName("user_id")
#Expose
private Integer user_id;
public String getAccessToken() {
return access_token;
}
public void setAccessToken(String accessToken) {
this.access_token = accessToken;
}
public Integer getUserId() {
return user_id;
}
public void setUserId(Integer userId) {
this.user_id = userId;
}
}
Auth.java
package com.example.alexandra.instagramlogin.rest.services;
import com.example.alexandra.instagramlogin.Classes.AuthorizationToken;
import com.example.alexandra.instagramlogin.models.AuthToken;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;
public interface Auth {
#FormUrlEncoded
#POST("oauth/access_token")
Call<AuthToken>getAuthToken(#Field("client_id")String clientid,#Field("client_secret")String client_secret,#Field("grant_type")String grant_type
,#Field("redirect_uri")String redirect_uri,#Field("code")String code);
}
Response
D/OkHttp: {"access_token": "IGQVJXWTcyNVBZANmFfeWNSQXUwQmdZAYlUtSHYxc1Q1dUlZAWTVPaTVTZA3dqYU00dC1ocjc4WDJwS2ZA2cVJjMTA3Rkx5QkN4alBlVjFNWjBndkJMcm45ZA0s3dk5HbXBFNnU5empGVGI0WXdrb1ZARZADktVlFjeVJIQUxGRnpv", "user_id": 17841401561947636}
I think you are not handling all case correctly like what if onFailure trigger for error.
I am not debugging you project so exact error i can tell you but i suggest you some links where you can find how to debug your code properly.
How to debug android apps

How to receive Messages in chat App using signalR in Android

hello i am new in signalR i am making one chating app with using signalR i take reference from SignalR integration in android studio here with the help of this i able to send the messages to the chat group but i am not able to receive messages i read lots of Q&A here but i am not able to solve this problem i paste here my code and please anyone tell me how do i receive message from the server.following is my code.
Activity main
package myapp.chatapp;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;
import com.google.gson.JsonElement;
import java.util.ArrayList;
import microsoft.aspnet.signalr.client.MessageReceivedHandler;
import microsoft.aspnet.signalr.client.Platform;
import microsoft.aspnet.signalr.client.http.android.AndroidPlatformComponent;
import microsoft.aspnet.signalr.client.hubs.HubConnection;
import microsoft.aspnet.signalr.client.hubs.HubProxy;
import microsoft.aspnet.signalr.client.hubs.SubscriptionHandler2;
import microsoft.aspnet.signalr.client.transport.ClientTransport;
import microsoft.aspnet.signalr.client.transport.LongPollingTransport;
public class MainActivity extends AppCompatActivity implements SignalRService.Something {
private StringBuilder mLog;
private ListView mTestCaseList;
private Spinner mTestGroupSpinner;
private HubConnection mHubConnection;
private HubProxy mHubProxy;
private final Context mContext = this;
private SignalRService mService;
private SignalRService mMessageResive;
private boolean mBound = false;
ListView list_item;
EditText editText;
ArrayList<String> listItems;
ArrayAdapter<String> adapter;
ClientTransport transport;
private Handler mHandler; // to display Toast message
private Thread t;
#Override
public void onConfigurationChanged(Configuration newConfig) {
// don't restart the activity. Just process the configuration change
super.onConfigurationChanged(newConfig);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent();
intent.setClass(mContext, SignalRService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
editText = (EditText)findViewById(R.id.edit_message);
ImageButton btn = (ImageButton)findViewById(R.id.btn);
list_item = (ListView)findViewById(R.id.list_item);
listItems = new ArrayList<String>();
/*listItems.add("First Item - added on Activity Create");*/
/* adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, listItems);*/
adapter = new ArrayAdapter<String>(mContext,R.layout.custom_list, R.id.textView,listItems);
list_item.setAdapter(adapter);
final Handler handler = new Handler();
handler.postDelayed( new Runnable() {
#Override
public void run() {
adapter.notifyDataSetChanged();
handler.postDelayed( this, 1000 );
}
}, 1000 );
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listItems.add(editText.getText().toString());
adapter.notifyDataSetChanged();
sendMessage(view);
}
});
}
#Override
protected void onStop() {
// Unbind from the service
if (mBound) {
unbindService(mConnection);
mBound = false;
}
super.onStop();
}
public void sendMessage(View view) {
if (mBound) {
String message = editText.getText().toString();
String email = "kn#yopmail.com";
String name = "Kunal From Android";
String group ="1";
mService.sendMessage(name,email,group,message);
editText.setText("");
// Call a method from the SignalRService.
// However, if this call were something that might hang, then this request should
// occur in a separate thread to avoid slowing down the activity performance.
/*EditText editText = (EditText) findViewById(R.id.edit_message);
if (editText != null && editText.getText().length() > 0) {
}*/
}
}
public void setmMessageResive(JsonElement jsonElement)
{
listItems.add(10, String.valueOf(jsonElement));
}
/**
* Defines callbacks for service binding, passed to bindService()
*/
private final ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
// We've bound to SignalRService, cast the IBinder and get SignalRService instance
SignalRService.LocalBinder binder = (SignalRService.LocalBinder) iBinder;
mService = binder.getService();
mBound = true;
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
mBound = false;
}
};
#Override
public void doSomething(String msg) {
listItems.add(msg);
}
}
Service code
package myapp.chatapp;
import android.app.Service;
import android.bluetooth.BluetoothClass;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;
import com.google.gson.JsonElement;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
import java.util.logging.Logger;
import microsoft.aspnet.signalr.client.Action;
import microsoft.aspnet.signalr.client.Credentials;
import microsoft.aspnet.signalr.client.LogLevel;
import microsoft.aspnet.signalr.client.MessageReceivedHandler;
import microsoft.aspnet.signalr.client.Platform;
import microsoft.aspnet.signalr.client.SignalRFuture;
import microsoft.aspnet.signalr.client.http.Request;
import microsoft.aspnet.signalr.client.http.android.AndroidPlatformComponent;
import microsoft.aspnet.signalr.client.hubs.HubConnection;
import microsoft.aspnet.signalr.client.hubs.HubProxy;
import microsoft.aspnet.signalr.client.hubs.SubscriptionHandler1;
import microsoft.aspnet.signalr.client.hubs.SubscriptionHandler2;
import microsoft.aspnet.signalr.client.hubs.SubscriptionHandler4;
import microsoft.aspnet.signalr.client.transport.ClientTransport;
import microsoft.aspnet.signalr.client.transport.LongPollingTransport;
import microsoft.aspnet.signalr.client.transport.ServerSentEventsTransport;
/**
* Created by NULLPLEX7 on 11/28/2017.
*/
public class SignalRService extends Service {
private HubConnection mHubConnection;
private HubProxy mHubProxy;
private Handler mHandler; // to display Toast message
private final IBinder mBinder = new LocalBinder(); // Binder given to clients
ClientTransport transport;
registerListener registerListener;
private MainActivity setmMessageResive;
public Something list;
public SignalRService() {
}
#Override
public void onCreate() {
super.onCreate();
mHandler = new Handler(Looper.getMainLooper());
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
int result = super.onStartCommand(intent, flags, startId);
startSignalR();
return result;
}
#Override
public void onDestroy() {
mHubConnection.stop();
super.onDestroy();
}
#Override
public IBinder onBind(Intent intent) {
// Return the communication channel to the service.
startSignalR();
return mBinder;
}
/**
* Class used for the client Binder. Because we know this service always
* runs in the same process as its clients, we don't need to deal with IPC.
*/
public class LocalBinder extends Binder {
public SignalRService getService() {
// Return this instance of SignalRService so clients can call public methods
return SignalRService.this;
}
}
/**
* method for clients (activities)
*/
public void sendMessage(String name, String email, String group, String msg ) {
String SERVER_METHOD_SEND = "BroadCastMessage";
mHubProxy.invoke(SERVER_METHOD_SEND, name,email,group,msg);
}
private void startSignalR() {
Platform.loadPlatformComponent(new AndroidPlatformComponent());
Credentials credentials = new Credentials() {
#Override
public void prepareRequest(Request request) {
request.addHeader("User-Name", "BNK");
}
};
String serverUrl = "myurlhere";
mHubConnection = new HubConnection(serverUrl);
mHubConnection.setCredentials(credentials);
String SERVER_HUB_CHAT = "ChatHub";
mHubProxy = mHubConnection.createHubProxy(SERVER_HUB_CHAT);
ClientTransport clientTransport = new ServerSentEventsTransport(mHubConnection.getLogger());
SignalRFuture<Void> signalRFuture = mHubConnection.start(clientTransport);
mHubProxy.subscribe(this);
transport = new LongPollingTransport(mHubConnection.getLogger());
mHubConnection.start(transport);
/* ****new codes here**** */
/* ****seems useless but should be here!**** */
mHubProxy.subscribe(new Object() {
#SuppressWarnings("unused")
public void newMessage(final String message, final String messageId, final String chatId,
final String senderUserId, final String fileUrl, final String replyToMessageId) {
}
});
try {
signalRFuture.get();
}catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
return;
}
mHubProxy.on("receiveGroupMessage",
new SubscriptionHandler4<String, String, String, String>() {
#Override
public void run(final String name,final String msg ,final String avtar,final String date ) {
final String finalMsg = name + " says " + msg;
/*final String finalMsg = msg;*/
// display Toast message
mHandler.post(new Runnable() {
#Override
public void run() {
list.doSomething(msg);
}
});
}
}
, String.class,String.class,String.class,String.class);
mHubConnection.received(new MessageReceivedHandler() {
#Override
public void onMessageReceived(final JsonElement json) {
Log.e("receiveGroupMessage ", json.toString());
mHandler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), ""+json, Toast.LENGTH_SHORT).show();
}
});
}
});
}
public interface Something
{
void doSomething(String msg);
}
}
i read on stack overflow that in onMessageReceived i get the server responses but i did not get any response here . I want when any one send message in group from web i want that message in my chat app someone suggest me that i need to create Event listener but i don't no how to create it . please tell me how do i get messages in my chat app.
mHubProxy.on("receiveGroupMessage",
new SubscriptionHandler4<String, String, String, String>() {
#Override
public void run(final String name,final String msg ,final String avtar,final String date ) {
final String finalMsg = name + " says " + msg;
/*final String finalMsg = msg;*/
// display Toast message
mHandler.post(new Runnable() {
#Override
public void run() {
list.doSomething(msg);
}
});
}
}
, String.class,String.class,String.class,String.class);
i thought that i got messages here but execution not go inside the Run.
Any Help is Welcome

BraintreeHttpClient.setBaseUrl(java.lang.String) on a null object reference

I am using braintree api to get add card in app for payments. It works fines and sometimes crashes randomly,
This is my stacktrace,
E/AndroidRuntime: FATAL EXCEPTION: Thread-833
Process: cl.tempclick, PID: 29509
java.lang.NullPointerException: Attempt to invoke virtual method 'com.braintreepayments.api.internal.HttpClient com.braintreepayments.api.internal.BraintreeHttpClient.setBaseUrl(java.lang.String)' on a null object reference
at com.braintreepayments.api.BraintreeFragment.setConfiguration(BraintreeFragment.java:488)
at com.braintreepayments.api.BraintreeFragment$5.onConfigurationFetched(BraintreeFragment.java:415)
at com.braintreepayments.api.ConfigurationManager.getConfiguration(ConfigurationManager.java:46)
at com.braintreepayments.api.BraintreeFragment.fetchConfiguration(BraintreeFragment.java:412)
at com.braintreepayments.api.BraintreeFragment.waitForConfiguration(BraintreeFragment.java:458)
at com.braintreepayments.api.TokenizationClient.tokenize(TokenizationClient.java:72)
at com.braintreepayments.api.Card.tokenize(Card.java:29)
at cl.tk.ui.activities.sub_activity.AddPayment$UIThreadHandler$1.run(AddPayment.java:364)
at java.lang.Thread.run(Thread.java:818)
This is my Code for the activity,
package cl.tk.ui.activities.sub_activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.braintreepayments.api.BraintreeFragment;
import com.braintreepayments.api.exceptions.InvalidArgumentException;
import com.braintreepayments.api.interfaces.PaymentMethodNonceCreatedListener;
import com.braintreepayments.api.models.CardBuilder;
import com.braintreepayments.api.models.PaymentMethodNonce;
import cl.tk.R;
import cl.tk.controllers.constants.Constants;
import cl.tk.controllers.constants.Enums_String;
import cl.tk.controllers.listeners.ProcessedResult;
import cl.tk.controllers.rest_api.RetrofitAdapters;
import cl.tk.ui.activities.Register;
import cl.tk.ui.fragments.dialog.DTDialog;
import cl.tk.ui.iBAPViews.editext.pattern.PatternedEditText;
import cl.tk.utility.CreditCard;
import cl.tk.utility.CustomException;
import cl.tek.utility.GeneralFunctions;
import cl.tk.utility.MonthYearPicker;
import cl.tk.utility.Validation;
import cl.tk.utility.fonts.FontsManager;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
public class AddPayment extends AppCompatActivity implements View.OnClickListener,View.OnTouchListener, ProcessedResult,PaymentMethodNonceCreatedListener
{
private Handler uiThreadHandler;
private TextView tvExpiryDate;
//private EditText edCvv,ed_cardHOlderName,edZip;
private PatternedEditText edCardNumber;
private MonthYearPicker myp;
private String mClientToken=null;
private CreditCard creditCard =null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_payment);
uiThreadHandler = new UIThreadHandler();
initialze();
downloadBraintreeTOken();
}
private void downloadBraintreeTOken()
{
RetrofitAdapters.get().getBraintreeToken(new Callback<Response>() {
#Override
public void success(Response response, Response response2) {
parseResult(response);
}
#Override
public void failure(RetrofitError error) {
uiThreadHandler.sendEmptyMessage(Constants.ActivityBasicsCode.HIDEDIALOG);
Message message = uiThreadHandler.obtainMessage(Constants.ActivityBasicsCode.SHOWTOAST);
message.obj = error.getLocalizedMessage();
uiThreadHandler.sendMessage(message);
}
});
}
private void initialze()
{
GeneralFunctions.setToolbarMsgIconHide(this, Constants.ToolbarConstants.PAYMENTS, true);
Button buttonAdd=GeneralFunctions.findViewByIdAndCast(this,R.id.payment_bt_addCard);
buttonAdd.setOnClickListener(this);
GeneralFunctions.setColorSelector(ContextCompat.getColor(this, R.color.color175), ContextCompat.getColor(this, R.color.color1A9), buttonAdd);
TextView tv_defult=GeneralFunctions.findViewByIdAndCast(this,R.id.payment_ct_default);
tv_defult.setOnClickListener(this);
FontsManager.initFormAssets(this, Enums_String.FontsNameLato.SEMIBOLD.toString());
FontsManager.changeFonts(tv_defult);
edCardNumber=GeneralFunctions.findViewByIdAndCast(this,R.id.payment_ed_cardNumber);
tvExpiryDate=GeneralFunctions.findViewByIdAndCast(this,R.id.payment_tv_expiryDate);
tvExpiryDate.setOnTouchListener(this);
myp = new MonthYearPicker(this);
myp.build(new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
tvExpiryDate.setText(myp.getSelectedMonth() + 1 + "/" + myp.getSelectedYear());
}
}, null);
}
#Override
protected void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter(Enums_String.LocalReceiver.INTERENT.toString());
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, filter);
}
#Override
protected void onPause() {
super.onPause();
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
}
#Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.payment_bt_addCard:
uiThreadHandler.sendEmptyMessage(Constants.ActivityBasicsCode.VALIDATION);
break;
}
}
#Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_UP)
{
if(v.getId()==R.id.payment_tv_expiryDate)
{
if(myp.pickerDialog != null && !myp.pickerDialog.isShowing())
myp.pickerDialog.dismiss();
myp.show();
}
return true;
}
return false;
}
#Override
public <IResponse, IMethod, IExtra> void processedResult(IResponse iResponse, IMethod iMethod, IExtra iExtra) {
}
#Override
public <IResponse, IMethod> void processedResult(IResponse iResponse, IMethod iMethod) {
switch (iMethod.toString())
{
case Constants.CallbackConstants.VIEW_ERROR: {
Message message = uiThreadHandler.obtainMessage(Constants.ActivityBasicsCode.SETERROR);
message.obj=iResponse;
uiThreadHandler.sendMessage(message);
}
break;
case Constants.CallbackConstants.BACK:
finish();
break;
}
}
#Override
public void onPaymentMethodNonceCreated(final PaymentMethodNonce paymentMethodNonce) {
}
private void setError(String errorMsg) {
if (errorMsg.equalsIgnoreCase("cardNumber"))
GeneralFunctions.setError(null,String.format(getString(R.string.ed_error_invalid),edCardNumber.getTag().toString()),edCardNumber);
else if (errorMsg.equalsIgnoreCase("cardDate"))
GeneralFunctions.setError(null,String.format(getString(R.string.ed_error_invalid),tvExpiryDate.getTag().toString()),tvExpiryDate);
}
private class UIThreadHandler extends Handler {
#Override
public void handleMessage(Message msg)
{
switch (msg.what) {
case Constants.ActivityBasicsCode.CARDERROR:
GeneralFunctions.setError((CustomException)msg.obj,null,null);
break;
case Constants.ActivityBasicsCode.SETERROR:
setError(msg.obj.toString());
break;
case Constants.ActivityBasicsCode.SHOWTOAST:
{
String text=(String)msg.obj;
GeneralFunctions.showToast(text,AddPayment.this);
}
break;
case Constants.ActivityBasicsCode.HIDEDIALOG:
GeneralFunctions.hideProgressDialog(Constants.DialogConstants.Transparent, AddPayment.this);
break;
case Constants.ActivityBasicsCode.SHOWDIALOG:
{
DTDialog dtDialog=DTDialog.newInstance();
GeneralFunctions.showProgressDialog(dtDialog, Constants.DialogConstants.Transparent, AddPayment.this);
}break;
case Constants.ActivityBasicsCode.VALIDATION: {
new Thread(new Runnable() {
#Override
public void run()
{
try {
if(Validation.validate(AddPayment.this)) {
creditCard = new CreditCard(GeneralFunctions.getText(edCardNumber),GeneralFunctions.getText(tvExpiryDate),AddPayment.this);
boolean validation = creditCard.validateCard();
if (validation) {
if(mClientToken==null) {
downloadBraintreeTOken();
Message message = uiThreadHandler.obtainMessage(Constants.ActivityBasicsCode.SHOWTOAST);
message.obj = getString(R.string.toast_payment_token);
uiThreadHandler.sendMessage(message);
return;
}
BraintreeFragment braintreeFragment= BraintreeFragment.newInstance(AddPayment.this, mClientToken);
if(null==braintreeFragment)
{
Message message = uiThreadHandler.obtainMessage(Constants.ActivityBasicsCode.SHOWTOAST);
message.obj = getString(R.string.toast_payment_fragment);
uiThreadHandler.sendMessage(message);
uiThreadHandler.sendEmptyMessage(Constants.ActivityBasicsCode.SHOWDIALOG);
}
else {
CardBuilder cardBuilder = new CardBuilder()
.cardNumber(creditCard.getNumber().replaceAll("-", "").trim())
.expirationDate(creditCard.getExpriyDate());
com.braintreepayments.api.Card.tokenize(braintreeFragment, cardBuilder); //On this line my app crashes randomly
}
}
}
}catch (CustomException e)
{
Message message = uiThreadHandler.obtainMessage(Constants.ActivityBasicsCode.CARDERROR);
message.obj=e;
uiThreadHandler.sendMessage(message);
} catch (InvalidArgumentException e) {
e.printStackTrace();
}
}
}).start();
break;
}
}
super.handleMessage(msg);
}
}
}
This is my gradle version,
compile 'com.braintreepayments.api:braintree:2.+'
Full disclosure: I work for Braintree.
Are you refreshing the client token every time you go through the checkout process as required? I see that you are only downloading the Braintree token from the server if it is null.
Without having any insight into your CreditCard class or its validateCard method, another possibility may be that the CardBuilder object you are passing into Card.tokenize may not be well-formed.
​
If you are still having trouble, please reach out to Braintree support for help debugging your integration.

facebook login android app crashes

The code is posted here and the app crashes when the login button is clicked with null pointer exception at homefragment on click.im a beginer.please help.logcat http://postimg.org/image/6d1qyszkd/
simple facebook class basically is :
public SimpleFacebook()
{
mSessionStatusCallback = new SessionStatusCallback();
}
public static void initialize(Activity activity)
{
if (mInstance == null)
{
mInstance = new SimpleFacebook();
}
mActivity = activity;
}
public static SimpleFacebook getInstance(Activity activity)
{
if (mInstance == null)
{
mInstance = new SimpleFacebook();
}
mActivity = activity;
return mInstance;
}
public static SimpleFacebook getInstance()
{
return mInstance;
}
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.parse.GetDataCallback;
import com.sromku.simple.fb.SimpleFacebook;
import com.sromku.simple.fb.Properties;
import com.sromku.simple.fb.SimpleFacebook;
import com.sromku.simple.fb.SimpleFacebook.OnFriendsRequestListener;
import com.sromku.simple.fb.SimpleFacebook.OnLoginListener;
import com.sromku.simple.fb.SimpleFacebook.OnLogoutListener;
import com.sromku.simple.fb.SimpleFacebook.OnProfileRequestListener;
import com.sromku.simple.fb.entities.Profile;
import com.sromku.simple.fb.example.utils.Utils;
import com.sromku.simple.fb.utils.Attributes;
import com.sromku.simple.fb.utils.PictureAttributes;
import com.sromku.simple.fb.utils.PictureAttributes.PictureType;
public class HomeFragment extends Fragment {
protected static final String TAG = HomeFragment.class.getName();
private SimpleFacebook mSimpleFacebook;
ProgressDialog mProgress;
Button mButtonLogin;
Button mButtonLogout;
TextView mTextStatus;
// Login listener
private OnLoginListener mOnLoginListener = new OnLoginListener()
{
#Override
public void onFail(String reason)
{
mTextStatus.setText(reason);
Log.w(TAG, "Failed to login");
}
#Override
public void onException(Throwable throwable)
{
mTextStatus.setText("Exception: " + throwable.getMessage());
Log.e(TAG, "Bad thing happened", throwable);
}
#Override
public void onThinking()
{
// show progress bar or something to the user while login is happening
mTextStatus.setText("Thinking...");
}
#Override
public void onLogin()
{
// change the state of the button or do whatever you want
mTextStatus.setText("Logged in");
loggedInUIState();
toast("You are logged in");
}
#Override
public void onNotAcceptingPermissions()
{
toast("You didn't accept read permissions");
}
};
// Logout listener
private OnLogoutListener mOnLogoutListener = new OnLogoutListener()
{
#Override
public void onFail(String reason)
{
mTextStatus.setText(reason);
Log.w(TAG, "Failed to login");
}
#Override
public void onException(Throwable throwable)
{
mTextStatus.setText("Exception: " + throwable.getMessage());
Log.e(TAG, "Bad thing happened", throwable);
}
#Override
public void onThinking()
{
// show progress bar or something to the user while login is happening
mTextStatus.setText("Thinking...");
}
#Override
public void onLogout()
{
// change the state of the button or do whatever you want
mTextStatus.setText("Logged out");
loggedOutUIState();
toast("You are logged out");
}
};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.homend_home_fragment, container, false);
// test local language
Utils.updateLanguage(getActivity(), "en");
Utils.printHashKey(getActivity());
mButtonLogin = (Button)rootView.findViewById(R.id.button_login);
mButtonLogout = (Button)rootView.findViewById(R.id.button_logout);
mTextStatus = (TextView)rootView.findViewById(R.id.text_status);
mButtonLogin.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View arg0)
{
mSimpleFacebook.login(mOnLoginListener);
}
});
// 2. Logout example
mButtonLogout.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View arg0)
{
mSimpleFacebook.logout(mOnLogoutListener);
}
});
return rootView;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
mSimpleFacebook.onActivityResult(getActivity(), requestCode, resultCode, data);
super.onActivityResult(requestCode, resultCode, data);
}
private void setUIState()
{
if (mSimpleFacebook.isLogin())
{
loggedInUIState();
}
else
{
loggedOutUIState();
}
}
/**
* Show toast
*
* #param message
*/
private void toast(String message)
{
Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show();
}
private void loggedInUIState()
{
mButtonLogin.setEnabled(false);
mButtonLogout.setEnabled(true);
mTextStatus.setText("Logged in");
}
private void loggedOutUIState()
{
mButtonLogin.setEnabled(true);
mButtonLogout.setEnabled(false);
mTextStatus.setText("Logged out");
}
private void showDialog()
{
mProgress = ProgressDialog.show(getActivity(), "Thinking",
"Waiting for Facebook", true);
}
private void hideDialog()
{
mProgress.hide();
}
public class OnProfileRequestAdapter implements OnProfileRequestListener
{
#Override
public void onThinking()
{
}
#Override
public void onException(Throwable throwable)
{
}
#Override
public void onFail(String reason)
{
}
#Override
public void onComplete(Profile profile)
{
}
}
}
I think problem might be here. You have just declared your variable
private SimpleFacebook mSimpleFacebook;
you haven't initialized that variable so you got NPE
So initialized it on onCreateView() method.
mSimpleFacebook = SimpleFacebook.getInstance(getActivity());
And yet you get error then you need to finally change
mSimpleFacebook = SimpleFacebook.getInstance();
Add this line to manifest file..
<activity android:name="com.facebook.LoginActivity" android:screenOrientation="portrait" android:configChanges="keyboardHidden|orientation">
</activity>
which would be finally works for you.!!

Making a call when button pressed on Arduino

Hi I'm trying to combine 2 projects
1. that tells me wen button on arduino pressed
2. make a call on android
what im trying to do is when button pressed on arduino make a call..
but with no luck :(
Call
package net.mitchtech.adb;
import net.mitchtech.adb.simpledigitalinput.R;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
public class phonecalls extends Activity {
private void call() {
try {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:048598077"));
startActivity(callIntent);
} catch (ActivityNotFoundException activityException) {
Log.e("dialing-example", "Call failed", activityException);
}
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.input);
}
}
buttons
package net.mitchtech.adb;
import net.mitchtech.adb.simpledigitalinput.R;
import net.mitchtech.adb.phonecalls;
import org.microbridge.server.AbstractServerListener;
import org.microbridge.server.Server;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;
public class ButtonView extends FrameLayout {
private static final String TAG = ButtonView.class.getSimpleName();
private final View mButtonView;
private Server mServer;
private final int BUTTON1 = 2;
private final int BUTTON2 = 3;
public ButtonView(Context context, AttributeSet attrs) {
super(context, attrs);
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mButtonView = inflater.inflate(R.layout.input, this);
}
public void setServer(Server server) {
mServer = server;
mServer.addListener(new AbstractServerListener() {
#Override
public void onReceive(org.microbridge.server.Client client, byte[] data) {
if (data.length < 2)
return;
final int pinNumber = data[0];
final int pinState = data[1];
Log.i(TAG, "data[0]:" + pinNumber + " data[1]:" + pinState);
final TextView positionText = (TextView) findViewById(R.id.activeText);
class InputAction implements Runnable {
public void run() {
switch (pinNumber) {
case BUTTON1:
if (pinState == 1) {
call();
positionText.setText("Button 1 Active");
} else {
positionText.setText("");
}
break;
case BUTTON2:
if (pinState == 1) {
positionText.setText("Button 2 Active");
} else {
positionText.setText("");
}
break;
default:
break;
}
}
};
InputAction action = new InputAction();
post(action);
}
});
}
public View getmButtonView() {
return mButtonView;
}
}
and another activity
package net.mitchtech.adb;
import java.io.IOException;
import net.mitchtech.adb.simpledigitalinput.R;
import org.microbridge.server.Server;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class SimpleDigitalInputActivity extends Activity {
private final static String TAG = SimpleDigitalInputActivity.class.getSimpleName();
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Server server = null;
try
{
server = new Server(4567);
server.start();
ButtonView buttonView = (ButtonView) findViewById(R.id.inputView);
buttonView.setServer(server);
} catch (IOException e)
{
Log.e(TAG, "Unable to start TCP server", e);
System.exit(-1);
}
}
}
Your call() function is declared in your activity, but you're trying to access it in your ButtonView class. Try moving it into ButtonView (copy & paste).

Categories

Resources