'NoSuchMethodException' even though the method really does exist - java

fragment_view1.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/viewOneText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="92dp"
android:layout_marginTop="182dp"
android:text="First View"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="#+id/viewOneBtn"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/viewOneText"
android:layout_below="#+id/viewOneText"
android:layout_marginTop="17dp"
android:text="Click Here" />
<include layout = "#layout/drop_down"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:layout_alignParentBottom="true"/>
</RelativeLayout>
drop_down.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<SlidingDrawer
android:id="#+id/SlidingDrawer"
android:layout_width="wrap_content"
android:layout_height="250dp"
android:layout_alignParentBottom="true"
android:content="#+id/contentLayout"
android:handle="#+id/slideButton"
android:orientation="vertical"
android:alpha="0.7">
<LinearLayout
android:id="#+id/slideButton"
android:layout_width="fill_parent"
android:layout_height="20dp"
android:orientation="vertical"
android:clickable="true"
android:gravity="right"
android:background="#android:drawable/bottom_bar"
>
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="^^^"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
<LinearLayout
android:id="#+id/contentLayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#000000"
android:padding="10dip" >
<TextView
android:id="#+id/menu_add_inquiry"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:text="AAA"
android:textColor="#ffffff"
android:clickable="true"
android:onClick="onMenuItemClicked"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/menu_add_event"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:text="BBB"
android:textColor="#ffffff"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/menu_additional_info"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:text="CCC"
android:textColor="#ffffff"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/menu_add_to_contacts"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:text="DDD"
android:textColor="#ffffff"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
</SlidingDrawer>
</RelativeLayout>
FirstView.java (for fragment_view1.xml)
package com.example.fragmenttest;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
public class FirstView extends DropDownMenu
{
private TextView firstText;
private Button btn;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_view1,container,false);
firstText = (TextView)view.findViewById(R.id.viewOneText);
btn = (Button)view.findViewById(R.id.viewOneBtn);
return view;
}
}
DropDownMenu.java (for drop_down.xml)
package com.example.fragmenttest;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class DropDownMenu extends Fragment {
private TextView addInquiry, addEvent, additionalInfo, addToContacts;
private View view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
view = inflater.inflate(R.layout.drop_down,container,false);
intialize();
return view;
}
private void intialize()
{
//Intializing instance variables
addInquiry = (TextView)view.findViewById(R.id.menu_add_inquiry);
addEvent = (TextView)view.findViewById(R.id.menu_add_event);
additionalInfo = (TextView)view.findViewById(R.id.menu_additional_info);
addToContacts = (TextView)view.findViewById(R.id.menu_add_to_contacts);
}
public void onMenuItemClicked(View view) {
switch (view.getId()) {
case R.id.menu_add_inquiry:
// Intent intent = new Intent(DropDownMenu.this,NewLead.class);
// startActivity(intent);
break;
default:;
}
}
}
MainActivity.java
package com.example.fragmenttest;
import android.os.Bundle;
import android.app.Activity;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Menu;
public class MainActivity extends FragmentActivity {
private ViewPager viewPager;
private MyAdapter pageAdapter;
private static final int ITEMS = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager)findViewById(R.id.pager);
pageAdapter = new MyAdapter(getSupportFragmentManager());
viewPager.setAdapter(pageAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public static class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
#Override
public int getCount() {
return ITEMS;
}
#Override
public Fragment getItem(int position) {
if(position==0)
{
return new FirstView();
}
else
{
return new SecondView();
}
}
}
public void setCurrentItem (int item, boolean smoothScroll) {
viewPager.setCurrentItem(item, smoothScroll);
}
}
This code generate the following UI. Note that what you see as a "Menu" is built by drop_down.xml.
The problem is, when I click the TextView menu_add_inquiry in drop_down.xml, I get the following error.
11-28 14:13:52.537: E/AndroidRuntime(1933): FATAL EXCEPTION: main
11-28 14:13:52.537: E/AndroidRuntime(1933): java.lang.IllegalStateException: Could not find a method onMenuItemClicked(View) in the activity class com.example.fragmenttest.MainActivity for onClick handler on view class android.widget.TextView with id 'menu_add_inquiry'
11-28 14:13:52.537: E/AndroidRuntime(1933): at android.view.View$1.onClick(View.java:3586)
11-28 14:13:52.537: E/AndroidRuntime(1933): at android.view.View.performClick(View.java:4204)
11-28 14:13:52.537: E/AndroidRuntime(1933): at android.view.View$PerformClick.run(View.java:17355)
11-28 14:13:52.537: E/AndroidRuntime(1933): at android.os.Handler.handleCallback(Handler.java:725)
11-28 14:13:52.537: E/AndroidRuntime(1933): at android.os.Handler.dispatchMessage(Handler.java:92)
11-28 14:13:52.537: E/AndroidRuntime(1933): at android.os.Looper.loop(Looper.java:137)
11-28 14:13:52.537: E/AndroidRuntime(1933): at android.app.ActivityThread.main(ActivityThread.java:5041)
11-28 14:13:52.537: E/AndroidRuntime(1933): at java.lang.reflect.Method.invokeNative(Native Method)
11-28 14:13:52.537: E/AndroidRuntime(1933): at java.lang.reflect.Method.invoke(Method.java:511)
11-28 14:13:52.537: E/AndroidRuntime(1933): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
11-28 14:13:52.537: E/AndroidRuntime(1933): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
11-28 14:13:52.537: E/AndroidRuntime(1933): at dalvik.system.NativeStart.main(Native Method)
11-28 14:13:52.537: E/AndroidRuntime(1933): Caused by: java.lang.NoSuchMethodException: onMenuItemClicked [class android.view.View]
11-28 14:13:52.537: E/AndroidRuntime(1933): at java.lang.Class.getConstructorOrMethod(Class.java:460)
11-28 14:13:52.537: E/AndroidRuntime(1933): at java.lang.Class.getMethod(Class.java:915)
11-28 14:13:52.537: E/AndroidRuntime(1933): at android.view.View$1.onClick(View.java:3579)
11-28 14:13:52.537: E/AndroidRuntime(1933): ... 11 more
It says that method is missing, but it is there.
UPDATE
I edited the button in drop_down.xml with the full definition com.example.fragmenttest.DropDownMenu.onMenuItemClicked. Now I have the following issue
11-28 14:49:45.757: E/AndroidRuntime(2604): Caused by: java.lang.NoSuchMethodException: com.example.fragmenttest.DropDownMenu.onMenuItemClicked [class android.view.View]

In your drop_down.xml layout, you call onMenuItemClicked method, that does not exist in MainActivity class.
In the case of your layout, it is the method of the activity that will be called (and not the one of the fragment).
You may want to replace your method by same method, but in your MainActivity class.
You may read documentation of Android android:onclick :
This name must correspond to a public method that takes exactly one parameter of type View. For instance, if you specify android:onClick="sayHello", you must declare a public void sayHello(View v) method of your context (typically, your Activity).

Related

App crashing when switching to landscape mode (Android Studio)

I'm new to android development, and I have been trying to use fragments, however, the app is crashing when I try to switch to landscape mode. I have been trying to use android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" android:windowSoftInputMode="adjustPan" in my application manifest, but it seems that the application just ignores it and keeps staying in portrait mode despite being in landscape until the app restarts.
Here is my code
main XML
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
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">
<fragment
android:id="#+id/fragment"
android:name="com.example.TopFrag"
android:layout_width="421dp"
android:layout_height="163dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.49"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<fragment
android:id="#+id/fragment2"
android:name="com.example.BottomFrag"
android:layout_width="413dp"
android:layout_height="568dp"
android:layout_marginTop="1dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.708"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/fragment" />
</androidx.constraintlayout.widget.ConstraintLayout>
//Main activity `
package com.example;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.app.FragmentManager;
import android.os.Bundle;
MainActivity
public class MainActivity extends AppCompatActivity implements TopFrag.TopHalfFragmentListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
Fragment myFragment = new TopFrag();
ft.replace(R.id.fragment,myFragment);
ft.commit();
}
#Override
public void handleClicks(int holder) {
}
}
Fragment XML
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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"
android:background="#color/topFrag"
tools:context=".TopFrag" >
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="#+id/btnUp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="88dp"
android:layout_marginEnd="71dp"
android:text="#string/minus"
app:layout_constraintEnd_toStartOf="#+id/btnDown"
app:layout_constraintHorizontal_bias="0.855"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/btnDown"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="88dp"
android:layout_marginEnd="88dp"
android:text="#string/plus"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</FrameLayout>
Fragment.java
package com.example;
import android.os.Bundle;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
/**
* A simple {#link Fragment} subclass.
*/
public class TopFrag extends Fragment implements View.OnClickListener{
public TopFrag() {
// Required empty public constructor
}
Button up;
Button down;
int count =0;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View mv = inflater.inflate(R.layout.fragment_top, container, false);
up = mv.findViewById(R.id.btnDown);
down = mv.findViewById(R.id.btnUp);
up.setOnClickListener(this);
down.setOnClickListener(this);
return mv;
}
#Override
public void onClick(View v) {
if (up.isPressed()){
count= count+1;
}else if(count>0){
count= count -1;
}
TopHalfFragmentListener clickListner = (TopHalfFragmentListener) getActivity();
clickListner.handleClicks(count);
}
public interface TopHalfFragmentListener{
void handleClicks(int count);
}
}
Fragment 2 XML
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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"
android:background="#color/bottomFragColor"
tools:context=".BottomFrag" >
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/txtOutput"
android:layout_width="31dp"
android:layout_height="13dp"
android:layout_marginTop="200dp"
android:textSize="18sp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</FrameLayout>
Fragment 2.JAVA
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* A simple {#link Fragment} subclass.
*/
public class BottomFrag extends Fragment {
public BottomFrag() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View mv = inflater.inflate(R.layout.fragment_bottom, container, false);
return mv;
}
}
The error i received..
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example, PID: 1096
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.example/com.example.MainActivity}: android.view.InflateException: Binary XML file
line #9: Binary XML file line #9: Error inflating class fragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4754)
at android.app.ActivityThread.-wrap18(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1599)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Caused by: android.view.InflateException: Binary XML file line #9: Binary XML file line #9: Error
inflating class fragment
Caused by: android.view.InflateException: Binary XML file line #9: Error inflating class fragment
Caused by: java.lang.IllegalStateException: Fragment com.example.TopFrag did not create a view.
at android.app.FragmentManagerImpl.onCreateView(FragmentManager.java:3643)
at android.app.FragmentController.onCreateView(FragmentController.java:98)
at android.app.Activity.onCreateView(Activity.java:6187)
at androidx.fragment.app.FragmentActivity.onCreateView(FragmentActivity.java:389)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:780)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:730)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:863)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:824)
at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:469)
at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
at com.example.MainActivity.onCreate(MainActivity.java:22)
at android.app.Activity.performCreate(Activity.java:6975)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4754)
at android.app.ActivityThread.-wrap18(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1599)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Any help is much appreciated.

Android Studio - image button is crashing after i click on it

I am trying to make some simple image click button to go to another activity but I can't get it to work.
It says:
Unfortunately, myapp has stopped.
If I highlighted my android: onClick="myButton" it says Method myButton' is missing in 'MainActivity' in my layout.xml
MainActivity.java
package com.zemoapps.alarmclockgold;
import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.AttributeSet;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
//Old code "public class MainActivity extends AppCompatActivity {"
public class MainActivity extends AppCompatActivity {
private Button myButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView myTextview = (TextView) findViewById(R.id.RepeatingText);
TextView myTextview2 = (TextView) findViewById(R.id.CountDownText);
Typeface myCustomFont = Typeface.createFromAsset(getAssets(), "fonts/AndadaRegular.otf");
myTextview.setTypeface(myCustomFont);
myTextview2.setTypeface(myCustomFont);
}
public class MyCustomTextView extends TextView {
public MyCustomTextView(Context context, AttributeSet attrs) {
super(context, attrs);
this.setTypeface(Typeface.createFromAsset(context.getAssets(),
"fonts/AndadaRegular.otf"));
}
}
public class AlarmPage extends AppCompatActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myButton = (Button) findViewById(R.id.RepeatingImage);
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, AddAlarm.class));
}
});
}
}}
Layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:andriod="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/BG"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#9e84d3"
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="com.zemoapps.onething.MainActivity">
<ImageButton
android:id="#+id/RepeatingImage"
android:layout_width="200dp"
android:layout_height="150dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:background="#00000000"
android:contentDescription="#null"
android:onClick="myButton"
android:scaleType="fitCenter"
android:src="#drawable/alarm1" />
</RelativeLayout>
AndroidManifest says there is error too:
java.lang.IllegalStateException: Could not find method myButton(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatImageButton with id 'RepeatingImage'
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:307)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:266)
at android.view.View.performClick(View.java:4084)
at android.view.View$PerformClick.run(View.java:16966)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Remove android:onClick="myButton" from ImageButton in your XML.
<ImageButton
android:id="#+id/RepeatingImage"
android:layout_width="200dp"
android:layout_height="150dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:background="#00000000"
android:contentDescription="#null"
android:onClick="myButton" // remove this line from your xml
android:scaleType="fitCenter"
android:src="#drawable/alarm1" />
This is because you have extended AppCompatActivity.
It will work fine if you extend Activity.
You didn't define method for imagebutton click,you should add it to MainActivity like this:
public void myButton(View view){
}
Remove the next row from you ImageButton node:
android:onClick="myButton"
When you add it, Android will expect a method named "myButton" in your Activity.

Null pointer searching findViewById android app Java

problem
Hello, I am having an issue referencing a button on an android app I am making. The issue is a null pointer on referencing the button and I'm rather confused as to why that is occurring. A very similar reference worked on another class and I have included that for reference (onTestButtonClickr of welcomeScreen.java)
edit
I found that if I change setContentView(R.layout.activity_in_game); to setContentView(R.layout.fragment_in_game); the null pointer goes away but then any changes I make to the button do not work
logcat
04-14 13:13:40.280: D/dalvikvm(838): Not late-enabling CheckJNI (already on)
04-14 13:13:43.330: D/dalvikvm(838): GC_FOR_ALLOC freed 72K, 5% free 2993K/3132K, paused 167ms, total 169ms
04-14 13:13:44.280: D/dalvikvm(838): GC_FOR_ALLOC freed 3K, 5% free 3382K/3524K, paused 154ms, total 154ms
04-14 13:13:45.310: D/dalvikvm(838): GC_FOR_ALLOC freed 8K, 3% free 3802K/3916K, paused 194ms, total 194ms
04-14 13:13:45.590: D/gralloc_goldfish(838): Emulator without GPU emulation detected.
04-14 13:13:59.570: I/Choreographer(838): Skipped 33 frames! The application may be doing too much work on its main thread.
04-14 13:14:01.030: D/AndroidRuntime(838): Shutting down VM
04-14 13:14:01.030: W/dalvikvm(838): threadid=1: thread exiting with uncaught exception (group=0xb2aabba8)
04-14 13:14:01.080: E/AndroidRuntime(838): FATAL EXCEPTION: main
04-14 13:14:01.080: E/AndroidRuntime(838): Process: com.moconnell.thehacker, PID: 838
04-14 13:14:01.080: E/AndroidRuntime(838): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.moconnell.thehacker/com.moconnell.thehacker.InGame}: java.lang.NullPointerException
04-14 13:14:01.080: E/AndroidRuntime(838): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
04-14 13:14:01.080: E/AndroidRuntime(838): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
04-14 13:14:01.080: E/AndroidRuntime(838): at android.app.ActivityThread.access$800(ActivityThread.java:135)
04-14 13:14:01.080: E/AndroidRuntime(838): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
04-14 13:14:01.080: E/AndroidRuntime(838): at android.os.Handler.dispatchMessage(Handler.java:102)
04-14 13:14:01.080: E/AndroidRuntime(838): at android.os.Looper.loop(Looper.java:136)
04-14 13:14:01.080: E/AndroidRuntime(838): at android.app.ActivityThread.main(ActivityThread.java:5017)
04-14 13:14:01.080: E/AndroidRuntime(838): at java.lang.reflect.Method.invokeNative(Native Method)
04-14 13:14:01.080: E/AndroidRuntime(838): at java.lang.reflect.Method.invoke(Method.java:515)
04-14 13:14:01.080: E/AndroidRuntime(838): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
04-14 13:14:01.080: E/AndroidRuntime(838): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
04-14 13:14:01.080: E/AndroidRuntime(838): at dalvik.system.NativeStart.main(Native Method)
04-14 13:14:01.080: E/AndroidRuntime(838): Caused by: java.lang.NullPointerException
04-14 13:14:01.080: E/AndroidRuntime(838): at com.moconnell.thehacker.InGame.generateImages(InGame.java:195)
04-14 13:14:01.080: E/AndroidRuntime(838): at com.moconnell.thehacker.InGame.onCreate(InGame.java:64)
04-14 13:14:01.080: E/AndroidRuntime(838): at android.app.Activity.performCreate(Activity.java:5231)
04-14 13:14:01.080: E/AndroidRuntime(838): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
04-14 13:14:01.080: E/AndroidRuntime(838): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
04-14 13:14:01.080: E/AndroidRuntime(838): ... 11 more
04-14 13:14:03.760: I/Process(838): Sending signal. PID: 838 SIG: 9
class with error
package com.moconnell.thehacker;
import java.io.File;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.ResourceBundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.os.Build;
public class InGame extends ActionBarActivity {
//public ImageButton mBtn;
ImageButton currentImage;
//public ArrayList<Drawable> j;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_in_game);
//mBtn = (ImageButton) findViewById(R.id.ImageButton1_2);
//mBtn.setImageResource(R.drawable.fat_banana);
//
//
// btn.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// btn.setBackgroundColor(Color.GREEN);
// //evaluateSubmission(v);
// }
// });
//
// Resources resources = com.moconnell.thehacker.WelcomeScreen.getResources();
// j= new ArrayList<Drawable>();
// j.add(resources.getDrawable(R.drawable.a_button));
// j.add(resources.getDrawable(R.drawable.b_button));
// j.add(resources.getDrawable(R.drawable.c_button));
// j.add(resources.getDrawable(R.drawable.d_button));
// j.add(resources.getDrawable(R.drawable.e_button));
//
generateImages();
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.in_game, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_in_game,
container, false);
return rootView;
}
}
//final TextView txtDir = (TextView) findViewById(R.id.txtDirections);
public void onTestButtonClickr(View view)
{
startActivity(new Intent("com.moconnell.thehacker.WelcomeScreen"));
}
public void click(View v)
{
//txtDir.setText("eed");//startActivity(new Intent("com.moconnell.thehacker.InGame"));
}
public void evaluateButton(View view)
{
ImageButton b = (ImageButton)view;
currentImage = (ImageButton)findViewById(R.id.ImageButton1_6);
Log.v("", "currentImage:" + currentImage.getResources());
//Log.v("", "buttnID:" + b.getId());
if( b.getId()==R.id.ImageButton1_5)
Log.v("", "1,5");
if( b.getId()==R.id.ImageButton2_5)
Log.v("", "2,5");
if( b.getId()==R.id.ImageButton3_5)
Log.v("", "3,5");
//Log.v("","buttonpressed:"+ b.getdi);
}
public void generateImages()
{
ImageButton b16 = (ImageButton)findViewById(R.id.ImageButton1_6);
Log.v("", "b16:" + b16.toString());
Log.v("", "pic:" + com.moconnell.thehacker.WelcomeScreen.j.get(1));
// b12.setImageDrawable(com.moconnell.thehacker.WelcomeScreen.j.get(1));
\
//int id = getResources().getIdentifier("thehacker/drawable/" + "a_button.png", null, null);
// b12.setImageDrawable(resources.getDrawable(R.drawable.e_button));
//b13.setImageResource(id);
// b14.setImageDrawable(j.get(2));
// Log.v("", b13.toString());
// Log.v("", j.get(1));
}
}
other class that works for reference
package com.moconnell.thehacker;
import java.util.ArrayList;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.os.Build;
public class WelcomeScreen extends ActionBarActivity {
public Button btnNewGame;
public Button mBtn;
public static ArrayList<Drawable> j;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnNewGame = (Button) findViewById(R.id.btnNewGame);
//btnNewGame.setOnClickListener(this);
////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////
// Button toggleButton = (Button) findViewById(R.id.btnHighScore);
// final ImageView img = (ImageView) findViewById(R.id.ImageView01);
// toggleButton.setOnClickListener(
//
// new View.OnClickListener() {
//
// public void onClick(View v) {
// img.setImageResource(R.drawable.fat_banana);
// }
//
// });
//////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
Resources resources = getResources();
j= new ArrayList<Drawable>();
j.add(resources.getDrawable(R.drawable.a_button));
j.add(resources.getDrawable(R.drawable.b_button));
j.add(resources.getDrawable(R.drawable.c_button));
j.add(resources.getDrawable(R.drawable.d_button));
j.add(resources.getDrawable(R.drawable.e_button));
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
public void onTestButtonClick(View view)
{
startActivity(new Intent("com.moconnell.thehacker.InGame"));
}
public void highScores(View view)
{
}
public void onTestButtonClickr(View view)
{
Button b = (Button)view;
String buttonText = b.getText().toString();
Log.v("", "butText:" + buttonText);
b.setText("cc");
Log.v("", "buttnID:" + b.getId());
if( b.getId()==R.id.btnNewGame)
Log.v("", "thsi is the new game button");
if( b.getId()==R.id.btnHighScore)
Log.v("", "thsi is the high scores button");
ImageView i = (ImageView)findViewById(R.id.ImageView01);
// .setImageResource(R.drawable.fat_banana);
Log.v("", "dispImg:" + i.getId());
Resources resources = getResources();
//i.setImageDrawable(resources.getDrawable(R.drawable.fat_banana));
i.setImageDrawable(j.get(1));
// if(buttonText.equals("View High Scores"))
// startActivity(new Intent("com.moconnell.thehacker.InGame"));
}
// private void empezarNewGame()
// {
//
// }
//
}
fragment_ingame
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:background="#drawable/background_tron"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.moconnell.thehacker.WelcomeScreen"
tools:ignore="MergeRootFrame"
android:orientation="vertical">
<TableLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:paddingTop="10dp"
android:gravity="center">
<Button
android:id="#+id/buttonReturn"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:onClick="onTestButtonClickr"
/>
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="53dp"
android:onClick="click"
android:src="#drawable/a_button"
android:gravity="center"/>
<TableRow
android:id="#+id/tableRow01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center">
<ImageButton
android:id="#+id/ImageButton1_6"
android:layout_width="50dp"
android:layout_height="50dp"
android:src="#drawable/a_display" />
<ImageButton
android:id="#+id/ImageButton2_6"
android:layout_width="50dp"
android:layout_height="50dp"
android:src="#drawable/b_display" />
<ImageButton
android:id="#+id/ImageButton3_6"
android:layout_width="50dp"
android:layout_height="50dp"
android:src="#drawable/c_display" />
<ImageButton
android:id="#+id/ImageButton4_6"
android:layout_width="50dp"
android:layout_height="50dp"
android:src="#drawable/d_display" />
<ImageButton
android:id="#+id/ImageButton5_6"
android:layout_width="50dp"
android:layout_height="50dp"
android:src="#drawable/e_display" />
</TableRow>
<TextView
android:id="#+id/txtDirections"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter the above code open lock"
android:textAppearance="?android:attr/textAppearanceMedium"
android:gravity="center" />
<TableRow
android:id="#+id/TableRow02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center">
<ImageButton
android:id="#+id/ImageButton1_5"
android:layout_width="50dp"
android:layout_height="50dp"
android:src="#drawable/loading"
android:onClick="evaluateButton"/>
<ImageButton
android:id="#+id/ImageButton2_5"
android:layout_width="50dp"
android:layout_height="50dp"
android:src="#drawable/loading"
android:onClick="evaluateButton"/>
<ImageButton
android:id="#+id/ImageButton3_5"
android:layout_width="50dp"
android:layout_height="50dp"
android:src="#drawable/loading"
android:onClick="evaluateButton" />
<ImageButton
android:id="#+id/ImageButton4_5"
android:layout_width="50dp"
android:layout_height="50dp"
android:src="#drawable/loading"
android:onClick="evaluateButton"/>
<ImageButton
android:id="#+id/ImageButton5_5"
android:layout_width="50dp"
android:layout_height="50dp"
android:src="#drawable/loading"
android:onClick="evaluateButton"/>
</TableRow>
<TableRow
android:id="#+id/TableRow03"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center" >
<ImageButton
android:id="#+id/ImageButton1_4"
android:layout_width="50dp"
android:layout_height="50dp"
android:src="#drawable/loading"
android:onClick="evaluateButton" />
<ImageButton
android:id="#+id/ImageButton2_4"
android:layout_width="50dp"
android:layout_height="50dp"
android:src="#drawable/loading"
android:onClick="evaluateButton" />
<ImageButton
android:id="#+id/ImageButton3_4"
android:layout_width="50dp"
android:layout_height="50dp"
android:src="#drawable/loading"
android:onClick="evaluateButton" />
<ImageButton
android:id="#+id/ImageButton4_4"
android:layout_width="50dp"
android:layout_height="50dp"
android:src="#drawable/loading"
android:onClick="evaluateButton" />
<ImageButton
android:id="#+id/ImageButton5_4"
android:layout_width="50dp"
android:layout_height="50dp"
android:src="#drawable/loading"
android:onClick="evaluateButton" />
</TableRow>
<TableRow
android:id="#+id/tableRow6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center" >
<ImageButton
android:id="#+id/ImageButton1_3"
android:layout_width="50dp"
android:layout_height="50dp"
android:src="#drawable/loading"
android:onClick="evaluateButton"/>
<ImageButton
android:id="#+id/ImageButton2_3"
android:layout_width="50dp"
android:layout_height="50dp"
android:src="#drawable/loading"
android:onClick="evaluateButton"/>
<ImageButton
android:id="#+id/ImageButton3_3"
android:layout_width="50dp"
android:layout_height="50dp"
android:src="#drawable/loading"
android:onClick="evaluateButton" />
<ImageButton
android:id="#+id/ImageButton4_3"
android:layout_width="50dp"
android:layout_height="50dp"
android:src="#drawable/loading"
android:onClick="evaluateButton" />
<ImageButton
android:id="#+id/ImageButton5_3"
android:layout_width="50dp"
android:layout_height="50dp"
android:src="#drawable/loading"
android:onClick="evaluateButton"/>
</TableRow>
<TableRow
android:id="#+id/tableRow5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center">
<ImageButton
android:id="#+id/ImageButton1_2"
android:layout_width="50dp"
android:layout_height="50dp"
android:src="#drawable/loading"
android:onClick="evaluateButton"/>
<ImageButton
android:id="#+id/ImageButton2_2"
android:layout_width="50dp"
android:layout_height="50dp"
android:src="#drawable/loading"
android:onClick="evaluateButton" />
<ImageButton
android:id="#+id/ImageButton3_2"
android:layout_width="50dp"
android:layout_height="50dp"
android:src="#drawable/loading"
android:onClick="evaluateButton"/>
<ImageButton
android:id="#+id/ImageButton4_2"
android:layout_width="50dp"
android:layout_height="50dp"
android:src="#drawable/loading"
android:onClick="evaluateButton"/>
<ImageButton
android:id="#+id/ImageButton5_2"
android:layout_width="50dp"
android:layout_height="50dp"
android:src="#drawable/loading"
android:onClick="evaluateButton" />
</TableRow>
</TableLayout>
</FrameLayout>
activity_inGame
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.moconnell.thehacker.InGame"
tools:ignore="MergeRootFrame" />
You are calling generateImages() function before fragment with view resource fragment_ingame is attached. So in generateImages() there is no ImageButton is avaiable having id R.id.ImageButton1_6.
Ultimately the issue was I was editing the fragment and the referring to the activity. Was to replace the welcome screen class line that states:
setContentView(R.layout.activity_main);
to one reflecting of the xml i was editing. Like this:
setContentView(R.layout.fragment_in_game);

Null Pointer Exception - SetOnClickedListener

I'm having a problem with Null Pointer Exception which is threw by setOnClickListener.
I'm trying to make an application processing an image, and I want to load and image from gallery.
I've been reading lots of posts here but I still don't understand what's happening.
Why Am I getting NullPointerException?
Here is my code:
import android.net.Uri;
import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.graphics.*;
import android.graphics.drawable.*;
import android.content.Intent;
import android.app.Activity;
public class MainActivity extends ActionBarActivity {
Bitmap oryginal;
ImageView image;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
image = (ImageView) findViewById(R.id.imageView);
image.setOnClickListener(new View.OnClickListener() { here is the Null Pointer Exception
#Override
public void onClick(View view) {
Intent gallery = new Intent();
gallery.setType("image/*");
gallery.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(gallery,"Select Image"),1);
}
});
}
public void onActivityResult(int requestCode , int resultCode, Intent data)
{
if(resultCode == RESULT_OK)
{
if(requestCode ==1)
{
image.setImageURI(data.getData());
}
}
}
Here is my fragment_main.xml where I have my ImageView (in the first paragraph)
<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.example.app.MainActivity$PlaceholderFragment"
android:background="#ffe93d"
android:focusable="false">
<ImageView
android:layout_width="300dp"
android:layout_height="400dp"
android:id="#+id/imageView"
android:src="#drawable/tucano"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentEnd="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/oryginal"
android:id="#+id/oryginal"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:onClick="Oryginal" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/kotim"
android:layout_below="#+id/imageView"
android:layout_toLeftOf="#+id/oryginal"
android:visibility="invisible"
android:src="#drawable/kot" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/lennaim"
android:layout_above="#+id/oryginal"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:visibility="invisible"
android:src="#drawable/lenna" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/lennaim"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:visibility="invisible"
android:src="#drawable/obrazek"
android:id="#+id/stworim"
android:focusableInTouchMode="false" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/help"
android:id="#+id/help"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:onClick="Help" />
Details:
Details:
04-07 16:01:14.162 1451-1451/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.app/com.example.app.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.app.MainActivity.onCreate(MainActivity.java:36)
at android.app.Activity.performCreate(Activity.java:5104)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
The problem is that you're setting your content as this:
setContentView(R.layout.activity_main);
But as per your code, the required ImageView is in this file: Here is my fragment_main.xml where I have my ImageView (in the first paragraph), therefore my assumption of:
image = (ImageView) findViewById(R.id.imageView); is returning null
is true and you're getting the NullPointerException error. You can just find Views that correspond to the layout declared in your setContentView() statement, otherwise it will return null.
Your ImageView is in Fragment Layout while you are trying to initialize variable using Activity's method FindViewByID. To do that properly get your fragment's View reference and then call View.FindViewByID(). Also I would advise to change your Image's View ID just in case.

Attempting to Save Data In a SQLite Database - Cleaned (no major issues) Still Force Closes

I'm a bit new to StackOverflow and I was wondering if I could have a bit of input on the following issue: I'm attempting to save a bit of data in a sqlite database but each time I attempt to do so the app force closes and I'm not sure why. I've cleaned the file and there are no issues. (I have no idea what I've done wrong - but something has been programmed incorrectly.)
JAVA:
import android.app.Activity;
import android.app.AlertDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.ViewGroup;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.TimePicker;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.text.format.DateFormat;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.app.Activity;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.text.format.DateFormat;
import android.widget.TimePicker;
import com.nfc.linkingmanager.TimePickerFragment.TimePickedListener;
import java.util.Calendar;
public class AddEditCountry extends Activity implements TimePickedListener
{
private TextView mPickedTimeText;
private Button mPickTimeButton;
private long rowID;
private EditText nameEt;
private EditText capEt;
private EditText codeEt;
private TimePicker timeEt;
public static final String KEY_BUNDLE_TIME = "time";
public static final String KEY_BUNDLE_MIN = "min";
#Override
public void onCreate(Bundle savedInstanceState)
{
setContentView(R.layout.add_country); // where your_layout is the name of the xml file with the layout you want to use minus the .xml extention
//this layout must contain all of these views below that you are trying to initialize
nameEt = (EditText) findViewById(R.id.nameEdit);
capEt = (EditText) findViewById(R.id.capEdit);
codeEt = (EditText) findViewById(R.id.codeEdit);
timeEt = (TimePicker) findViewById(R.id.timeEdit);
Bundle extras = getIntent().getExtras();
if (extras != null)
{
rowID = extras.getLong("row_id");
nameEt.setText(extras.getString("name"));
capEt.setText(extras.getString("cap"));
codeEt.setText(extras.getString("code"));
String time = extras.getString("time");
String[] parts = time.split(":");
timeEt.setCurrentHour(Integer.valueOf(parts[0]));
timeEt.setCurrentMinute(Integer.valueOf(parts[1]));
timeEt.setIs24HourView(false);
}
Button saveButton =(Button) findViewById(R.id.saveBtn);
saveButton.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
if (nameEt.getText().length() != 0)
{
AsyncTask<Object, Object, Object> saveContactTask =
new AsyncTask<Object, Object, Object>()
{
#Override
protected Object doInBackground(Object... params)
{
saveContact();
return null;
}
#Override
protected void onPostExecute(Object result)
{
finish();
}
};
saveContactTask.execute((Object[]) null);
}
else
{
AlertDialog.Builder alert = new AlertDialog.Builder(AddEditCountry.this);
alert.setTitle(R.string.errorTitle);
alert.setMessage(R.string.errorMessage);
alert.setPositiveButton(R.string.errorButton, null);
alert.show();
}
}
});
}
private void saveContact()
{
DatabaseConnector dbConnector = new DatabaseConnector(this);
if (getIntent().getExtras() == null)
{
dbConnector.insertContact(nameEt.getText().toString(),
capEt.getText().toString(),
timeEt.getCurrentHour().toString() + ":"
+ timeEt.getCurrentMinute().toString(),
codeEt.getText().toString());
}
else
{
dbConnector.insertContact(nameEt.getText().toString(),
capEt.getText().toString(),
timeEt.getCurrentHour().toString() + ":"
+ timeEt.getCurrentMinute().toString(),
codeEt.getText().toString());
}
}
#Override
public void onTimePicked(Calendar time)
{
// display the selected time in the TextView
mPickedTimeText.setText(DateFormat.format("h:mm a", time));
}
}
XML:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content" android:layout_weight="1">
<LinearLayout android:id="#+id/linearLayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="5dp">
<EditText android:id="#+id/nameEdit"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:imeOptions="actionNext"
android:hint="#string/name_hint"
android:inputType="textPersonName|textCapWords"/>
<EditText android:id="#+id/capEdit"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:imeOptions="actionNext"
android:hint="#string/cap_hint"
android:inputType="textPersonName|textCapWords"/>
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Data Limit"
android:textColor="#ffffff"
android:textAppearance="?android:textAppearanceMedium" />
<SeekBar
android:id="#+id/seekBar1"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1.0"
android:gravity="left"
android:textColor="#ffffff"
android:text="10MB" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1.0"
android:gravity="right"
android:textColor="#ffffff"
android:text="Unlimited Data" />
</LinearLayout>
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Bandwidth Limit"
android:textColor="#ffffff"
android:textAppearance="?android:textAppearanceMedium" />
<SeekBar
android:id="#+id/seekBar1"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1.0"
android:gravity="left"
android:textColor="#ffffff"
android:text="10kbs" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1.0"
android:textColor="#ffffff"
android:gravity="right"
android:text="Unlimited Bandwidth" />
</LinearLayout>
<TextView
android:id="#+id/TextView02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:textAppearanceSmall" />
<TextView
android:id="#+id/TextView02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="WiFi Time Limit"
android:textColor="#ffffff"
android:textAppearance="?android:textAppearanceMedium" />
<TimePicker
android:id="#+id/timeEdit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:layout_weight="1.0" />
<EditText
android:id="#+id/codeEdit"
android:inputType="textUri"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:ems="10"
android:lines="1"
android:hint="#string/code_hint"
android:imeOptions="actionNext" />
<Button android:id="#+id/saveBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:layout_gravity="center_horizontal"
android:text="#string/save_btn"/>
</LinearLayout>
</ScrollView>
PROBLEMS:
Cleaned - No Problems
LOGCAT:
03-29 13:23:28.950: D/OpenGLRenderer(20744): Enabling debug mode 0
03-29 13:23:33.780: D/AndroidRuntime(20744): Shutting down VM
03-29 13:23:33.780: W/dalvikvm(20744): threadid=1: thread exiting with uncaught exception (group=0x41f7b930)
03-29 13:23:33.790: E/AndroidRuntime(20744): FATAL EXCEPTION: main
03-29 13:23:33.790: E/AndroidRuntime(20744): android.app.SuperNotCalledException: Activity {com.app.gamedemo/com.app.gamedemo.AddEditCountry} did not call through to super.onCreate()
03-29 13:23:33.790: E/AndroidRuntime(20744): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2146)
03-29 13:23:33.790: E/AndroidRuntime(20744): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
03-29 13:23:33.790: E/AndroidRuntime(20744): at android.app.ActivityThread.access$600(ActivityThread.java:141)
03-29 13:23:33.790: E/AndroidRuntime(20744): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
03-29 13:23:33.790: E/AndroidRuntime(20744): at android.os.Handler.dispatchMessage(Handler.java:99)
03-29 13:23:33.790: E/AndroidRuntime(20744): at android.os.Looper.loop(Looper.java:137)
03-29 13:23:33.790: E/AndroidRuntime(20744): at android.app.ActivityThread.main(ActivityThread.java:5041)
03-29 13:23:33.790: E/AndroidRuntime(20744): at java.lang.reflect.Method.invokeNative(Native Method)
03-29 13:23:33.790: E/AndroidRuntime(20744): at java.lang.reflect.Method.invoke(Method.java:511)
03-29 13:23:33.790: E/AndroidRuntime(20744): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
03-29 13:23:33.790: E/AndroidRuntime(20744): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
03-29 13:23:33.790: E/AndroidRuntime(20744): at dalvik.system.NativeStart.main(Native Method)
03-29 13:23:35.390: I/Process(20744): Sending signal. PID: 20744 SIG: 9
The problem is here in your onCreate()
#Override
public void onCreate(Bundle savedInstanceState)
{
nameEt = (EditText) findViewById(R.id.nameEdit);
capEt = (EditText) findViewById(R.id.capEdit);
codeEt = (EditText) findViewById(R.id.codeEdit);
timeEt = (TimePicker) findViewById(R.id.timeEdit);
You need to call setContentView() before trying to access your EditTexts and so on. Your Views "live" within your layout (xml file) so they are null until you inflate the layout. Change it to someting like
#Override
public void onCreate(Bundle savedInstanceState)
{
setContentView(R.layout.your_layout); // where your_layout is the name of the xml file with the layout you want to use minus the .xml extention
//this layout must contain all of these views below that you are trying to initialize
nameEt = (EditText) findViewById(R.id.nameEdit);
capEt = (EditText) findViewById(R.id.capEdit);
codeEt = (EditText) findViewById(R.id.codeEdit);
timeEt = (TimePicker) findViewById(R.id.timeEdit);
Edit
Just like the error says, you are trying to cast a TextView to a TimePicker. Here
timeEt = (TimePicker) findViewById(R.id.timeEdit);
(R.id.timeEdit) points to a TextView but here
private TimePicker timeEt;
you declare it as a TimePicker. If you want it to be a TimePicker then change it in your xml
`<TimePicker
android:id="#+id/timeEdit"
style="#style/StyleText"/> `
Also, you have multiple ids in your xml
android:id="#+id/codeText"
might want to change that
Second Edit
03-29 13:23:33.790: E/AndroidRuntime(20744): android.app.SuperNotCalledException: Activity {com.app.gamedemo/com.app.gamedemo.AddEditCountry} did not call through to super.onCreate()
This line in the logcat says it all. You didn't call super.onCreate(). Add the following line as the first line in your onCreate() method
super.onCreate(savedInstanceState);
When reading your logcat, look for where it says Fatal Exception. The next line should say what it is (Null Pointer Exception, Class Cast Exception, etc...) then look for the first line that references your package name and it will tell you where to start looking for the error. Ex. Main.java 57 tells you that whatever the fatal exception was occurs in your Main.java file at line 57. The problem may originally come from somewhere else but this is always a good place to start so you can narrow it down and post relevant code if you need help.

Categories