PopupMenu inside Adapter getView() not working - android

I'm using a custom adapter and adding this code on getView() method:
final ImageView popupMenu = (ImageView) v.findViewById(R.id.popupMenu);
popupMenu.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
popupMenu.setImageResource(R.drawable.ic_popup_menu_selected);
PopupMenu popup = new PopupMenu(context, view);
popup.getMenuInflater().inflate(R.menu.popup, popup.getMenu());
popup.setOnDismissListener(new PopupMenu.OnDismissListener() {
#Override
public void onDismiss(PopupMenu pm) {
popupMenu.setImageResource(R.drawable.ic_popup_menu);
}
});
popup.show();
}
});
But I get this error:
java.lang.RuntimeException: Failed to resolve attribute at index 6
The same code works onListItemClick() but it doesn't make sense to be there because it needs to be clicked once to setup and click again to trigger the PopupMenu.
Edit: Logcat
11-02 17:58:51.276 1996-1996/com.android.example E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.android.example, PID: 1996
java.lang.RuntimeException: Failed to resolve attribute at index 6
at android.content.res.TypedArray.getLayoutDimension(TypedArray.java:603)
at android.view.ViewGroup$LayoutParams.setBaseAttributes(ViewGroup.java:6423)
at android.view.ViewGroup$MarginLayoutParams.<init>(ViewGroup.java:6591)
at android.widget.FrameLayout$LayoutParams.<init>(FrameLayout.java:735)
at android.widget.FrameLayout.generateLayoutParams(FrameLayout.java:679)
at android.widget.FrameLayout.generateLayoutParams(FrameLayout.java:62)
at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
at android.support.v7.internal.view.menu.MenuPopupHelper$MenuAdapter.getView(MenuPopupHelper.java:363)
at android.support.v7.internal.view.menu.MenuPopupHelper.measureContentWidth(MenuPopupHelper.java:212)
at android.support.v7.internal.view.menu.MenuPopupHelper.tryShow(MenuPopupHelper.java:146)
at android.support.v7.internal.view.menu.MenuPopupHelper.show(MenuPopupHelper.java:118)
at android.support.v7.widget.PopupMenu.show(PopupMenu.java:168)
at com.android.example.GetAdapter$listAdapter$1.onClick(GetAdapter.java:81)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
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:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

With the following import I always had the error:
import android.support.v7.widget.PopupMenu;
It works fine with the following import:
import android.widget.PopupMenu;
Full answer: stackoverflow.com/a/27826670/4548500

I solve it this way:
Add this on adapter getView():
ImageView popupMenu = (ImageView) v.findViewById(R.id.popupMenu);
popupMenu.setTag(getItem(position));
popupMenu.setOnClickListener(MyFragment.popupMenuListener);
And this on MyFragment:
implements OnClickListener
popupMenuListener = this;
#Override
public void onClick(final View view) {
view.post(new Runnable() {
#Override
public void run() {
showPopupMenu(view);
}
});
}

This issue is related to missing theme attributes.
Make sure that your app theme extends Theme.AppCompat.
<style name="AppTheme" parent="#style/Theme.AppCompat" />

Related

I'm using gowong/material-sheet-fab but it's showing me errors .Can anyone help me out?

Here is my Fab Activity
public class Fab extends FloatingActionButton implements AnimatedFab {
public Fab(Context context) {
super(context);
}
#Override
public void show() {
show(0, 0);
}
#SuppressLint("RestrictedApi")
#Override
public void show(float translationX, float translationY) {
setVisibility(View.VISIBLE);
}
/**
* Hides the FAB.
*/
#SuppressLint("RestrictedApi")
#Override
public void hide() {
setVisibility(View.INVISIBLE);
}
}
Here is my Main Activity
// MATERIAL ANIMATED FAB
Fab fab = findViewById(R.id.fab);
View sheetView = findViewById(R.id.fab_sheet);
View overlay = findViewById(R.id.overlay);
int sheetColor = getResources().getColor(R.color.fab_sheet_color);
int fabColor = getResources().getColor(R.color.fab_color);
// Initialize material sheet FAB
materialSheetFab = new MaterialSheetFab<>(fab, sheetView, overlay,
sheetColor, fabColor);
materialSheetFab.setEventListener(new MaterialSheetFabEventListener() {
#Override
public void onShowSheet() {
// Called when the material sheet's "show" animation starts.
}
#Override
public void onSheetShown() {
// Called when the material sheet's "show" animation ends.
}
#Override
public void onHideSheet() {
// Called when the material sheet's "hide" animation starts.
}
public void onSheetHidden() {
// Called when the material sheet's "hide" animation ends.
}
});
Here is my logcat
Process: com.teepe.teepe, PID: 29259
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.teepe.teepe/com.teepe.teepe.MainActivity}: java.lang.ClassCastException: android.support.design.widget.FloatingActionButton cannot be cast to com.teepe.teepe.Fab
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
Caused by: java.lang.ClassCastException: android.support.design.widget.FloatingActionButton cannot be cast to com.teepe.teepe.Fab
at com.teepe.teepe.MainActivity.onCreate(MainActivity.java:95)
at android.app.Activity.performCreate(Activity.java:6662)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6077) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756) 
As the error says, Caused by: java.lang.ClassCastException: android.support.design.widget.FloatingActionButton cannot be cast to com.teepe.teepe.Fab at com.teepe.teepe.MainActivity.onCreate(MainActivity.java:95), in your MainActivity, check this line of code from the library you used:
<com.gordonwong.materialsheetfab.sample.Fab
android:id="#+id/fab"
style="#style/Widget.MaterialSheetFab.Fab"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true" />
Change your <path.to.your.FloatingActionButton to <path.to.your.Fab in the layout of MainActivity (preferably, activity_main.xml) in which your R.id.fab has been declared.
Hope this should fix your error. Click on the check mark beside the answer to toggle it from greyed out to fill in if it does.

#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>

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

Android Studio Button OnClick Causing Failure?

I'm working on an application for android in Android Studio and I'm attempting to make an on-click listener like so:
Button menu_button = (Button)findViewById(R.id.menu_button);
menu_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
However, when I start genymotion it tells me that the app has stopped working. If I remove this code:
menu_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
The application runs fine. I'm very confused and was hoping maybe someone could point something out I'm not understanding.
Here's the full code of the main activity I'm working on, and I should note that the button is inside a ViewPager.
public class MainActivity extends FragmentActivity {
private ViewPager m_BackgroundViewPager;
private ViewPager m_PanelViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature((int) Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
m_BackgroundViewPager = (ViewPager)(findViewById(R.id.mainViewPager));
m_PanelViewPager = (ViewPager)(findViewById(R.id.bottomViewPager));
m_BackgroundViewPager.setAdapter
(new BackgroundPagerAdapter(getSupportFragmentManager(), this));
m_PanelViewPager.setAdapter
(new PanelPagerAdapter(getSupportFragmentManager(), this));
Button menu_button = (Button)findViewById(R.id.menu_button);
menu_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
}
LogCat Results:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at eqlogic.annswingsandthings.MainActivity.onCreate(MainActivity.java:37)
at android.app.Activity.performCreate(Activity.java:5933)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            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:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
XML:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#998822">
<Button
android:layout_width="75dp"
android:layout_height="75dp"
android:id="#+id/menu_button"
android:text="Menu"
android:textSize="12dp" />
</FrameLayout>
Create a global variable for your Button as follows :
Button menu_button;
Then in your onCreate() you add this line :
menu_button = (Button)findViewById(R.id.menu_button);
And now whenever you want to make a setOnClickListener() you can do it like you were doing :
menu_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Your click stuff
}
});
EDIT
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
Make sure that in your activity_main.xml your button has this :
android:id="#+id/menu_button"
Problem is that the button is inside the view pager.
So in order to display the button either remove it out of the view pager or add it to the xml of the fragment which forms part of the view pager and inflate it in that fragment.

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