I am trying to learn how to make a connection via a websocket in android. I am trying to use the websocket client to send a message to server and then try to view it on the screen.
I can start the application, but when I type a message and then click the send Button I receive the following error:
org.java_websocket.exceptions.WebsocketNotConnectedException
Here is my MainActivity Class:
public class MainActivity extends AppCompatActivity {
private TextView userView;
private ListView listView;
private EditText textToSend;
private Button sendButton;
private WebClient webClient;
private JSONObject jsonObject;
private URI uri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
userView = (TextView) findViewById(R.id.userView);
listView = (ListView) findViewById(R.id.listView);
textToSend = (EditText) findViewById(R.id.textToSend);
sendButton = (Button) findViewById(R.id.sendButton);
try {
uri = new URI("http://127.0.0.1:8080/chat");
} catch (URISyntaxException e) {
e.printStackTrace();
}
webClient = new WebClient(uri);
webClient.connect();
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
jsonObject = new JSONObject();
try {
jsonObject.put("message",textToSend.toString());
} catch (JSONException e) {
e.printStackTrace();
}
webClient.send(jsonObject.toString());
}
});
}
}
And here is the WebClient Class:
public class WebClient extends WebSocketClient {
public WebClient(URI serverURI) {
super(serverURI);
}
#Override
public void onOpen(ServerHandshake handshakedata) {
Log.e("Websocket", "Opened");
}
#Override
public void onMessage(String message) {
}
#Override
public void onClose(int code, String reason, boolean remote) {
}
#Override
public void onError(Exception ex) {
}
}
And this is logcat after clicking the send button:
--------- beginning of crash
10-30 20:09:50.830 2682-2682/example.com.chatapp E/AndroidRuntime: FATAL EXCEPTION: main Process: example.com.chatapp, PID: 2682
org.java_websocket.exceptions.WebsocketNotConnectedException
at org.java_websocket.WebSocketImpl.send(WebSocketImpl.java:566)
at org.java_websocket.WebSocketImpl.send(WebSocketImpl.java:543)
at org.java_websocket.client.WebSocketClient.send(WebSocketClient.java:171)
at ziad.example.com.chatapp.MainActivity$1.onClick(MainActivity.java:60)
at android.view.View.performClick(View.java:5637)
at android.view.View$PerformClick.run(View.java:22429)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Related
I'm making an app that controls esp modules and I'm using OkHttpClient to make post web requests.
You can set the ip of the esp module in the settings tab(e.g. if your esp ip is 123.456.789, the url for web request would be http://123.456.789), I'm saving, loading and getting that data from my settings activity to my main activity using sharedPrefrences, but when I open the app, it just crashes with the error url == null.
The only way I got it to work would be if I load it something like this:
public String ip = SettingsActivity.ipEsp;
but then every time I re-open the app, I have to open the setting activity for the data to be loaded.(tried saving this value with sharedPrefrences, but it doesn't seem to work, it doesn't crash or anything it just doesn't work)
I would want to have it saved in a way so whenever I re-open the app, it remembers the ip address that i set in the settings.
Here's the main activity code:
public class MainActivity extends AppCompatActivity {
Button settings;
Button send;
TextView view;
TextView see;
public String urlS;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
settings = (Button) findViewById(R.id.button);
send = (Button) findViewById(R.id.button2);
view = (TextView) findViewById(R.id.textView);
see = (TextView) findViewById(R.id.see);
SharedPreferences urls = getSharedPreferences("sPrefs", MODE_PRIVATE);
urlS = urls.getString("url", "http://0.0.0.0:8888");
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
client.newCall(requestlL).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
}
#Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()){
String myR = response.body().string();
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
see.setText(myR);
}
});
}
}
});
view.setText(urlS);
}
}
);
settings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setting();
}
});
}
OkHttpClient client = new OkHttpClient();
String urllL = urlS;
Request requestlL = new Request.Builder()
.url(urllL)
.build();
public void setting() {
Intent intent = new Intent(this, MainActivity2.class);
startActivity(intent);
}
}
and this is the setting activity code:
public class MainActivity2 extends AppCompatActivity {
private Handler sHand = new Handler();
public static final String S_PREFS = "sPrefs";
public static final String URL = "url";
Button back;
Button save;
EditText url;
public String urlS;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
back = (Button) findViewById(R.id.button3);
save = (Button) findViewById(R.id.button4);
url = (EditText) findViewById(R.id.edit);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
back();
}
});
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
urlS = url.getText().toString();
save();
}
});
load();
view();
}
public void back()
{
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
public void saveDataRunS()
{
sHand.post(saveDs);
}
private Runnable saveDs= new Runnable() {
#Override
public void run() {
save();
load();
sHand.postDelayed(this, 1);
}
};
public void save()
{
SharedPreferences sharedPreferences = getSharedPreferences("sPrefs", MODE_PRIVATE);
SharedPreferences.Editor edit = sharedPreferences.edit();
edit.putString(URL, url.getText().toString());
edit.apply();
}
public void load()
{
SharedPreferences sharedPreferences = getSharedPreferences(S_PREFS, MODE_PRIVATE);
urlS = sharedPreferences.getString(URL, "http://0.0.0.0:8888");
}
public void view()
{
url.setText(urlS);
}
}
and this is the error i get:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.test, PID: 18146
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.test/com.example.test.MainActivity}: java.lang.NullPointerException: url == null
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3222)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3437)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2041)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7386)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:980)
Caused by: java.lang.NullPointerException: url == null
at okhttp3.Request$Builder.url(Request.java:132)
at com.example.test.MainActivity.<init>(MainActivity.java:99)
at java.lang.Class.newInstance(Native Method)
at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:95)
at androidx.core.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:45)
at android.app.Instrumentation.newActivity(Instrumentation.java:1250)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3210)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3437)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2041)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7386)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:980)
#leeo6002
In MainActivity2, save() method is called in the following fashion.
onCreate -> saveDataRunS ->sHand.post(saveDs) -> save -> edit.putString(URL, url.getText().toString());
Basically, you are fetching the value from the url editText as soon as activity's onCreate is triggered. Which means you are not waiting for the user to enter the value in the EditText. At least, this is one of the issue.
Honestly, You need to clean up your code, It is a lot of mess right now.
I'm trying to implement two step verification with Firebase Auth
When user proceed to PelephoneActivity, he has a unique uuid , he get it when subscribed by email.
In the PelephoneActivity I'm trying to get also the user phone number.
I'm not really need another auth, but i don't know how to stop auth after getting sms code.
Anyway, my code is:
public class PelephoneActivity extends AppCompatActivity {
private static final String TAG = "PelephoneActivity";
private FirebaseAuth mAuth;
private DatabaseReference UsersRef;
String currentUserID;
private Spinner spinner;
private EditText editText;
private String verificationId,phoneNumber;
private ProgressBar progressBar;
private EditText editTextC;
private Button signIn;
private TextView plsWait;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pelephone);
Log.d(TAG, "onCreate: started.");
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
UsersRef = FirebaseDatabase.getInstance().getReference().child("users").child(currentUserID);
spinner = findViewById(R.id.spinnerCountries);
spinner.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, CountryData.countryNames));
editText = findViewById(R.id.editTextPhone);
//////////////////////////////////////////////
progressBar = findViewById(R.id.progressbar);
editTextC = findViewById(R.id.editTextCode);
signIn=findViewById(R.id.buttonSignIn);
editTextC.setVisibility(View.INVISIBLE);
signIn.setVisibility(View.INVISIBLE);
plsWait.setVisibility(View.INVISIBLE);
/////////////////////////////////////////////
findViewById(R.id.buttonContinue).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String code = CountryData.countryAreaCodes[spinner.getSelectedItemPosition()];
String number = editText.getText().toString().trim();
if (number.isEmpty() || number.length() < 9) {
editText.setError("Valid number is required");
editText.requestFocus();
return;
}
phoneNumber = "+" + code + number;
signIn.setVisibility(View.VISIBLE);
plsWait.setVisibility(View.VISIBLE);
}
});
findViewById(R.id.buttonSignIn).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String code = editTextC.getText().toString().trim();
if (code.isEmpty() || code.length() < 6)
{
editTextC.setError("Enter code...");
editTextC.requestFocus();
return;
}
verifyCode(code);
}
});
}
private void sendVerificationCode(String number) {
progressBar.setVisibility(View.VISIBLE);
PhoneAuthProvider.getInstance().verifyPhoneNumber(
number, //Phone number to verify
60, //timeout duration
TimeUnit.SECONDS, //unit of timeout
TaskExecutors.MAIN_THREAD, //Activity for callback binding
mCallBack //OnVerificationStateChangedCallbacks
);
}
private void verifyCode(String code) {
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, code);
signInWithCredential(credential);
}
private void signInWithCredential(PhoneAuthCredential credential) {
mAuth.signInWithCredential(credential)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
progressBar.setVisibility(View.GONE);
} else {
}
}
});
}
private PhoneAuthProvider.OnVerificationStateChangedCallbacks
mCallBack = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken forceResendingToken)
{
super.onCodeSent(s, forceResendingToken);
verificationId = s;
}
#Override
public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential)
{
String code = phoneAuthCredential.getSmsCode();
if (code != null) {
editTextC.setText(code);
verifyCode(code);
Intent intent = new Intent(PelephoneActivity.this, LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}
#Override
public void onVerificationFailed(FirebaseException e) {
Toast.makeText(PelephoneActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
}
};
}
And the error is:
--------- beginning of crash
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.blue, PID: 6726
java.lang.IllegalArgumentException: Given String is empty or null
at com.google.android.gms.common.internal.zzbo.zzcF(Unknown Source:11)
at com.google.firebase.auth.PhoneAuthCredential.<init>(Unknown Source:3)
at com.google.firebase.auth.PhoneAuthProvider.getCredential(Unknown Source:2)
at com.example.android.bluesky.SetupAccount.PelephoneActivity.verifyCode(PelephoneActivity.java:176)
at com.example.android.bluesky.SetupAccount.PelephoneActivity.access$900(PelephoneActivity.java:52)
at com.example.android.bluesky.SetupAccount.PelephoneActivity$2.onClick(PelephoneActivity.java:150)
at android.view.View.performClick(View.java:6597)
at android.view.View.performClickInternal(View.java:6574)
at android.view.View.access$3100(View.java:778)
at android.view.View$PerformClick.run(View.java:25885)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
The database structure is:
Any ideas how to solve it?
I am trying to access a class in another class and i can getting this error. I am using sinch to implement app to app phone call in my application and it is still not working.
This is my error
FATAL EXCEPTION: main
Process: com.example.thinker.myapplication2, PID: 10039
java.lang.NullPointerException: Attempt to invoke virtual method 'com.sinch.android.rtc.calling.Call com.example.thinker.myapplication2.SinchService$SinchServiceInterface.callUser(java.lang.String)' on a null object reference
at com.example.thinker.myapplication2.tabs.Chatting$Bases.callButtonClicked(Chatting.java:128)
at com.example.thinker.myapplication2.tabs.Chatting$1.onClick(Chatting.java:83)
at android.view.View.performClick(View.java:5265)
at android.view.View$PerformClick.run(View.java:21534)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5683)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
This is my java class.
public class Chatting extends ListActivity {
Runnable refresh, refres;
ImageView send,back,call;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.yon);
call= (ImageView)findViewById(R.id.call);
call.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if (!isOnline(Chatting.this)) {
Toast.makeText(Chatting.this, "No network connection",
Toast.LENGTH_SHORT).show();
return;
}
Bases ba = new Bases();
ba.onServiceConnected();
ba.callButtonClicked();
}
});
}
public class Bases extends BaseActivity {
#Override
protected void onServiceConnected() {
Toast.makeText(this, " call ready", Toast.LENGTH_LONG).show();
}
public void callButtonClicked() {
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(this);
String emaill = sp.getString("friend_email", "anon");
if (emaill.isEmpty()) {
Toast.makeText(this, "Please enter a user to call", Toast.LENGTH_LONG).show();
return;
}
try {
Call call = getSinchServiceInterface().callUser("emaill");
if (call == null) {
// Service failed for some reason, show a Toast and abort
Toast.makeText(this, "Service is not started. Try stopping the service and starting it again before "
+ "placing a call.", Toast.LENGTH_LONG).show();
return;
}
String callId = call.getCallId();
Intent callScreen = new Intent(this, CallScreenActivity.class);
callScreen.putExtra(SinchService.CALL_ID, callId);
startActivity(callScreen);
} catch (MissingPermissionException e) {
ActivityCompat.requestPermissions(this, new String[]{e.getRequiredPermission()}, 0);
}
}
}
}
below is the baseactivity class that has the getSinchServiceInterface(). that is returning null
public abstract class BaseActivity extends Activity implements ServiceConnection {
private SinchService.SinchServiceInterface mSinchServiceInterface;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getApplicationContext().bindService(new Intent(this, SinchService.class), this,
BIND_AUTO_CREATE);
}
#Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
if (SinchService.class.getName().equals(componentName.getClassName())) {
mSinchServiceInterface = (SinchService.SinchServiceInterface) iBinder;
onServiceConnected();
}
}
#Override
public void onServiceDisconnected(ComponentName componentName) {
if (SinchService.class.getName().equals(componentName.getClassName())) {
mSinchServiceInterface = null;
onServiceDisconnected();
}
}
protected void onServiceConnected() {
// for subclasses
}
protected void onServiceDisconnected() {
// for subclasses
}
protected SinchService.SinchServiceInterface getSinchServiceInterface() {
return mSinchServiceInterface;
}
}
Most of time this happen when someone use wrong way to pass context try to pass context as YourActivityName.this (eg Bases.this )rather than just this or getApplicationContext()
start with
#Override
protected void onServiceConnected() {
Toast.makeText(Bases.this, " call ready", Toast.LENGTH_LONG).show();
}
this is not the proper method to call activity
Bases ba = new Bases();
ba.onServiceConnected();
ba.callButtonClicked();
use
Intent intent = new Intent(YourCurrentActivityName.this,Bases.class);
startActivity(intent);
in the oncreate method you can call this methods callButtonClicked()
I have made a class LocationFinder which gets the user's location.
I am instantiating the class and class and calling required methods to get the location.
Now after the location is found in LocationFinder class, I want to communicate with my MainActivity so that I can update the user's location on some TextView.
To do so, I have done this:
The constructor of my LocationFinder class looks like:
private Context context;
private OnLocationFoundListener onLocationFoundListener;
public LocationFinder(Context context) {
this.context = context;
onLocationFoundListener = (OnLocationFoundListener) context; // here is the exception is thrown
}
Where OnLocationFoundListener is an interface like:
public interface OnLocationFoundListener
{
void setOnLocationFoundListener(String cityName, String stateName, String countryName);
}
After this on successful location found I am using onLocationFoundListener.setOnLocationFoundListener(cityName, stateName, countryName); to notify the MainActivity where I'm implementing the OnLocationFoundListener and overriding the required method.
The code sample is:
The LocationFinder class:
public class LocationFinder implements LocationListener {
private Context context;
private OnLocationFoundListener onLocationFoundListener;
public LocationFinder(Context context) {
this.context = context;
onLocationFoundListener = (OnLocationFoundListener) context;
}
private static final int MY_PERMISSIONS_ACCESS_FINE_LOCATION = 1;
private LocationManager locationManager;
private ProgressDialog progressDialog;
void getCityByLocation() {
locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale((Activity)context,
Manifest.permission.ACCESS_FINE_LOCATION)) {
// Explanation not needed, since user requests this himself
} else {
ActivityCompat.requestPermissions((Activity)context,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_ACCESS_FINE_LOCATION);
}
} else if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER) ||
locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
progressDialog = new ProgressDialog(context);
progressDialog.setMessage(context.getString(R.string.getting_location));
progressDialog.setCancelable(false);
progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, context.getString(R.string.dialog_cancel), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
try {
locationManager.removeUpdates(LocationFinder.this);
} catch (SecurityException e) {
e.printStackTrace();
}
}
});
progressDialog.show();
if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
}
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
} else {
showLocationSettingsDialog();
}
}
#Override
public void onLocationChanged(Location location) {
progressDialog.hide();
try {
locationManager.removeUpdates(this);
} catch (SecurityException e) {
Log.e("LocationManager", "Error while trying to stop listening for location updates. This is probably a permissions issue", e);
}
Log.i("LOCATION (" + location.getProvider().toUpperCase() + ")", location.getLatitude() + ", " + location.getLongitude());
double latitude = location.getLatitude();
double longitude = location.getLongitude();
getCityDetails(latitude, longitude);
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
private void getCityDetails(double lat, double lon)
{
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(lat, lon, 1);
} catch (IOException e) {
e.printStackTrace();
}
String cityName = addresses.get(0).getAddressLine(0);
String stateName = addresses.get(0).getAddressLine(1);
String countryName = addresses.get(0).getAddressLine(2);
progressDialog.dismiss();
onLocationFoundListener.setOnLocationFoundListener(cityName, stateName, countryName);
}
private void showLocationSettingsDialog() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle(R.string.location_settings);
alertDialog.setMessage(R.string.location_settings_message);
alertDialog.setPositiveButton(R.string.location_settings_button, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(intent);
}
});
alertDialog.setNegativeButton(R.string.dialog_cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
public interface OnLocationFoundListener
{
void setOnLocationFoundListener(String cityName, String stateName, String countryName);
}
}
The MainActivity :
public class MainActivity extends AppCompatActivity implements LocationFinder.OnLocationFoundListener {
Button getCurrentLocation;
TextView locationTextview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getCurrentLocation = (Button) findViewById(R.id.getCurrentCity);
locationTextview = (TextView) findViewById(R.id.current_city);
LocationFinder locationFinder = new LocationFinder(getApplicationContext());
locationFinder.getCityByLocation();
}
#Override
public void setOnLocationFoundListener(String cityName, String stateName, String countryName) {
locationTextview.setText("City : "+cityName+", "+"\nState : "+stateName+", "+"\nCountry : "+countryName);
}
}
Logcat:
Process: com.amitupadhyay.citybasedlocation, PID: 18474
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.amitupadhyay.citybasedlocation/com.amitupadhyay.citybasedlocation.MainActivity}:
java.lang.ClassCastException: android.app.Application cannot be cast
to
com.amitupadhyay.citybasedlocation.LocationFinder$OnLocationFoundListener
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2456)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2523)
at android.app.ActivityThread.access$900(ActivityThread.java:168)
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1373)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5609)
at java.lang.reflect.Method.invoke(Native Method)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:797)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:687)
Caused by: java.lang.ClassCastException: android.app.Application
cannot be cast to
com.amitupadhyay.citybasedlocation.LocationFinder$OnLocationFoundListener
at
com.amitupadhyay.citybasedlocation.LocationFinder.(LocationFinder.java:38)
at
com.amitupadhyay.citybasedlocation.MainActivity.onCreate(MainActivity.java:21)
at android.app.Activity.performCreate(Activity.java:6307)
at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2409)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2523)
at android.app.ActivityThread.access$900(ActivityThread.java:168)
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1373)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5609)
at java.lang.reflect.Method.invoke(Native Method)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:797)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:687)
I don't understand why is this happening?
try passing this as context instead of application context.
LocationFinder locationFinder = new LocationFinder(this);
locationFinder.getCityByLocation();
EDIT That is exactly what your logcat says. You are trying to pass a application context to activity.
Change it like following,
public LocationFinder(Context context, OnLocationFoundListener listener) {
this.context = context;
onLocationFoundListener = listener;
}
And from Activity, initiate it like this,
LocationFinder locationFinder = new LocationFinder(getApplicationContext(), this);
You Should Change OnLocationFoundListener Context parameter in constructor with OnLocationFoundListener
public LocationFinder(OnLocationFoundListener context) {
this.context = context;
onLocationFoundListener = context; // here is the exception is thrown
}
And You should pass
MainActvity.this.
LocationFinder locationFinder = new LocationFinder(MainActvity.this);
I'm creating an app in Android using Socket.IO. I am stuck at the Login itself. Here is my code for Login
public class MainActivity extends AppCompatActivity {
EditText uname_et, pwd_et;
Button log;
String username, password;
private Socket mSocket;
private Emitter.Listener onLogin = new Emitter.Listener() {
#Override
public void call(Object... args) {
Log.e(args[0].toString(), "data");
Log.w("yes ", "in evtLogin");
// JSONObject data = (JSONObject) args[0];
}
};
{
try {
String URL = "http://MYIP:8081";
mSocket = IO.socket(URL);
} catch (URISyntaxException e1) {
e1.printStackTrace();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
uname_et = (EditText) findViewById(R.id.username_input);
pwd_et = (EditText) findViewById(R.id.pwd);
log = (Button) findViewById(R.id.sign_in_button);
log.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
signin();
}
});
mSocket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {
#Override
public void call(Object... args) {
Log.i("Make Emit", "Emit");
Log.w(mSocket.connected() + " - ", "Connection status");
}
});
mSocket.on("evtLogin", onLogin);
mSocket.connect();
}
private void signin() {
username = uname_et.getText().toString();
password = pwd_et.getText().toString();
mSocket.emit("userName", username);
mSocket.emit("Password", password);
}
#Override
protected void onDestroy() {
super.onDestroy();
mSocket.off("evtLogin", onLogin);
}
}
I'm not sure that socket is even connected or not, I'm gettong logs from Socket.EVENT_CONNECT
08-31 12:22:22.062 13399-13441/com.fis.kotsocket I/Make Emit﹕ Emit
08-31 12:22:22.063 13399-13441/com.fis.kotsocket W/true -﹕ Connection status
But onLogin listener is not called.
As a newbie I am not sure what to do exactly.
js code
//code for login event
socket.on('evtLogin', function (loginData) {
console.log('loged');
User.findOne({'login.userName':loginData.userName,'login.password':loginData.password},function(err,user){
if(err){throw err;}
else {if(!user){
console.log('not a authenticated user');
}
else
{
var userType;
User.find({'login.userName':loginData.userName,'login.password':loginData.password},function(err,rslt){
if(err){throw err;}
else
{
userType = JSON.stringify(rslt[0]['userType'].userId);
socket.emit('evtUserType',userType);
}
})
}
}
});
console.log('done');
});
Your socket is not getting initialized.
Try this initialization:
private Socket mSocket;
{
try {
mSocket = IO.socket("enter url here");
} catch (URISyntaxException e) {}
}
Or it might be that you are not emitting the evtLogin event from your javascript code.