Skip to content

Commit

Permalink
create function which migrates JSON data to Firebase
Browse files Browse the repository at this point in the history
  • Loading branch information
Julesssss committed Feb 26, 2018
1 parent 5420c00 commit 3f1cc16
Show file tree
Hide file tree
Showing 3 changed files with 130 additions and 15 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,18 @@ package website.julianrosser.birthdays.activities

import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.preference.PreferenceManager
import android.support.design.widget.Snackbar
import android.util.Log
import com.google.android.gms.analytics.GoogleAnalytics
import com.google.android.gms.analytics.HitBuilders
import com.google.android.gms.analytics.Tracker
import com.google.firebase.auth.FirebaseUser
import kotlinx.android.synthetic.main.activity_welcome.*
import website.julianrosser.birthdays.Preferences
import website.julianrosser.birthdays.R
import website.julianrosser.birthdays.database.DatabaseHelper

class WelcomeActivity : GoogleSignInActivity() {

Expand All @@ -19,7 +22,7 @@ class WelcomeActivity : GoogleSignInActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)

if (Preferences.shouldShowWelcomeScreen(this)) {
// if (Preferences.shouldShowWelcomeScreen(this)) {

setTheme()
setContentView(R.layout.activity_welcome)
Expand All @@ -29,36 +32,59 @@ class WelcomeActivity : GoogleSignInActivity() {

mTracker = getDefaultTracker()

} else {
startActivity(Intent(applicationContext, BirthdayListActivity::class.java))
finish()
}
// } else {
// startActivity(Intent(applicationContext, BirthdayListActivity::class.java))
// finish()
// }
}

private fun setUpSignInButton() {
setUpGoogleSignInButton(welcomeButtonGoogleSignIn, object : GoogleSignInListener {

override fun onLogin(firebaseUser: FirebaseUser) {
Snackbar.make(welcomeButtonGoogleSignIn, "Already signed in, GOTO main activity", Snackbar.LENGTH_SHORT).show()
startActivity(Intent(applicationContext, BirthdayListActivity::class.java))
mTracker?.send(HitBuilders.EventBuilder()
.setCategory("Action")
.setAction("Welcome--Logged In")
.build())
Preferences.setShouldShowWelcomeScreen(applicationContext, false)
finish()

// TODO: JSON data exists ONLY ONCE!!!!!!!!!
if (true) {
migratejsonBirthdays(firebaseUser)
} else {
handleLogin()
}
}

override fun onGoogleFailure(message: String) {
Snackbar.make(welcomeButtonGoogleSignIn, "onGoogleFailure: $message", Snackbar.LENGTH_SHORT).show()
Log.i(javaClass.simpleName, "onGoogleFailure: $message")
}

override fun onFirebaseFailure(message: String) {
Snackbar.make(welcomeButtonGoogleSignIn, "New or signed out user: $message", Snackbar.LENGTH_SHORT).show()
Log.i(javaClass.simpleName, "New or signed out user: $message")
}
})
}

private fun migratejsonBirthdays(firebaseUser: FirebaseUser) {
DatabaseHelper().migrateJsonToFirebase(applicationContext, firebaseUser, object : DatabaseHelper.MigrateUsersCallback {
override fun onSuccess(migratedCount: Int) {
Snackbar.make(welcomeButtonGoogleSignIn, "Migrated $migratedCount users!", Snackbar.LENGTH_SHORT).show()
handleLogin()
}

override fun onFailure(message: String?) {
Snackbar.make(welcomeButtonGoogleSignIn, "ERROR migrating: $message", Snackbar.LENGTH_SHORT).show()
handleLogin()
}
})
}

private fun handleLogin() {
startActivity(Intent(applicationContext, BirthdayListActivity::class.java))
mTracker?.send(HitBuilders.EventBuilder()
.setCategory("Action")
.setAction("Welcome--Logged In")
.build())
Preferences.setShouldShowWelcomeScreen(applicationContext, false)
finish()
}

private fun onContinueClicked() {
startActivity(Intent(this, BirthdayListActivity::class.java))
Preferences.setShouldShowWelcomeScreen(this, false)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
import website.julianrosser.birthdays.BirthdayReminder;
import website.julianrosser.birthdays.Constants;
import website.julianrosser.birthdays.Preferences;
import website.julianrosser.birthdays.R;
import website.julianrosser.birthdays.Utils;
import website.julianrosser.birthdays.model.Birthday;
import website.julianrosser.birthdays.model.FirebaseBirthday;
Expand Down Expand Up @@ -123,6 +124,93 @@ private static void setLastUpdatedTime() {
}
}

public interface MigrateUsersCallback {
void onSuccess(int migratedCount);
void onFailure(String message);
}

public void migrateJsonToFirebase(Context context, FirebaseUser user, MigrateUsersCallback callback) {
Log.i("Migration", "starting migration");

if (user == null || Utils.isStringEmpty(user.getUid())) {
Log.i("Migration", "User null or empty");
return;
}

ArrayList<Birthday> jsonbirthdays = new ArrayList();
try {
jsonbirthdays = loadJSONData(context);
} catch (FileNotFoundException e) {
// Ignore this one; it happens when starting fresh
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
callback.onFailure(e.getMessage());
} catch (Exception e) {
e.printStackTrace();
callback.onFailure(e.getMessage());
}

Log.i("Migration", "Past execption checks");

if (jsonbirthdays.size() > 0) {
Log.i("Migration", "Found JSON birthdays!");

// Get Firebase Database reference
DatabaseReference databaseReference;
for (Birthday jsonBirthday : jsonbirthdays) {

Log.i("Migration", "for birthday: " + jsonBirthday.getName());

// Update database ref
databaseReference = BirthdayReminder.getInstance().getDatabaseReference().child(user.getUid()).child(Constants.TABLE_BIRTHDAYS)
.child(String.valueOf(jsonBirthday.getUID()));

// Convert to Firebase birthday
FirebaseBirthday firebaseBirthday = FirebaseBirthday.convertToFirebaseBirthday(jsonBirthday);

// Save to Firebase
databaseReference.setValue(firebaseBirthday);
Log.i("Migration", "Saved to FIREBASE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
}

setLastUpdatedTime();
callback.onSuccess(jsonbirthdays.size());

} else {
callback.onFailure(context.getString(R.string.error_no_json_birthdays));
}
}

private ArrayList<Birthday> loadJSONData(Context context) throws Exception {
ArrayList<Birthday> birthdays = new ArrayList<>();
// Load birthdays
BufferedReader reader = null;
try {
// Open and read the file into a StringBuilder
InputStream in = context.openFileInput(Constants.FILENAME);
reader = new BufferedReader(new InputStreamReader(in));
StringBuilder jsonString = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
// Line breaks are omitted and irrelevant
jsonString.append(line);
}
// Parse the JSON using JSONTokener
JSONArray array = (JSONArray) new JSONTokener(jsonString.toString())
.nextValue();

// Build the array of birthdays from JSONObjects
for (int i = 0; i < array.length(); i++) {
birthdays.add(new Birthday(array.getJSONObject(i)));
}
} finally {
if (reader != null) reader.close();
}
return birthdays;
}

private static void saveJSONChange(Birthday birthday, Update state) throws IOException {
ArrayList<Birthday> birthdays = new ArrayList<>();
Context context = BirthdayReminder.getInstance();
Expand Down
1 change: 1 addition & 0 deletions app/src/main/res/values/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,7 @@
<string name="title_log_out">Log Out</string>
<string name="welcome_text_message">You can now sign into your Google account. This will automatically backup your birthdays and allow you to see your birthdays on any other device after signing in.\n\nIf you want to continue using the app without backing up your birthdays, click continue.</string>
<string name="error_google_login">Error while logging in</string>
<string name="error_no_json_birthdays">No JSON birthdays found!</string>


</resources>

0 comments on commit 3f1cc16

Please sign in to comment.