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

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.

Related

"SinchClient not started" The main problem in android studio

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");
}
}
}

App enters infinite loop trying to connect to HC-06, but no loop is present

My application enters an infinite loop when I press the Connect button to connect to an HC-06 Bluetooth module (Arduino shield). However, there are no loops anywhere in the code when the button is pressed.
package dleedesign.dubcommunicationstestapp;
import android.app.Fragment;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import java.util.Set;
/**
* Created by Chris on 7/24/2016.
*/
public class FirstFragment extends Fragment {
View myView;
public final String TAG = "Main";
private Bluetooth bt;
public Button sendCommand;
public Button send;
public TextView msgReceived;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.first_layout, container, false);
sendCommand = (Button) myView.findViewById(R.id.sendCommand);
sendCommand.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
connectService();
}
});
send = (Button) myView.findViewById(R.id.send);
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendBtCommand("1");
}
});
msgReceived = (TextView) myView.findViewById(R.id.msgReceived);
msgReceived.setText("Ready to connect");
bt = new Bluetooth(new MainActivity(), mHandler);
return myView;
}
public void sendBtCommand(String msg)
{
bt.sendMessage(msg);
}
public void connectService()
{
try {
msgReceived.setText("Connecting...");
BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
if(btAdapter.isEnabled())
{
bt.start();
bt.connectDevice("HC-06");
Log.d(TAG, "Btservice started- listening");
msgReceived.setText("Connected!");
}
else
{
Log.w(TAG, "Btservice started - bluetooth is not enabled, requesting enable...");
Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBluetooth, 0);
msgReceived.setText("Bluetooth not enabled, requested for enable");
}
} catch (Exception e) {
Log.e(TAG, "Unable to start bluetooth", e);
msgReceived.setText("Unable to connect: " + e);
}
}
private final Handler mHandler = new Handler()
{
#Override
public void handleMessage(Message msg)
{
switch (msg.what)
{
case Bluetooth.MESSAGE_STATE_CHANGE:
Log.d(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
break;
case Bluetooth.MESSAGE_WRITE:
Log.d(TAG, "MESSAGE_WRITE");
break;
case Bluetooth.MESSAGE_READ:
Log.d(TAG, "MESSAGE_READ");
break;
case Bluetooth.MESSAGE_DEVICE_NAME:
Log.d(TAG, "MESSAGE_DEVICE_NAME " + msg);
break;
case Bluetooth.MESSAGE_TOAST:
Log.d(TAG, "MESSAGE_TOAST " + msg);
break;
}
}
};
}
For some reason, this problem just suddenly appeared when I tried to employ a loop to keep trying to connect while the connection is not established. I removed that code, but could it still be there somewhere?
Have you overridden the fragment's onActivityResult method?
If not, try overriding it and calling connectService() inside of it, by adding this to your fragment:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
connectService()
}

Android Error with Websocket

Im working on Websocket android application. I want to create Register and Login application with websocket. I am able to connect to websocket server with websocket android project. I have created Register,Login activity with online reference.In register Activity, when I'm storing Registered data to Server using "send" method of websocketclient Java Class I'm getting "java.lang.NullPointerException: Attempt to invoke virtual method 'void org.java_websocket.client.WebSocketClient.send(java.lang.String)' on a null object reference" Error on my Log-cat window.
here is my Main Activity:
package org.asperohgedgetws.a7.hgadgetws;
import android.app.Activity;
import android.app.Fragment;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import java.net.URI;
import java.net.URISyntaxException;
import android.widget.Button;
import android.widget.Toast;
import android.content.Intent;
public class MainActivity extends Activity implements View.OnClickListener {
Button bLogout;
UserLocalStore userLocalStore;
private WebSocketClient mWebSocketClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bLogout = (Button) findViewById(R.id.bLogout);
bLogout.setOnClickListener(this);
userLocalStore = new UserLocalStore(this);
connectWebSocket();
}
#Override
protected void onStart() {
super.onStart();
if (authenticate()== true){
displayUserDetails();
} else{
Toast.makeText(getApplicationContext(), "Not Registered User :(", Toast.LENGTH_SHORT).show();
startActivity(new Intent(MainActivity.this,Login.class));
}
}
private boolean authenticate(){
return userLocalStore.getUserLoggedIn();
}
private void displayUserDetails(){
User user = userLocalStore.getLoggedInUser();
}
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.bLogout:
startActivity(new Intent(this,Login.class));
userLocalStore.clearUserData();
userLocalStore.setUserLoggedIn(false);
Toast.makeText(getApplicationContext(), "Logout :)", Toast.LENGTH_SHORT).show();
break;
}
}
private void connectWebSocket() {
URI uri;
try {
uri = new URI("ws://xxx.xxx.xxx.xxx:xxxx");
} catch (URISyntaxException e) {
e.printStackTrace();
return;
}
mWebSocketClient = new WebSocketClient(uri) {
#Override
public void onOpen(ServerHandshake serverHandshake) {
Log.i("Websocket", "Opened");
//mWebSocketClient.send("Hello from " + Build.MANUFACTURER + " " + Build.MODEL);
mWebSocketClient.send("{\"1512BD002\":\"SO#0\":\"2\"}");
}
#Override
public void onMessage(String s) {
final String message = s;
runOnUiThread(new Runnable() {
#Override
public void run() {
//TextView textView = (TextView)findViewById(R.id.messages);
//textView.setText(textView.getText() + "\n" + message);
}
});
}
#Override
public void onClose(int i, String s, boolean b) {
Log.i("Websocket", "Closed " + s);
}
#Override
public void onError(Exception e) {
Log.i("Websocket", "Error " + e.getMessage());
}
};
mWebSocketClient.connect();
}
public void sendMessage(View view) {
// EditText editText = (EditText)findViewById(R.id.message);
// mWebSocketClient.send(editText.getText().toString());
//editText.setText("");
}
}
RegisterActivity
package org.asperohgedgetws.a7.hgadgetws;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import org.java_websocket.handshake.ServerHandshake;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.java_websocket.client.WebSocketClient;
public class Register extends AppCompatActivity implements View.OnClickListener {
Button bRegister;
EditText etName, etAge, etUsername, etPassword;
WebSocketClient nwebsocket;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
etName = (EditText) findViewById(R.id.etName);
etAge = (EditText) findViewById(R.id.etAge);
etUsername = (EditText) findViewById(R.id.etUsername);
etPassword = (EditText) findViewById(R.id.etPassword);
bRegister = (Button) findViewById(R.id.bRegister);
bRegister.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bRegister:
// Toast.makeText(getApplicationContext(), "Register", Toast.LENGTH_SHORT).show();
String name = etName.getText().toString();
int age = Integer.parseInt(etAge.getText().toString());
String username = etUsername.getText().toString();
String password = etPassword.getText().toString();
User user = new User(name, age, username, password);
registerUser(user);
break;
}
}
private void registerUser(User user) {
String strtosend = "";
JSONObject object = new JSONObject();
try {
// Add the id to the json
object.put("name", user.name);
object.put("age", user.age);
object.put("username", user.username);
object.put("password", user.password);
strtosend = object.toString();
} catch (JSONException e) {
// Handle impossible error
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), strtosend, Toast.LENGTH_SHORT).show();
nwebsocket.send("Hi!");
Intent loginIntent = new Intent(Register.this, Login.class);
startActivity(loginIntent);
}
}
Logcat Output:
05-27 11:49:54.331 19459-19459/org.asperohgedgetws.a7.hgadgetws E/AndroidRuntime: FATAL EXCEPTION: main
Process: org.asperohgedgetws.a7.hgadgetws, PID: 19459
java.lang.NullPointerException: Attempt to invoke virtual method 'void org.java_websocket.client.WebSocketClient.send(java.lang.String)' on a null object reference
at org.asperohgedgetws.a7.hgadgetws.Register.registerUser(Register.java:73)
at org.asperohgedgetws.a7.hgadgetws.Register.onClick(Register.java:51)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Do I have to use again below code in Registered activity?
private void connectWebSocket() {
URI uri;
try {
uri = new URI("ws://xxx.xxx.xxx.xxx:xxxx");
} catch (URISyntaxException e) {
e.printStackTrace();
return;
}
nWebsocketClient = new WebSocketClient(uri) {
#Override
public void onOpen(ServerHandshake serverHandshake) {
Log.i("Websocket", "Opened");
}
#Override
public void onMessage(String s) {
final String message = s;
runOnUiThread(new Runnable() {
#Override
public void run() {
}
});
}
#Override
public void onClose(int i, String s, boolean b) {
Log.i("Websocket", "Closed " + s);
}
#Override
public void onError(Exception e) {
Log.i("Websocket", "Error " + e.getMessage());
}
};
nWebsocketClient.connect();
}
The problem is that your nwebsocket is never initialized, its value is null and that's why you get this error when trying to execute the send method.
You need to initialize it somewhere:
nwebsocket = new WebSocketClient(...);
NB: If you want to share the same instance of WebSocketClient between MainActivity and Register activity, you could make it public static in MainActivity
public static WebSocketClient mWebSocketClient;
Then remove your WebSocketClient nwebsocket from Register and use MainActivity.mWebSocketClient instead.

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.!!

Calling activitygroup from customlistadapter

I am working on an android app which is having functionality of tabs.
Everything is working fine but I am not able to call activtygroup from listadapter.
Here is my code for list adapter:
import java.util.ArrayList;
import android.app.Activity;
import android.app.ActivityGroup;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.tv.socialgoal.R;
import com.tv.socialgoal.imageloader.ImageLoader;
public class AllyListAdapter extends BaseAdapter{
Activity ctx;
ArrayList<Object> alist;
private ImageLoader imageLoader;
AllyBean allyBean;
private String photoPath;
public AllyListAdapter(Activity ctx, ArrayList<Object> alist) {
super();
this.ctx = ctx;
this.alist = alist;
imageLoader=new ImageLoader(ctx);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return alist.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View arg1, ViewGroup arg2) {
LayoutInflater linf=(LayoutInflater) ctx.getSystemService(ctx.LAYOUT_INFLATER_SERVICE);
View v=linf.inflate(R.layout.ally_list_row, null);
TextView tv=(TextView)v.findViewById(R.id.allyName);
ImageView profileImage=(ImageView)v.findViewById(R.id.ally_image);
Button inviteBtn=(Button)v.findViewById(R.id.invite_btn);
//SHOW DATA FROM LIST
allyBean=(AllyBean)alist.get(position);
tv.setText(allyBean.getName());
photoPath=allyBean.getAvatar();
profileImage.setTag(photoPath);
imageLoader.displayImage(photoPath, ctx, profileImage, false);
inviteBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent=new Intent(ctx,AddRemoveFriendScreen.class);
//intent.putExtra("friendId", allyBean.getUserId());
ctx.startActivity(intent);
}
});
return v;
}
/*public void replaceContentView(String id, Intent newIntent) {
View view =getLocalActivityManager().startActivity(id,
newIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
.getDecorView();
this.setContentView(view);
}*/
}
Now I have to call AddRemoveFriends activtygroup.
Here is the code for activtygroup:
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ActivityGroup;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import com.tv.servercommunication.IServerResponse;
import com.tv.servercommunication.WebServiceCommunicator;
import com.tv.socialgoal.Constant;
import com.tv.socialgoal.R;
import com.tv.socialgoal.network.NetworkAvailablity;
import com.tv.task.TabViewActivity;
public class AddRemoveFriendScreen extends ActivityGroup implements OnClickListener, IServerResponse{
Button backBtn;
Button addRemoveFriendBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.friends_profile_screen);
backBtn=(Button)findViewById(R.id.back_button);
addRemoveFriendBtn=(Button)findViewById(R.id.add_remove_frnd_btn);
backBtn.setOnClickListener(this);
addRemoveFriendBtn.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.back_button:
break;
case R.id.add_remove_frnd_btn:
callAddFriend_WS();
break;
default:
break;
}
}
private Handler _handler = new Handler() {
public void dispatchMessage(Message msg) {
switch (msg.arg1) {
case Constant.PID_ADD_REMOVE_FRIEND:
if (parseResponse(msg.obj.toString()) == true) {
Intent intent = new Intent(getParent(),
TabViewActivity.class);
startActivity(intent);
} else {
runOnUiThread(new Runnable() {
public void run() {
Constant.showAlertDialog(
Constant.DIALOG_TITLE_ERROR,
"Invalid username or password.",
getParent(), false);
}
});
}
break;
default:
break;
}
}
};
// GET USER ACCESSTOCKEN AND USER ID
private boolean parseResponse(String response) {
String message = null;
JSONObject post;
boolean isUserInfoAvail = false;
try {
JSONObject postjsonObject = new JSONObject(response);
JSONObject posts = postjsonObject.getJSONObject("posts");
post = posts.getJSONObject("post");
message = post.getString("message");
if (message.equalsIgnoreCase("failure")) {
isUserInfoAvail = false;
} else {
isUserInfoAvail = true;
}
} catch (JSONException e1) {
e1.printStackTrace();
}
return isUserInfoAvail;
}
public void callAddFriend_WS() {
if (NetworkAvailablity.checkNetworkStatus(AddRemoveFriendScreen.this)) {
// PREPARE URL
Constant.methodURL = "http://admin.tvdevphp.com/goalmachine/add_friend.php";
// PREPARE REQUEST PARAMETER
ArrayList<NameValuePair> requestParaList = new ArrayList<NameValuePair>();
requestParaList.add(new BasicNameValuePair("self_user_id", "1"));
requestParaList.add(new BasicNameValuePair("user_friend_id", "2"));
// CALL WEBSERVICE
WebServiceCommunicator.getInstance().registerForServerResponse(
AddRemoveFriendScreen.this);
WebServiceCommunicator.getInstance().callGetAppWebService(
Constant.showDialog, getParent(),
Constant.methodURL, getParent(), Constant.PID_ADD_REMOVE_FRIEND,
false, requestParaList);
} else {
Constant.showAlertDialog(Constant.errorTitle,
Constant.MSG_CHECK_INTERNET_SETTING, getParent(),
false);
}
}
// SERVER RESPONSE METHOD
public void serverResponse(String response, int processid) {
Message msg = new Message();
msg.arg1 = processid;
msg.obj = response;
_handler.dispatchMessage(msg);
}
}
Please suggest me how to call activtygroup from listadapter.
Make it like this you can access everything by doing like this.
public class AddRemoveFriendScreen extends ActivityGroup implements OnClickListener, IServerResponse
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
.......
}
class AllyListAdapter extends BaseAdapter
{
//Now you can call everything from ActivityGroup
}
}
Hope this will help you.
According to the android developper reference, you may use Fragments.
ActivityGroup is deprecated. Use the new Fragment and FragmentManager APIs instead; these are also available on older platforms through the Android compatibility package.
You can try this trick.
inviteBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(ctx instanceof ActivityGroup){
Intent intent = new Intent(ctx.getParent(),AddRemoveFriendScreen.class);
//intent.putExtra("friendId", allyBean.getUserId());
ctx.getParent().startActivity(intent);
}
else{
Intent intent = new Intent(ctx,AddRemoveFriendScreen.class);
//intent.putExtra("friendId", allyBean.getUserId());
ctx.startActivity(intent);
}
}
});
If it doesn't work just use internal class for your adapter in your AddRemoveFriendScreen class.

Categories

Resources