Android dynamic buttons and checkbox getting id0x0 on rotate - android

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

Related

ViewPager and Android Wear = crash

_
Hello members of stackoverflow!
I worked successfully with the ViewPager (VP) on a "normal" activity.
Now I tried to use almost the same way for an Android Wear app.
In my MainActivity, which contains the VP, I faced different errors like:
Error 1: (getFragmentManager() -> "Cannot be applied"
Error 2: super(manager); -> "Cannot be applied"
Error 3: public Fragment getItem(int i); -> "Incompatible return type"
I found this thread and was able to fix those errors by changing the imports + changing the build.gradle.
How to implement view pager in Android watch?
Those are now my imports in my MainActivity.java:
import android.app.Fragment;
import android.app.FragmentManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v13.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.wearable.activity.WearableActivity;
import java.util.ArrayList;
import java.util.List;
This is the rest of the MainActivity:
public class MainActivity extends WearableActivity
{
ViewPager vp; // Variable for Viewpager
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); // Link to layout
ViewPager vp = findViewById(R.id.vp); // Link variable to ID
SetUpViewPager(vp); // Run viewpager method
}
public void SetUpViewPager(ViewPager viewpager)
{
MyViewPagerAdapter Adapter = new MyViewPagerAdapter(getFragmentManager());
Adapter.AddPageFragment(new Fragment1(), "Fragment1"); // Load page 1 inside of ViewPager
Adapter.AddPageFragment(new Fragment2(), "Fragment2"); // Load page 2 inside of ViewPager
viewpager.setAdapter(Adapter);
}
public class MyViewPagerAdapter extends android.support.v4.app.FragmentPagerAdapter
{
private List<Fragment> MyFragment = new ArrayList<>();
private List<String> MyPageTitle = new ArrayList<>();
public MyViewPagerAdapter(FragmentManager manager)
{
super(manager);
}
public void AddPageFragment(Fragment Frag, String Title)
{
MyFragment.add(Frag);
MyPageTitle.add(Title);
}
#Override
public Fragment getItem(int i)
{
return MyFragment.get(i);
}
#Nullable
#Override
public CharSequence getPageTitle(int position)
{
return MyPageTitle.get(position);
}
#Override
public int getCount()
{
return 2; // 2 pages total
}
}
}
Strange is that is says ViewPager vp; -> Field 'vp' is never used!
Fragment1: (Fragment2 is the same except for 2/two)
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Fragment1 extends Fragment
{
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState)
{
View fragmentOne = inflater.inflate(R.layout.fragment1, container, false); // Link view and layout
return fragmentOne;
}
}
The XML files for the fragments are just constraint layouts with each 1 button.
The content_main.xml contains the VP which accesses the activity_main.xml.
I used the same way on the normal smartphone device and it worked flawlessly.
The problem is that everytime I start the app on the Wear Emulator, it immediately crashes.
This is what Logcat says:
10-23 14:40:32.909 2203-2203/com.example.user.wearvp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.user.wearvp, PID: 2203
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.user.wearvp/com.example.user.wearvp.MainActivity}: java.lang.NullPointerException:
Attempt to invoke virtual method 'void android.support.v4.view.ViewPager.setAdapter(android.support.v4.view.PagerAdapter)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5422)
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 android.support.v4.view.ViewPager.setAdapter(android.support.v4.view.PagerAdapter)' on a null object reference
at com.example.user.wearvp.MainActivity.SetUpViewPager(MainActivity.java:35)
at com.example.user.wearvp.MainActivity.onCreate(MainActivity.java:24)
at android.app.Activity.performCreate(Activity.java:6251)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5422) 
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) 
Any help will be appreciated!
P.S:
If I forgot to mention anything important, please, just ask and I will give you the needed information!
Best regards
The stack trace indicates that there is no view with the id vp defined in your activity_main.xml layout file. I'm not completely sure what you mean with:
The content_main.xml contains the VP which accesses the activity_main.xml.
If vp is defined in the content_main.xml layout, then that might be the one you should use with setContentView() (instead of the current activity_main.xml).
Strange is that is says ViewPager vp; -> Field 'vp' is never used!
The local variable vp (defined inside the onCreate method) is shadowing the instance variable vp. If you need it to have object-level scope just remove ViewPager when you assign a value to it.

#android:id/list cannot resolve symbol

import android.app.ListFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
/**
* Created by name on 3/13/17.
* Used for the specials tab to allow a list of days to choose what special one would like to view
*/
public class SpecialsScroll extends ListFragment implements AdapterView.OnItemClickListener{
public SpecialsScroll(){
//Empty Constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
super.onCreate(savedInstanceState);
return inflater.inflate(R.layout.fragment_specials_scroll, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
setListAdapter(ArrayAdapter.createFromResource(getActivity(), R.array.days, android.R.layout.simple_list_item_1)); //Loads array into the ListFragment
getListView().setOnItemClickListener(this); //activates the listener for this Fragment class
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id){ // For checking when a user taps on an option
SpecialsPage specialsPage = new SpecialsPage();
Bundle foodArgs = new Bundle();
switch (position){ // checks what option is chosen and sends respective keys as parameters
case 0:
int[] keysMonday = {R.string.boom_boom_enchiladas_key, R.string.tacos_mexican_key};
foodArgs.putIntArray("keys", keysMonday);
break;
case 1:
int[] keysTuesday = {R.string.shrimp_avocado_tacos_key, R.string.green_chile_chicken_enchiladas_key};
foodArgs.putIntArray("keys", keysTuesday);
break;
}
specialsPage.setArguments(foodArgs);
getActivity().getFragmentManager().beginTransaction().replace(R.id.container, specialsPage).addToBackStack(null).commit();
}
}
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity{
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
if(getFragmentManager().findFragmentByTag("CURRENT") == null){
getFragmentManager().beginTransaction().add(R.id.container, new SpecialsScroll(), "CURRENT").commit();
}
switch (item.getItemId()) {
case R.id.special:
getFragmentManager().beginTransaction().replace(R.id.container, new SpecialsScroll(), "CURRENT").commit();
return true;
case R.id.locations:
getFragmentManager().beginTransaction().replace(R.id.container, new LocationsScroll(), "CURRENT").commit();
return true;
case R.id.order:
return true;
}
return false;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
getFragmentManager().beginTransaction().add(R.id.container, new SpecialsScroll(), "CURRENT").commit();
}
}
So, I am trying to create a ListView and everything in the code works, but suddenly I am unable to get the xml to recognize the android:id/list attribute for some reason, I don't know why. When I click on an item in the listview in my app it still does what it should, I just really want to get rid of the error.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white">
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
<TextView
android:id="#+id/text_specialsscroll"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
04-26 14:06:30.299 2576-2576
/com.namename.www.name
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.namename.www.name, PID: 2576
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.namename.www.name/com.namename.www.name.MainActivity}: java.lang.RuntimeException: Content has view with id attribute 'android.R.id.list' that is not a ListView class
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
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)
Caused by: java.lang.RuntimeException: Content has view with id attribute 'android.R.id.list' that is not a ListView class
at android.app.ListFragment.ensureList(ListFragment.java:402)
at android.app.ListFragment.onViewCreated(ListFragment.java:203)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1010)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1171)
at android.app.BackStackRecord.run(BackStackRecord.java:816)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1578)
at android.app.FragmentController.execPendingActions(FragmentController.java:371)
at android.app.Activity.performStart(Activity.java:6695)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2628)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
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)
Change your id to this:
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>

how to set Firebase Context to use database

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

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.

app crashing when goin to Editfriends activity [duplicate]

This question already has answers here:
Your content must have a ListView whose id attribute is 'android.R.id.list'
(7 answers)
Closed 7 years ago.
here is the EditFriends activity..........................................
package com.josephvarkey996gmail.test1;
import android.app.ListActivity;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.widget.ArrayAdapter;
import com.parse.FindCallback;
import com.parse.ParseException;
import com.parse.ParseQuery;
import com.parse.ParseUser;
import java.util.List;
public class Editfriends extends ListActivity {
public static final String Tag=Editfriends.class.getSimpleName();
protected List<ParseUser> mUser;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.activity_editfriends);
}
#Override
protected void onResume() {
super.onResume();
setProgressBarIndeterminateVisibility(true);
ParseQuery<ParseUser> query= ParseUser.getQuery();
query.orderByAscending(ParseConstants.key_Username);
query.setLimit(1000);
query.findInBackground(new FindCallback<ParseUser>() {
#Override
public void done(List<ParseUser> users, ParseException e) {
setProgressBarIndeterminateVisibility(true);
if (e== null){
mUser=users;
String[] username = new String[mUser.size()];
int i=0;
for(ParseUser user:mUser){
username[i]=user.getUsername();
i++;
}
ArrayAdapter<String> adapter = new ArrayAdapter<>(Editfriends.this,android.R.layout.simple_list_item_checked,username);
setListAdapter(adapter);
}
else
{
Log.e(Tag,e.getMessage());
AlertDialog.Builder builder=new AlertDialog.Builder(Editfriends.this);
builder.setMessage(e.getMessage()).setTitle(R.string.error_title).setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_editfriends, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
here is the xml of Editfriends ............................................
<RelativeLayout 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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.josephvarkey996gmail.test1.Editfriends">
<TextView android:text="#string/hello_world" android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
im learning ,so cant understand the eror. here is the logcat..............................
07-21 19:42:05.397 9188-9188/com.josephvarkey996gmail.test1 E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.josephvarkey996gmail.test1, PID: 9188
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.josephvarkey996gmail.test1/com.josephvarkey996gmail.test1.Editfriends}: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
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.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'
at android.app.ListActivity.onContentChanged(ListActivity.java:243)
at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:382)
at android.app.Activity.setContentView(Activity.java:2145)
at com.josephvarkey996gmail.test1.Editfriends.onCreate(Editfriends.java:27)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
            at android.app.ActivityThread.access$800(ActivityThread.java:151)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5257)
            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)
Your main activity class is extending a ListActivity. This means that your xml file needs a ListView.
Try adding something like this to your XML:
<ListView android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
More information can be found at http://developer.android.com/reference/android/app/ListActivity.html.
As the documentation states:
ListActivity has a default layout that consists of a single, full-screen list in the center of the screen. However, if you desire, you can customize the screen layout by setting your own view layout with setContentView() in onCreate(). To do this, your own view MUST contain a ListView object with the id "#android:id/list
Your activtiy extends ListActivity. So as the crash logs say :
Your content must have a ListView whose id attribute is 'android.R.id.list'
This mean that in your xml file you should have a ListView with the attribute android:id:"android.R.id.list.
This is because ListActivity expect to find a ListView in is content view.
You are using a ListActivity, which is a bit different than a normal Activity.
If you do nothing, then your ListActivity will have a single View in it, which is a ListView.
If you call setContentView() to supply your own layout (perhaps you want to display more than just a ListView), then your layout must contain a ListView and that ListView must have an id of #android:id/list.
Since you are providing a custom layout that consists of a RelativeLayout with a single TextView, your layout does not pass this requirement. Since it looks like you just have placeholder content there, I would remove the layout and remove the call to setContentView().
The exception you posted from your logcat mentions this:
Your content must have a ListView whose id attribute is 'android.R.id.list'

Categories

Resources