how to set Firebase Context to use database - android

i have just added firebase database to my app, when the activity is called (after user logs in) i get fatal error
ProfileActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.firebase.client.Firebase;
import com.google.firebase.FirebaseApp;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class ProfileActivity extends AppCompatActivity implements View.OnClickListener {
//firebase auth object
private FirebaseAuth firebaseAuth;
private Firebase firebase;
//view objects
private TextView textViewUserEmail;
private TextView emailText;
private Button buttonLogout,button2;
private EditText nameEdit, ageEdit;
private DatabaseReference mRootRef;
private Firebase myFirebaseRef = new Firebase("https://********************.com");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Previous versions of Firebase
firebase.setAndroidContext(this);
//Newer version of Firebase
if(!FirebaseApp.getApps(this).isEmpty()) {
FirebaseDatabase.getInstance().setPersistenceEnabled(true);
}
// remove title
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_profile);
//initializing firebase authentication object
firebaseAuth = FirebaseAuth.getInstance();
//if the user is not logged in
//that means current user will return null
if(firebaseAuth.getCurrentUser() == null){
//closing this activity
finish();
//starting login activity
startActivity(new Intent(this, LoginActivity.class));
}
//getting current user
FirebaseUser user = firebaseAuth.getCurrentUser();
//initializing views
textViewUserEmail = (TextView) findViewById(R.id.textViewProfile);
emailText = (TextView) findViewById(R.id.emailEditText);
nameEdit = (EditText) findViewById(R.id.entername);
ageEdit = (EditText) findViewById(R.id.ageedit);
buttonLogout = (Button) findViewById(R.id.buttonLogout);
button2 = (Button) findViewById(R.id.button2);
mRootRef = FirebaseDatabase.getInstance().getReference();
//displaying logged in user name
textViewUserEmail.setText("Welcome To Your Profile");
emailText.setText(user.getEmail());
//adding listener to button
buttonLogout.setOnClickListener(this);
button2.setOnClickListener(this);
}
#Override
public void onClick(View view) {
//if logout is pressed
if(view == buttonLogout){
//logging out the user
firebaseAuth.signOut();
//closing activity
finish();
//starting login activity
startActivity(new Intent(this, LoginActivity.class));
}
if (view == button2) {
myFirebaseRef.setValue(nameEdit.getText().toString());
myFirebaseRef.setValue(ageEdit.getText().toString());
finish();
startActivity(new Intent(this, Main2Activity.class));
}
}
}
Exception thrown is:
12-07 12:42:41.855 26718-26718/com.vb.myapplication E/AndroidRuntime:
FATAL EXCEPTION: main
Process: com.vb.myapplication, PID: 26718
java.lang.RuntimeException: Unable to instantiate activity
ComponentInfo{com.vb.myapplication/com.vb.food4thought.ProfileActivity}:
java.lang.RuntimeException: You need to set the Android context using
Firebase.setAndroidContext() before using Firebase.
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3094)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3350)
at android.app.ActivityThread.access$1100(ActivityThread.java:222)
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1795)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7229)
at java.lang.reflect.Method.invoke(Native Method)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Caused by: java.lang.RuntimeException: You need to set the Android
context using Firebase.setAndroidContext() before using Firebase.
at com.firebase.client.core.Context.getPlatform(Context.java:45)
at com.firebase.client.core.Context.ensureLogger(Context.java:218)
at com.firebase.client.core.Context.initServices(Context.java:105)
at com.firebase.client.core.Context.freeze(Context.java:92)
at
com.firebase.client.core.RepoManager.getLocalRepo(RepoManager.java:55)
at com.firebase.client.core.RepoManager.getRepo(RepoManager.java:19)
at com.firebase.client.Firebase.(Firebase.java:172)
at com.firebase.client.Firebase.(Firebase.java:177)
at com.firebase.client.Firebase.(Firebase.java:155)
at com.vb.food4thought.ProfileActivity.(ProfileActivity.java:32)
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1095)
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3084)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3350) 
at android.app.ActivityThread.access$1100(ActivityThread.java:222) 
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1795) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:158) 
at android.app.ActivityThread.main(ActivityThread.java:7229) 
at java.lang.reflect.Method.invoke(Native Method) 
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
I dont know what im doing wrong. Any help very much appreciated.
Thankyou.

for either new or old version you need to first set
Firebase.setAndroidContext(getApplicationContext());
then you can move for enabling or disabling persistance

Related

Android studio creating a settings page

I am slightly new to Android studio and have the following code for a settings page using a fragment. I used a settingsFragment and settingsActivity to create the settings page. I also created a button in the mainActivity that should take me to the settings page. But whenever I run it, the app just closes. Im not sure how to fix this. Could somebody please take a look?
MainActivity.java:
package com.example.settingspagecs309;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toolbar;
public class MainActivity extends AppCompatActivity {
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button=(Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openSettingsActivity();
}
});
}
public void openSettingsActivity(){
Intent intent=new Intent(this,SettingsActivity.class);
startActivity(intent);
}
}
ActivityMain.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Open settings"/>
</RelativeLayout>
SettingsFragment.java:
package com.example.settingspagecs309;
import android.content.Intent;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.preference.PreferenceFragmentCompat;
import androidx.preference.Preference;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class SettingsFragment extends PreferenceFragmentCompat {
#Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
setPreferencesFromResource(R.xml.preferences,rootKey);
Preference myPref= (Preference) findPreference("Contact_Preference");
myPref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
startActivity(new Intent(getContext(),MainActivity.class));
return true;
}
});
}
}
SettingsActivity.java:
package com.example.settingspagecs309;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
public class SettingsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportFragmentManager().beginTransaction().replace(android.R.id.content,new SettingsFragment()).commit();
ActionBar menu=getSupportActionBar();
menu.setDisplayShowHomeEnabled(true);
menu.setDisplayShowHomeEnabled(true);
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
}
This is the error message it is showing:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.settingspagecs309, PID: 29462
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.settingspagecs309/com.example.settingspagecs309.SettingsActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.preference.Preference.setOnPreferenceClickListener(androidx.preference.Preference$OnPreferenceClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2452)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2535)
at android.app.ActivityThread.access$900(ActivityThread.java:155)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1380)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:152)
at android.app.ActivityThread.main(ActivityThread.java:5497)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.preference.Preference.setOnPreferenceClickListener(androidx.preference.Preference$OnPreferenceClickListener)' on a null object reference
at com.example.settingspagecs309.SettingsFragment.onCreatePreferences(SettingsFragment.java:22)
at androidx.preference.PreferenceFragmentCompat.onCreate(PreferenceFragmentCompat.java:228)
at androidx.fragment.app.Fragment.performCreate(Fragment.java:2949)
at androidx.fragment.app.FragmentStateManager.create(FragmentStateManager.java:475)
at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:278)
at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:2189)
at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:2100)
at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:2002)
at androidx.fragment.app.FragmentManager.dispatchStateChange(FragmentManager.java:3138)
at androidx.fragment.app.FragmentManager.dispatchActivityCreated(FragmentManager.java:3072)
at androidx.fragment.app.FragmentController.dispatchActivityCreated(FragmentController.java:251)
at androidx.fragment.app.FragmentActivity.onStart(FragmentActivity.java:502)
at androidx.appcompat.app.AppCompatActivity.onStart(AppCompatActivity.java:246)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1277)
at android.app.Activity.performStart(Activity.java:6306)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2415)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2535) 
at android.app.ActivityThread.access$900(ActivityThread.java:155) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1380) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:152) 
at android.app.ActivityThread.main(ActivityThread.java:5497) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
D/AppTracker: App Event: crash
I/Process: Sending signal. PID: 29462 SIG: 9

Android dynamic buttons and checkbox getting id0x0 on rotate

I found the following Android sample app to create a scrollview with checkbox and buttons, everything work great except when I switch or rotate to landscape mode, it crashes with:
Caused by: java.lang.IllegalArgumentException: Wrong state class, expecting View State but received class android.widget.CompoundButton$SavedState instead. This usually happens when two views of different type have the same id in the same hierarchy. This view's id is id/0x0. Make sure other views do not use the same id.
Does rotating the app caused it use the same ids in the for statement?
can I release the setid (if that is the problem before reassigning)
And how could I save the state of checkbox when I rotate?
Sample Code:
package life.poa.webcastman.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.Toast;
public class MainActivity extends Activity {
ScrollView scrollview;
Button dynamicbtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// requestWindowFeature(Window.FEATURE_NO_TITLE); //AppCompActivity on public class
setContentView(R.layout.activity_main);
scrollview = new ScrollView(this);
LinearLayout linearlayout = new LinearLayout(this);
linearlayout.setOrientation(LinearLayout.VERTICAL);
scrollview.addView(linearlayout);
ImageView imagetop = new ImageView(this);
imagetop.setBackgroundResource(R.mipmap.ic_launcher );
imagetop.setMaxHeight(50);
imagetop.setMaxWidth(50);
linearlayout.addView(imagetop);
for(int i = 0; i<25;i++)
{
LinearLayout linear1 = new LinearLayout(this);
linear1.setOrientation(LinearLayout.HORIZONTAL);
linearlayout.addView(linear1);
ImageView image = new ImageView(this);
image.setBackgroundResource(R.mipmap.ic_launcher );
image.setMaxHeight(50);
image.setMaxWidth(50);
linear1.addView(image);
dynamicbtn = new Button(this);
dynamicbtn.setText("Button no... "+i);
dynamicbtn.setId(i);
dynamicbtn.setTextSize(10);
dynamicbtn.setPadding(8, 3, 8, 3);
dynamicbtn.setTypeface(Typeface.SERIF,Typeface.BOLD_ITALIC);
dynamicbtn.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
linear1.addView(dynamicbtn);
dynamicbtn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Toast.makeText(getApplicationContext(), "Yipee.."+ v.getId(), Toast.LENGTH_SHORT).show();
}
});
CheckBox dynamicchk = new CheckBox(this);
dynamicchk.setId(i);
dynamicchk.setText("Wow..A checkbox" + i);
linear1.addView(dynamicchk);
dynamicchk.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(CompoundButton arg0, boolean arg1)
{
Toast.makeText(getApplicationContext(), "Checked.."+ arg0.getId() + " " + arg1, Toast.LENGTH_SHORT).show();
}
});
}
this.setContentView(scrollview);
}
}
Abend:
09-04 18:59:04.631 2854-2854/life.poa.webcastman.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
Process: life.poa.webcastman.myapplication, PID: 2854
java.lang.RuntimeException: Unable to start activity ComponentInfo{life.poa.webcastman.myapplication/life.poa.webcastman.myapplication.MainActivity}: java.lang.IllegalArgumentException: Wrong state class, expecting View State but received class android.widget.CompoundButton$SavedState instead. This usually happens when two views of different type have the same id in the same hierarchy. This view's id is id/0x0. Make sure other views do not use the same id.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3947)
at android.app.ActivityThread.access$900(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1309)
at android.os.Handler.dispatchMessage(Handler.java:102)
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)
Caused by: java.lang.IllegalArgumentException: Wrong state class, expecting View State but received class android.widget.CompoundButton$SavedState instead. This usually happens when two views of different type have the same id in the same hierarchy. This view's id is id/0x0. Make sure other views do not use the same id.
at android.view.View.onRestoreInstanceState(View.java:13764)
at android.widget.TextView.onRestoreInstanceState(TextView.java:3781)
at android.view.View.dispatchRestoreInstanceState(View.java:13740)
at android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:2893)
at android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:2893)
at android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:2893)
at android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:2893)
at android.view.View.restoreHierarchyState(View.java:13718)
at com.android.internal.policy.impl.PhoneWindow.restoreHierarchyState(PhoneWindow.java:2009)
at android.app.Activity.onRestoreInstanceState(Activity.java:1023)
at android.app.Activity.performRestoreInstanceState(Activity.java:978)
at android.app.Instrumentation.callActivityOnRestoreInstanceState(Instrumentation.java:1162)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) 
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3947) 
at android.app.ActivityThread.access$900(ActivityThread.java:151) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1309) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
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) 
You don't need to set ID. If You want to assign some ID to the view you could achive this by using view.setTag(). And it will not affect any aspect of view hierarchy:
...
dynamicbtn.setTag(i);
...
dynamicbtn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
//You can cast it to `Integer` to get `ID` value
Toast.makeText(getApplicationContext(), "Yipee.."+ v.getTag(), Toast.LENGTH_SHORT).show();
}
});
...
dynamicchk.setTag(i);
...
dynamicchk.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(CompoundButton arg0, boolean arg1)
{
//You can cast it to `Integer` to get `ID` value
Toast.makeText(getApplicationContext(), "Checked.."+ arg0.getTag() + " " + arg1, Toast.LENGTH_SHORT).show();
}
});

d.support.design.widget.FloatingActionButton.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

I am using Drawer in a Fragment Floating Button whose value is getting null.
When clicking on Drawer item it is getting closed. Can anybody explain why?
Here is my code.
package com.example.mubeen.emei;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.support.v7.app.AppCompatActivity;
import android.widget.Button;
import android.widget.TextView;
/**
* A simple {#link Fragment} subclass.
*/
public class Category_Item extends Fragment {
FloatingActionButton fab;
public Category_Item() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SaveCategory fragment = new SaveCategory();
android.support.v4.app.FragmentTransaction fragmentTransaction =
getActivity().getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment1_container, fragment);
fragmentTransaction.commit();
getActivity().setTitle(R.string.Save_Category);
return inflater.inflate(R.layout.fragment_category__item, container, false);
}
}
}
logcat
12-26 05:22:50.952 9530-9530/com.example.mubeen.emei W/PathParser: Points are too far apart 4.000000596046461
12-26 05:22:53.902 9530-9530/com.example.mubeen.emei D/AndroidRuntime: Shutting down VM
12-26 05:22:53.902 9530-9530/com.example.mubeen.emei E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.mubeen.emei, PID: 9530
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.support.design.widget.FloatingActionButton.setOnClickListener(android.view.View$OnClickListener)'
on a null object reference
at com.example.mubeen.emei.Category_Item.button(Category_Item.java:49)
at com.example.mubeen.emei.Category_Item.onCreateView(Category_Item.java:37)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1962)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:106)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:124)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1613)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:517)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
initialize your FloatingActionButton fab in your code ..
In your onCreateView method use this.
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Enter your code here to do something after clicking Floating Actionbar
}
});
I think this may help you.

move Image to the next activity after Loging in with Google

I have managed to move both the Name and Email to the next activity but when I try to move the Image, It crashes....I have stored the name and Email in variables and also managed to get the path of the Image. How can I be able to move the Image to the next Activity...?
GoogleLogin.java
package net.simplifiedcoding.blaze;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.GoogleApiClient;
public class GoogleLogin extends AppCompatActivity implements View.OnClickListener, GoogleApiClient.OnConnectionFailedListener {
//Signin button
private SignInButton signInButton;
//Signing Options
private GoogleSignInOptions gso;
//google api client
private GoogleApiClient mGoogleApiClient;
//Signin constant to check the activity result
private int RC_SIGN_IN = 100;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_google);
//Initializing google signin option
gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
//Initializing signinbutton
signInButton = (SignInButton) findViewById(R.id.sign_in_button);
signInButton.setSize(SignInButton.SIZE_WIDE);
signInButton.setScopes(gso.getScopeArray());
//Initializing google api client
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
//Setting onclick listener to signing button
signInButton.setOnClickListener(this);
}
//This function will option signing intent
private void signIn() {
//Creating an intent
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
//Starting intent for result
startActivityForResult(signInIntent, RC_SIGN_IN);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//If signin
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
//Calling a new function to handle signin
handleSignInResult(result);
}
}
//After the signing we are calling this function
private void handleSignInResult(GoogleSignInResult result) {
//If the login succeed
if (result.isSuccess()) {
//Getting google account
GoogleSignInAccount acct = result.getSignInAccount();
Intent results = new Intent(getApplicationContext(), Result.class);
String strName = acct.getDisplayName();
String strEmail = acct.getEmail();
String strUrl = acct.getPhotoUrl().getPath();
results.putExtra("name", strName);
results.putExtra("email", strEmail);
results.putExtra("url", strUrl);
startActivity(results);
} else {
//If login fails
Toast.makeText(this, "Login Failed", Toast.LENGTH_LONG).show();
}
}
#Override
public void onClick(View v) {
if (v == signInButton) {
//Calling signin
signIn();
}
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
}
Result.Java
package net.simplifiedcoding.blaze;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
public class Result extends AppCompatActivity {
private NetworkImageView profilePhoto;
//Image Loader
private ImageLoader imageLoader;
TextView txtName;
TextView txtEmail;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
String name = getIntent().getExtras().getString("name");
String email = getIntent().getExtras().getString("email");
String url = getIntent().getExtras().getString("url");
Toast.makeText(getApplicationContext(), url, Toast.LENGTH_LONG).show();
txtName = (TextView) findViewById(R.id.textViewName);
txtName.setText(name);
txtEmail = (TextView) findViewById(R.id.textViewEmail);
txtEmail.setText(email);
profilePhoto = (NetworkImageView) findViewById(R.id.profileImage);
//Initializing image loader
imageLoader = CustomVolleyRequest.getInstance(this.getApplicationContext())
.getImageLoader();
imageLoader.get(url,
ImageLoader.getImageListener(profilePhoto,
R.mipmap.ic_launcher,
R.mipmap.ic_launcher));
//Loading image
profilePhoto.setImageUrl(url, imageLoader);
}
}
activity_google_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".GoogleLogin">
<com.google.android.gms.common.SignInButton
android:id="#+id/sign_in_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal" />
</LinearLayout>
result.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="net.simplifiedcoding.blaze.Result">
<com.android.volley.toolbox.NetworkImageView
android:id="#+id/profileImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:text="Name"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/textViewName"
android:textStyle="bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:text="email"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/textViewEmail"
android:textStyle="bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
Log cat
12-19 14:26:24.301 31821-31849/net.simplifiedcoding.blaze E/GED: Failed to get GED Log Buf, err(0)
12-19 14:26:25.894 31821-31821/net.simplifiedcoding.blaze E/AndroidRuntime: FATAL EXCEPTION: main
Process: net.simplifiedcoding.blaze, PID: 31821
java.lang.RuntimeException: Unable to start activity ComponentInfo{net.simplifiedcoding.blaze/net.simplifiedcoding.blaze.Result}: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.hashCode()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2521)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2601)
at android.app.ActivityThread.access$800(ActivityThread.java:178)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1470)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5637)
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:959)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:754)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.hashCode()' on a null object reference
at com.android.volley.Request.<init>(Request.java:136)
at com.android.volley.toolbox.ImageRequest.<init>(ImageRequest.java:71)
at com.android.volley.toolbox.ImageLoader.get(ImageLoader.java:219)
at com.android.volley.toolbox.ImageLoader.get(ImageLoader.java:171)
at net.simplifiedcoding.blaze.Result.onCreate(Result.java:48)
at android.app.Activity.performCreate(Activity.java:6092)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1112)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2468)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2601) 
at android.app.ActivityThread.access$800(ActivityThread.java:178) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1470) 
at android.os.Handler.dispatchMessage(Handler.java:111) 
at android.os.Looper.loop(Looper.java:194) 
at android.app.ActivityThread.main(ActivityThread.java:5637) 
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:959) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:754) 
If you successfully get user-id,
Make a query to get the profile picture directly from your second activity.
https://www.googleapis.com/plus/v1/people/{GOOGLE_USER_ID}?key={YOUR_API_KEY}
where:
GOOGLE_USER_ID - ID of the user in Google Plus
YOUR_API_KEY - Android API key
Save the image locally if you are able to access it from first activity (like mentioned in the comment) and then load the locally saved image file in the next activity.
I think the path is inaccessible after the life of the GoogleSignInOptions is over. And in your second activity it definitely is over.
Use this to save the image locally on sd-card:
URL url = new URL ("file://some/path/anImage.png");
InputStream input = url.openStream();
try {
//The sdcard directory e.g. '/sdcard' can be used directly, or
//more safely abstracted with getExternalStorageDirectory()
File storagePath = Environment.getExternalStorageDirectory();
OutputStream output = new FileOutputStream (storagePath + "/myImage.png");
try {
byte[] buffer = new byte[aReasonableSize];
int bytesRead = 0;
while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
output.write(buffer, 0, bytesRead);
}
} finally {
output.close();
}
} finally {
input.close();
}
Source of the above code posted
Another good reference on how to save the file from url and rad it again - from same post as above

Make ListFragment open a Activity

Oke so i'm really new to android studio and android app dev in general but i wanted to make a app that my youth movement could use as sort of a database but i ran into a problem.
So i have a drawer with all the groups and if you press the drawer buttons it opens a ListFragment with names and what i want to happen is when i press the name a activity shows up with the name a photo and a phone number. But i can't seem to figure out how to open a activity from that listFragment.
Here is the ListFragment.java
package app.jarifile.test;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
/**
* Created by User on 23/09/2015.
*/
public class Givers_Fragment extends ListFragment {
Intent i;
String[] listitems = {
"(Takleider)",
"(Takleider)",
"(Leider)",
"(Leider)"
};
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
}
#Override
public void onActivityCreated(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, listitems));
}
#Override
public void onListItemClick(ListView l, View v, int position, long id){
switch(position){
case 0:
i = new Intent(getActivity(), Test_Activity.class);
break;
case 1:
i = new Intent(getActivity(), Test_Activity.class);
break;
case 2:
i = new Intent(getActivity(), Test_Activity.class);
break;
}
startActivity(i);
}
And this is the Test_Activity code.
package app.jarifile.test;
import android.app.Activity;
import android.os.Bundle;
/**
* Created by User on 24/09/2015.
*/
public class Test_Activity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.test_layout);
}
This is what logcat says
09-28 18:48:28.915 24081-24081/app.jarifile.test E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: app.jarifile.test, PID: 24081
android.content.ActivityNotFoundException: Unable to find explicit activity class {app.jarifile.test/app.jarifile.test.Test_Activity}; have you declared this activity in your AndroidManifest.xml?
at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1793)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1515)
at android.app.Activity.startActivityForResult(Activity.java:4026)
at android.app.Activity.startActivityForResult(Activity.java:3973)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:748)
at android.app.Activity.startActivity(Activity.java:4297)
at android.app.Activity.startActivity(Activity.java:4265)
at app.jarifile.test.Givers_Fragment.onListItemClick(Givers_Fragment.java:51)
at android.support.v4.app.ListFragment$2.onItemClick(ListFragment.java:58)
at android.widget.AdapterView.performItemClick(AdapterView.java:339)
at android.widget.AbsListView.performItemClick(AbsListView.java:1544)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:3721)
at android.widget.AbsListView$3.run(AbsListView.java:5660)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6837)
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:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
09-28 18:48:31.635 24081-24081/app.jarifile.test I/Process﹕ Sending signal. PID: 24081 SIG: 9
Thank you for the help.
You have not declared Test_Activity in your AndroidManifest.xml. All Activities in your app must be declared there. Here's an example of what that might look like:
<manifest ... >
<application ... >
<activity android:name=".Test_Activity" />
...
</application ... >
...
</manifest>
http://developer.android.com/guide/components/activities.html#Declaring
try to replace startActivity(i) with getActivity().startActivity(i)

Categories

Resources