JavaFX With Connection To Firebase On Raspberry Pi System - java

I am running JavaFX jar file on Windows system and my code includes connection to Firebase. I make the connection to the firebase through the following code:
public void start(Stage primaryStage) throws Exception {
System.out.println("Connecting FireBase...");
// Initialize the app with a service account, granting admin privileges
FirebaseOptions options = null;
try {
options = new FirebaseOptions.Builder()
.setCredential(FirebaseCredentials.fromCertificate(getServiceAccount(<path-to-json-file>)))
.setDatabaseUrl("https://<firebase-name>.firebaseio.com")
.build();
} catch (IOException e) {
e.printStackTrace();
}
FirebaseApp.initializeApp(options);
System.out.println("Connecting to FireBase and initializing...");
// check if the connection succedded
DatabaseReference connectedRef =
FirebaseDatabase.getInstance().getReference(".info/connected");
connectedRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
boolean connected = snapshot.getValue(Boolean.class);
if (connected) {
System.out.println("Connected to firebase!");
} else {
System.out.println("Not connected to firebase...");
}
}
#Override
public void onCancelled(DatabaseError error) {
System.err.println("Listener was cancelled");
}
});
System.out.println("Get a reference to the firebase db...");
// Get a reference to our posts
final FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference("server/<path>");
// rest of the code ...
}
Eventually, I get the following output:
Connected to firebase!
Now I have to run the same jar file on Raspberry Pi system. When I execute the jar on Raspberry Pi, the console outputs the following:
Not connected to firebase...
and there is no exceptions.
Is there any way to check what is the reason of no connection to firebase from Raspberry Pi system?
How to resolve this problem?

Related

Save a wifi network connection (password) with WifiNetworkSpecifier? Android

Recently i discovered that the implementation to connect to a Wifi in Android is deprecated for Android 10 or above and I'm trying to fix my application using WifiNetworkSpecifier. But I notice the WifiNetworkSpecifier do not save the network connection and just stay connected while the application is running and when it's closed, the wifi is disconnected and do not save the password.
I'm using this code:
private void connectByWifiNetworkSpecifier(String wifiSsid, String pass) {
Log.d(TAG, "connectByWifiNetworkSpecifier: wifi=" + wifiSsid + ", pass=" + pass);
connectivityManager = (ConnectivityManager) context.getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
WifiNetworkSpecifier.Builder specifierBuilder = new WifiNetworkSpecifier.Builder()
.setSsid(wifiSsid)
.setWpa2Passphrase(pass);
NetworkRequest request = new NetworkRequest.Builder()
.addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
.removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
.setNetworkSpecifier(specifierBuilder.build())
.build();
networkCallback = new ConnectivityManager.NetworkCallback() {
#Override
public void onAvailable(Network network) {
super.onAvailable(network);
Log.d(TAG, "onAvailable: network=" + network);
// do success processing here..
connectivityManager.bindProcessToNetwork(network);
}
#Override
public void onUnavailable() {
super.onUnavailable();
Log.d(TAG, "onUnavailable: ");
// do failure processing here..
}
};
connectivityManager.requestNetwork(request, networkCallback);
}
Have it any way to save the connection "permanently" (without me having to connect all the time and always put the password) using WifiNetworkSpecifier or another API?
.

Cleaning local data from realtime-database remotely or after consecutive crashes

My realtime-database has data persistence for offline use and recently a recording error recorded a String as HashMap and consequently the application crashed for all my clients. I quickly corrected the error, but now all clients can no longer open the application, as it loads offline before online and ends up slowing down the error and closing the application for all users, or a good part of them.
I'm instructing them to do data wiping manually, but this is a big problem for me and I need to find a way to force this data wiping of all users remotely or predict in the application that when there are some crashes it will clear the local data automatically.
Any code suggestions or how can I do this?
I solve this problem with an try/catch, like code below:
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
try {
User user = dataSnapshot.getValue(User.class); // error occurs here
//... some code ...//
} catch (DatabaseException databaseException) {
Log.e(TAG, "DatabaseException ****** The read failed: " + databaseException);
clearPreferences(context.getApplicationContext());
deleteCache(context.getApplicationContext());
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) { Log.e(TAG, "onCancelled ****** The read failed: " + databaseError); }
public static void clearPreferences(Context context) {
try {
// clearing app data
Runtime runtime = Runtime.getRuntime();
runtime.exec("pm clear "+context.getPackageName());
} catch (Exception e) {
e.printStackTrace();
}
}
public static void deleteCache(Context context) {
try {
File dir = context.getCacheDir();
deleteDir(dir);
} catch (Exception ignored) {}
}

Firebase : How to log the full reference on read/write error

I'm trying to connect to another database on an Android App, and can't seem to see if I've successfully init the secondary database.
How I'm instantiating the second one.
public void initFirebase() {
//init the default db;
FirebaseApp.initializeApp(this);
//init the second db;
FirebaseOptions.Builder builder = new FirebaseOptions.Builder();
builder.setApplicationId("id");
builder.setApiKey("key");
builder.setDatabaseUrl("https://second-db.firebaseio.com");
try {
FirebaseApp.initializeApp(this, builder.build(), "second-db");
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
Then I try to read something here.
public static DatabaseReference getSecondDbRef(String child) {
FirebaseApp app = FirebaseApp.getInstance("second-db");
return FirebaseDatabase.getInstance(app).getReference(child);
}
Then this fails with some: Listen at /child/child/child/teams failed: DatabaseError: Permission denied, though I've allowed access at this location and can confirm with the rules simulator that this node can be read.
Is there a way to have this log: Listen to second-db/child/child/child/teams failed ..., notice the prefix second-db.

Connection refused when calling endpoints from android client

My android app uses google endpoints as a scalable backend solution. However, I am having trouble calling it from the android client.
I call an async task class from an activity and in the async task class call the endpoints method. In this case the default sayHi() method is called and the message should be displayed in a toast using the onPostExecute(String result) method.
However when I run the app module in the emulator, this error appears in the toast:
failed to connect to /10.0.2.2 (port 8080) after 20000ms: isConnected failed: ECONNREFUSED (Connection refused)
Here is the code that calls the async task from the activity:
Profile profile = new Profile(firstName, lastName, birthday);
new EndpointTask(). new SaveProfileTask(profile, this).execute();
Here is the async task class:
public class EndpointTask {
public class SaveProfileTask extends AsyncTask<Void, Void, String> {
private final String LOG_TAG = SaveProfileTask.class.getSimpleName();
private MyApi mApi;
private Profile mProfile;
private Context mContext;
public SaveProfileTask(Profile profile, Context context) {
mProfile = profile;
mContext = context;
}
#Override
protected String doInBackground(Void... params) {
if (mApi == null) {
MyApi.Builder builder = new MyApi.Builder(AndroidHttp.newCompatibleTransport(),
new AndroidJsonFactory(), null)
// options for running against local devappserver
// - 10.0.2.2 is localhost's IP address in Android emulator
// - turn off compression when running against local devappserver
.setRootUrl("http://10.0.2.2:8080/_ah/api/")
.setGoogleClientRequestInitializer(new GoogleClientRequestInitializer() {
#Override
public void initialize(AbstractGoogleClientRequest<?> abstractGoogleClientRequest) throws IOException {
abstractGoogleClientRequest.setDisableGZipContent(true);
}
});
mApi = builder.build();
}
try {
return mApi.sayHi(mProfile.getFirstName()).execute().getData();
} catch (IOException e) {
return e.getMessage();
}
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(mContext, result, Toast.LENGTH_LONG).show();
Log.d(LOG_TAG, "ERROR: " + result);
}
}
}
Most of this is taken from the github repo here. Which is part of the official android documentation for hooking up the client with the backend for google app engine.
Why is this error occurring and how can it be fixed?
Thanks guys, happy coding.

Google Cloud Endpoints Setup Trouble

I'm completely new to Google's Cloud Platform and I'm having trouble setting it up for my Android device. I am attempting to follow this tutorial and I'm at the point of trying to test my backend with my Android Emulator. The emulator, however, gives me this message after 20 seconds, Where instead it should say my name. Here's my code so far:
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
buildUI();
new EndpointsAsyncTask().execute(new Pair<Context, String>(this, "Solomon"));
}
EndpointsAsyncTask.java
public class EndpointsAsyncTask extends AsyncTask<Pair<Context, String>, Void, String> {
private static MyApi myApiService = null;
private Context context;
#Override
protected String doInBackground(Pair<Context, String>... params) {
if(myApiService == null) { // Only do this once
MyApi.Builder builder = new MyApi.Builder(AndroidHttp.newCompatibleTransport(),
new AndroidJsonFactory(), null)
// options for running against local devappserver
// - 10.0.2.2 is localhost's IP address in Android emulator
// - turn off compression when running against local devappserver
.setRootUrl("http://10.0.2.2:8080/_ah/api/")
.setGoogleClientRequestInitializer(new GoogleClientRequestInitializer() {
#Override
public void initialize(AbstractGoogleClientRequest<?> abstractGoogleClientRequest) throws IOException {
abstractGoogleClientRequest.setDisableGZipContent(true);
}
});
// end options for devappserver
myApiService = builder.build();
}
context = params[0].first;
String name = params[0].second;
try {
return myApiService.sayHi(name).execute().getData();
} catch (IOException e) {
return e.getMessage();
}
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(context, result, Toast.LENGTH_LONG).show();
}
}
All Help is appreciated!
EDIT: Part of the problem was that I was running Endpoints Backend rather than the App Engine Servlet Backend. But now I'm now getting "connection refused" and I am running the App Engine Servlet Backend. Any Ideas?
After a tough few days, i found that the problem was that I needed to change my rootUrl from http://10.0.2.2:8080/_ah/api/ to my appspot domain. Now I'm getting the Hello World message.

Categories

Resources