Null pointer searching findViewById android app Java - 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);

Related

Application worked before but now it just stops

Im new to android programming and i have searched my eyes out for a solution to my problem but i cant find it anywhere. Im building an application with 3 screen layouts but i have a problem with the last screen:
The problem:
The application starts and the 2 first screens works good but when i go to the last screen(activity_katag.xml & katagActivity.java) and press "Deal1" the application stops and gives me the error "Unfortunately, "AppName" has stopped."
LogCat Error File:
13:32:12.270: W/dalvikvm(614): threadid=1: thread exiting with uncaught exception (group=0x40a122a0)
03-12 13:32:12.290: E/AndroidRuntime(614): FATAL EXCEPTION: main
03-12 13:32:12.290: E/AndroidRuntime(614): java.lang.NullPointerException
03-12 13:32:12.290: E/AndroidRuntime(614): at com.appname.fundeals.DealsAdapter.getChildrenCount(DealsAdapter.java:42)
03-12 13:32:12.290: E/AndroidRuntime(614): at android.widget.ExpandableListConnector.refreshExpGroupMetadataList(ExpandableListConnector.java:563)
03-12 13:32:12.290: E/AndroidRuntime(614): at android.widget.ExpandableListConnector.expandGroup(ExpandableListConnector.java:688)
03-12 13:32:12.290: E/AndroidRuntime(614): at android.widget.ExpandableListView.handleItemClick(ExpandableListView.java:562)
03-12 13:32:12.290: E/AndroidRuntime(614): at android.widget.ExpandableListView.performItemClick(ExpandableListView.java:522)
03-12 13:32:12.290: E/AndroidRuntime(614): at android.widget.AbsListView$PerformClick.run(AbsListView.java:2859)
03-12 13:32:12.290: E/AndroidRuntime(614): at android.widget.AbsListView$1.run(AbsListView.java:3533)
03-12 13:32:12.290: E/AndroidRuntime(614): at android.os.Handler.handleCallback(Handler.java:615)
03-12 13:32:12.290: E/AndroidRuntime(614): at android.os.Handler.dispatchMessage(Handler.java:92)
03-12 13:32:12.290: E/AndroidRuntime(614): at android.os.Looper.loop(Looper.java:137)
03-12 13:32:12.290: E/AndroidRuntime(614): at android.app.ActivityThread.main(ActivityThread.java:4745)
03-12 13:32:12.290: E/AndroidRuntime(614): at java.lang.reflect.Method.invokeNative(Native Method)
03-12 13:32:12.290: E/AndroidRuntime(614): at java.lang.reflect.Method.invoke(Method.java:511)
03-12 13:32:12.290: E/AndroidRuntime(614): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
03-12 13:32:12.290: E/AndroidRuntime(614): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
03-12 13:32:12.290: E/AndroidRuntime(614): at dalvik.system.NativeStart.main(Native Method)
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.appname.fundeals"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/Theme.AppCompat" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".inloggActivity" />
<activity android:name=".katagActivity" />
</application>
</manifest>
activity_main.xml:
<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:background="#drawable/bakgrund"
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.appname.fundeals.MainActivity" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:text="Random Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView1"
android:layout_marginTop="75dp"
android:layout_marginLeft="10dp"
android:text="Username:"
android:textAppearance="?android:attr/textAppearanceMedium" />
/>
<EditText
android:id="#+id/usernameET"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/textView2"
android:layout_marginLeft="35dp"
android:layout_toRightOf="#+id/textView2"
android:hint="Användarnamn" >
<requestFocus />
</EditText>
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView2"
android:layout_below="#+id/textView2"
android:layout_marginTop="40dp"
android:text="Password:"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="#+id/passwordET"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/textView3"
android:layout_alignLeft="#+id/usernameET"
android:layout_alignRight="#+id/usernameET"
android:hint="lösenord"
android:inputType="textPassword" />
<TextView
android:id="#+id/attemptsLeftTV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView3"
android:layout_below="#+id/textView3"
android:layout_marginLeft="30dp"
android:layout_marginTop="48dp"
android:text="Attempts Left:"
android:visibility="invisible"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/numberOfRemainingLoginAttemptsTV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/textView1"
android:layout_alignTop="#+id/attemptsLeftTV"
android:visibility="invisible" />
<TextView
android:id="#+id/loginLockedTV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/loginBtn"
android:layout_marginTop="35dp"
android:layout_centerHorizontal="true"
android:textAppearance="?android:attr/textAppearanceMedium"
android:visibility="invisible" />
<Button
android:id="#+id/loginBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/numberOfRemainingLoginAttemptsTV"
android:layout_centerHorizontal="true"
android:onClick="authenticateLogin"
android:text="Login" />
<Button
android:id="#+id/FacebookBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/loginBtn"
android:layout_toLeftOf="#+id/usernameET"
android:onClick="authenticateLogin"
android:text="Facebook" />
MainActivity.java:
package com.appname.fundeals;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import com.appname.fundeals.R;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
#SuppressLint("NewApi")
public class MainActivity extends ActionBarActivity {
public class onClick implements OnClickListener {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent(MainActivity.this, inloggActivity.class));
}
}
private EditText username;
private EditText password;
private Button login;
private TextView loginLockedTV;
private Button facebookBtn;
private TextView attemptsLeftTV;
private TextView numberOfRemainingLoginAttemptsTV;
int numberOfRemainingLoginAttempts = 3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
facebookBtn = (Button) findViewById(R.id.FacebookBtn);
facebookBtn.setOnClickListener(new onClick());
setupVariables();
}
public void authenticateLogin(View view) {
if (username.getText().toString().equals("admin") &&
password.getText().toString().equals("admin")) {
Toast.makeText(getApplicationContext(), "Hello admin!",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Seems like you 're not admin!",
Toast.LENGTH_SHORT).show();
numberOfRemainingLoginAttempts--;
attemptsLeftTV.setVisibility(View.VISIBLE);
numberOfRemainingLoginAttemptsTV.setVisibility(View.VISIBLE);
numberOfRemainingLoginAttemptsTV.setText(Integer.toString(numberOfRemainingLoginAttempts));
if (numberOfRemainingLoginAttempts == 0) {
login.setEnabled(false);
loginLockedTV.setVisibility(View.VISIBLE);
loginLockedTV.setBackgroundColor(Color.RED);
loginLockedTV.setText("LOGIN LOCKED!!!");
}
}
}
private void setupVariables() {
username = (EditText) findViewById(R.id.usernameET);
password = (EditText) findViewById(R.id.passwordET);
login = (Button) findViewById(R.id.loginBtn);
loginLockedTV = (TextView) findViewById(R.id.loginLockedTV);
attemptsLeftTV = (TextView) findViewById(R.id.attemptsLeftTV);
numberOfRemainingLoginAttemptsTV = (TextView) findViewById(R.id.numberOfRemainingLoginAttemptsTV);
numberOfRemainingLoginAttemptsTV.setText(Integer.toString(numberOfRemainingLoginAttempts));
}
}
activity_inlogg.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:background="#drawable/bakgrund" >
<TextView
android:id="#+id/textViewFirst"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="14dp"
android:layout_marginTop="20dp"
android:text="Random Text."
android:textStyle="bold" />
<ImageButton
android:id="#+id/imageButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textViewFirst"
android:layout_centerHorizontal="true"
android:layout_marginTop="25dp"
android:background="#00000000"
android:src="#drawable/rkeepklar" />
<ImageButton
android:id="#+id/imageButton3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/imageButton2"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_marginTop="6dp"
android:background="#00000000"
android:src="#drawable/stklarmarkerad" />
<ImageButton
android:id="#+id/imageButton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/imageButton1"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_marginTop="4dp"
android:background="#00000000"
android:src="#drawable/ndklar" />
</RelativeLayout>
inloggActivity.java (screen2):
package com.appname.fundeals;
import com.appname.fundeals.inloggActivity.OnClick;
import com.appname.fundeals.R;
import android.app.Activity;
import android.graphics.Color;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.widget.Toast;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class inloggActivity extends Activity {
public class OnClick implements OnClickListener {
#Override
public void onClick(View v) {
startActivity(new Intent(inloggActivity.this, katagActivity.class));
}
}
private Button imageButton1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inlogg);
Button imageButton1 = (Button) findViewById(R.id.imageButton1);
imageButton1.setOnClickListener(new OnClick());
}
}
activity_katag.xml (screen3):
<?xml version="1.0" encoding="utf-8"?>
<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="match_parent"
android:background="#drawable/bakgrund"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="16dp"
android:paddingBottom="16dp"
>
<ExpandableListView
android:id="#+id/exp_list"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:indicatorLeft="?android:attr/expandableListPreferredItemIndicatorLeft"
android:divider="#A4C739"
android:dividerHeight="0.5dp"
></ExpandableListView>
</RelativeLayout>
katagActivity.java:
package com.appname.fundeals;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.widget.ExpandableListView;
public class katagActivity extends Activity {
private static final HashMap<String, List<String>> Deals_Catagory = null;
HashMap<String, List<String>> Deals_category;
List<String> Deals_list;
ExpandableListView Exp_list;
DealsAdapter adapter;
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_katag);
Exp_list = (ExpandableListView) findViewById(R.id.exp_list);
Deals_category = DataProvider.getInfo();
Deals_list = new ArrayList<String>(Deals_category.keySet());
adapter = new DealsAdapter(this, Deals_Catagory, Deals_list);
Exp_list.setAdapter(adapter);
}
}
DealsAdapter.java:
package com.appname.fundeals;
import java.util.HashMap;
import java.util.List;
import com.appname.fundeals.R;
import android.content.Context;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.TextView;
public class DealsAdapter extends BaseExpandableListAdapter {
private Context ctx;
private HashMap<String, List<String>> Deals_Catagory;
private List<String> Deals_List;
public DealsAdapter(Context ctx, HashMap<String, List<String>> Deals_Catagory, List<String> Deals_List) {
this.ctx = ctx;
this.Deals_Catagory = Deals_Catagory;
this.Deals_List = Deals_List;
// TODO Auto-generated constructor stub
}
#Override
public int getGroupCount() {
return Deals_List.size();
}
#Override
public int getChildrenCount(int arg0) {
return Deals_Catagory.get(Deals_List.get(arg0)).size();
}
#Override
public Object getGroup(int arg0) {
return Deals_List.get(arg0);
}
#Override
public Object getChild(int parent, int child) {
// TODO Auto-generated method stub
return Deals_Catagory.get(Deals_List.get(parent)).get(child);
}
#Override
public long getGroupId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public long getChildId(int parent, int child) {
// TODO Auto-generated method stub
return child;
}
#Override
public boolean hasStableIds() {
// TODO Auto-generated method stub
return false;
}
#Override
public View getGroupView(int parent, boolean isExpanded, View convertView, ViewGroup parentView) {
// TODO Auto-generated method stub
String group_title = (String) getGroup(parent);
if(convertView == null)
{
LayoutInflater inflator = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflator.inflate(R.layout.parent_deal1, parentView, false);
}
TextView parent_textView = (TextView) convertView.findViewById(R.id.parent_deal1);
parent_textView.setTypeface(null, Typeface.BOLD);
parent_textView.setText(group_title);
return convertView;
}
#Override
public View getChildView(int parent, int child, boolean lastChild, View convertView,
ViewGroup parentview) {
String child_title = (String) getChild(parent, child);
if (convertView == null)
{
LayoutInflater inflator = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflator.inflate(R.layout.child_deal1, parentview, false);
}
// TODO Auto-generated method stub
TextView child_textView = (TextView) convertView.findViewById(R.id.child_deal1);
child_textView.setText(child_title);
return convertView;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
return false;
}
}
DataProvider.java:
package com.appname.fundeals;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class DataProvider {
public static HashMap<String, List<String>> getInfo()
{
HashMap<String, List<String>> DealsDetails = new HashMap<String, List<String>>();
List<String> Deal_1 = new ArrayList<String>();
Deal_1.add("Text");
List<String> Deal_2 = new ArrayList<String>();
Deal_2.add("Text");
List<String> Deal_3 = new ArrayList<String>();
Deal_3.add("Text");
List<String> Deal_4 = new ArrayList<String>();
Deal_4.add("Text");
DealsDetails.put("Deal 1", Deal_1);
DealsDetails.put("Deal 2", Deal_2);
DealsDetails.put("Deal 3", Deal_3);
DealsDetails.put("Deal 4", Deal_4);
return DealsDetails;
}
}
You try to convert ImageButton to Button so Error come.
<ImageButton
android:id="#+id/imageButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textViewFirst"
android:layout_centerHorizontal="true"
android:layout_marginTop="25dp"
android:background="#00000000"
android:src="#drawable/rkeepklar" />
Button imageButton1 = (Button) findViewById(R.id.imageButton1);
imageButton1.setOnClickListener(new OnClick());
Do same in other Button also
Updated code
ImageButton imageButton1 = (ImageButton) findViewById(R.id.imageButton1);
imageButton1.setOnClickListener(new OnClick());
Caused by: java.lang.ClassCastException: android.widget.ImageButton
cannot be cast to android.widget.Button
A ClassCastException is an Exception that can occur in a Java program when you try to improperly convert a class from one type to another.
Don't
Button imageButton1 = (Button) findViewById(R.id.imageButton1);
Do
ImageButton imageButton1 = (ImageButton) findViewById(R.id.imageButton1);
Because your XML
<ImageButton
android:id="#+id/imageButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textViewFirst"
android:layout_centerHorizontal="true"
android:layout_marginTop="25dp"
android:background="#00000000"
android:src="#drawable/rkeepklar" />

How to use auto complete text in android [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am new in android. I created simple application,that contains autocomplete text field.I wrote some code but unfortunately application stopped when i run. there is no error, How do i fix...
Please any one help!
Mycode here:
Mainactivity.java
package com.h2o;
import android.app.Activity;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.location.Address;
import android.location.Geocoder;
import android.support.v4.app.DialogFragment;
import android.os.Bundle;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.res.Configuration;
import android.support.annotation.Nullable;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
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.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends FragmentActivity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
CustomDrawerAdapter adapter;
List<DrawerItem> dataList;
EditText mEdit;
private String[] states;
private Spinner spinner;
AutoCompleteTextView autoTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String[] city= getResources().getStringArray(R.array.city);
autoTextView = (AutoCompleteTextView) findViewById(R.id.city_autoCompleteTextView);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,city);
autoTextView.setThreshold(1);
autoTextView.setAdapter(arrayAdapter);
// Initializing
dataList = new ArrayList<DrawerItem>();
mTitle = mDrawerTitle = getTitle();
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
GravityCompat.START);
// Add Drawer Item to dataList
dataList.add(new DrawerItem(true)); // adding a spinner to the list - 0
dataList.add(new DrawerItem("Wallet")); // adding a header to the list - 1
dataList.add(new DrawerItem("Balance", R.drawable.ic_balance)); // - 2
dataList.add(new DrawerItem("Profile"));// adding a header to the list - 3
dataList.add(new DrawerItem("Personal", R.drawable.ic_account));
dataList.add(new DrawerItem("Work", R.drawable.ic_account));
dataList.add(new DrawerItem("Address", R.drawable.ic_account));
dataList.add(new DrawerItem("Vehicle", R.drawable.ic_car));
dataList.add(new DrawerItem("Preference", R.drawable.ic_pref));
dataList.add(new DrawerItem("Other Option")); // adding a header to the list
dataList.add(new DrawerItem("About", R.drawable.ic_action_about));
dataList.add(new DrawerItem("Settings", R.drawable.ic_action_settings));
dataList.add(new DrawerItem("Help", R.drawable.ic_action_help));
adapter = new CustomDrawerAdapter(this, R.layout.custom_drawer_item,
dataList);
mDrawerList.setAdapter(adapter);
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.drawer_open,
R.string.drawer_close) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
invalidateOptionsMenu(); // creates call to
// onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu(); // creates call to
// onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
//Calendar picker
public void selectDate(View view) {
DialogFragment newFragment = new SelectDateFragment();
newFragment.show(getSupportFragmentManager(), "DatePicker");
}
public void populateSetDate(int year, int month, int day) {
mEdit = (EditText)findViewById(R.id.dobText);
mEdit.setText(month + "/" + day + "/" + year);
}
public class SelectDateFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener
{
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Calendar calendar = Calendar.getInstance();
int yy = calendar.get(Calendar.YEAR);
int mm = calendar.get(Calendar.MONTH);
int dd = calendar.get(Calendar.DAY_OF_MONTH);
return new DatePickerDialog(getActivity(), this, yy, mm, dd);
}
public void onDateSet(DatePicker view, int yy, int mm, int dd) {
populateSetDate(yy, mm + 1, dd);
}
}
//Spinner
#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 void SelectItem(String item, int possition) {
Fragment fragment = null;
Bundle args = new Bundle();
switch(item) {
case "Balance": fragment = new BalanceFragment(); break;
case "Personal": fragment = new PersonalFragment(); break;
case "Work": fragment = new WorkFragment(); break;
case "Address": fragment = new AddressFragment(); break;
case "Vehicle": fragment = new VehicleFragment(); break;
case "Preference": fragment = new PreferenceFragment(); break;
case "About": fragment = new AboutFragment(); break;
case "Settings": fragment = new SettingsFragment(); break;
case "Help": fragment = new HelpFragment(); break;
default: fragment = new DefaultFragment(); break;
}
fragment.setArguments(args);
FragmentManager frgManager = getFragmentManager();
frgManager.beginTransaction().replace(R.id.content_frame, fragment)
.commit();
mDrawerList.setItemChecked(possition, true);
setTitle(dataList.get(possition).getItemName());
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
// ActionBarDrawerToggle will take care of this.
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return false;
}
private class DrawerItemClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
if (dataList.get(position).getTitle() == null) {
SelectItem(dataList.get(position).getItemName(), position);
}
}
}
}
log cat:
06-03 12:23:32.446 2843-2843/? I/art﹕ Not late-enabling -Xcheck:jni (already on)
06-03 12:23:32.637 2843-2843/com.h2o D/AndroidRuntime﹕ Shutting down VM
06-03 12:23:32.638 2843-2843/com.h2o E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.h2o, PID: 2843
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.h2o/com.h2o.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.AutoCompleteTextView.setThreshold(int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
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)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.AutoCompleteTextView.setThreshold(int)' on a null object reference
at com.h2o.MainActivity.onCreate(MainActivity.java:73)
at android.app.Activity.performCreate(Activity.java:5937)
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)
Layout file
<?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:weightSum="1">
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:weightSum="1">
<TextView
android:layout_width="wrap_content"
android:layout_height="40dp"
android:text="Address Details"
android:id="#+id/address"
android:textColor="#ff000000"
android:textSize="20dp"
android:layout_marginLeft="10dp"
android:gravity="center" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="1"
android:layout_weight="0.03">
<TextView
android:layout_width="wrap_content"
android:layout_height="33dp"
android:text="Tag Address"
android:id="#+id/residential"
android:textColor="#ff000000"
android:layout_marginLeft="10dp"
android:layout_gravity="center"
android:gravity="center" />
<RadioGroup
android:id="#+id/radioGroup"
android:layout_width="276dp"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_gravity="center"
android:weightSum="1">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Home"
android:id="#+id/home"
android:layout_gravity="center"
android:textColor="#FF000000"
android:checked="false"
android:layout_weight="0.22"
android:layout_marginLeft="10dp" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Office"
android:id="#+id/office"
android:textColor="#FF000000"
android:checked="false"
android:layout_gravity="center" />
</RadioGroup>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="1"
android:layout_weight="0.06">
<TextView
android:layout_width="48dp"
android:layout_height="wrap_content"
android:text="Line 1"
android:id="#+id/address1"
android:textColor="#ff000000"
android:layout_marginLeft="10dp"
android:gravity="center" />
<EditText
android:layout_width="291dp"
android:layout_height="wrap_content"
android:inputType="textPostalAddress"
android:ems="10"
android:id="#+id/addressText"
android:layout_marginLeft="50dp"
android:textColor="#ff000000"
android:layout_weight="1.04" /> />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="1"
android:layout_weight="0.06">
<TextView
android:layout_width="48dp"
android:layout_height="wrap_content"
android:text="Line 2"
android:id="#+id/address2"
android:textColor="#ff000000"
android:layout_marginLeft="10dp"
android:gravity="center" />
<EditText
android:layout_width="291dp"
android:layout_height="wrap_content"
android:inputType="textPostalAddress"
android:ems="10"
android:id="#+id/address2Text"
android:layout_marginLeft="50dp"
android:textColor="#ff000000"
android:layout_weight="1.04" /> />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="1"
android:layout_weight="0.06">
<TextView
android:layout_width="48dp"
android:layout_height="wrap_content"
android:text="City"
android:id="#+id/city"
android:textColor="#ff000000"
android:layout_marginLeft="5dp"
android:gravity="center"
android:layout_gravity="center" />
<AutoCompleteTextView
android:layout_width="112dp"
android:layout_height="wrap_content"
android:id="#+id/city_autoCompleteTextView"
android:ems="10"
android:layout_gravity="center" />
<TextView
android:layout_width="wrap_content"
android:layout_height="33dp"
android:text="Zipcode"
android:id="#+id/zipcode"
android:textColor="#ff000000"
android:layout_marginLeft="10dp"
android:layout_gravity="center"
android:gravity="center" />
<EditText
android:layout_width="291dp"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/zipcodeText"
android:layout_marginLeft="10dp"
android:textColor="#ff000000"
android:layout_weight="1.04" /> />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="50dp"
android:weightSum="1"
android:layout_weight="0.09">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Country"
android:id="#+id/country"
android:textColor="#ff000000"
android:layout_marginLeft="10dp"
android:layout_gravity="center" />
<Spinner
android:layout_width="75dp"
android:layout_height="31dp"
android:id="#+id/countrySpinner"
android:entries="#array/country_list"
android:layout_marginLeft="40dp"
android:spinnerMode="dropdown"
android:outlineProvider="bounds"
android:layout_gravity="center" />
<TextView
android:layout_width="51dp"
android:layout_height="match_parent"
android:text="State"
android:id="#+id/state"
android:textColor="#ff000000"
android:layout_marginLeft="10dp"
android:layout_gravity="center"
android:gravity="center" />
<Spinner
android:layout_width="75dp"
android:layout_height="31dp"
android:id="#+id/stateSpinner"
android:entries="#array/state_list"
android:spinnerMode="dropdown"
android:outlineProvider="bounds"
android:layout_weight="0.10"
android:layout_gravity="center"
android:layout_marginLeft="10dp" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="1"
android:layout_weight="0.06">
<TextView
android:layout_width="wrap_content"
android:layout_height="33dp"
android:text="Landmark"
android:id="#+id/landmark"
android:textColor="#ff000000"
android:layout_marginLeft="10dp"
android:layout_gravity="center"
android:gravity="center" />
<EditText
android:layout_width="291dp"
android:layout_height="wrap_content"
android:inputType="textPostalAddress"
android:ems="10"
android:id="#+id/landmarkText"
android:layout_marginLeft="40dp"
android:textColor="#ff000000"
android:layout_weight="1.04" /> />
</LinearLayout>
</LinearLayout>
Thanks for advance!!
Once check ID for below line in layout activity_main file
autoTextView = (AutoCompleteTextView) findViewById(R.id.city_autoCompleteTextView);
Here autoTextView is giving null.

Android application crashes every time on startup

I started coding my first app in Android Studio, what it should do at this stage is that you click a button with the digit and it outputs it into the textfield. When i run this code the application crashes right on startup and I have no idea what's wrong.
MyActivity.java
package com.example.david.calculator;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import org.w3c.dom.Text;
public class MyActivity extends Activity {
EditText results;
private int number;
final EditText result = (EditText) findViewById(R.id.number);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
Button one = (Button) findViewById(R.id.button);
one.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
BtnPressed(1);
}
});
}
private void BtnPressed(int i) {
result.setText(Integer.toString(i));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.my, 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);
}
}
activity_my.xml
<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=".MyActivity">
<EditText
android:layout_width="fill_parent"
android:layout_height="50dp"
android:id="#+id/number"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:hint="0"
android:background="#ffe7e7e7"
android:textSize="30sp"
android:gravity="center_vertical|right"
android:paddingRight="20dp"
android:editable="true"
android:enabled="true"
android:numeric="integer|signed|decimal" />
<Button
android:layout_width="75dp"
android:layout_height="75dp"
android:text="1"
android:id="#+id/button"
android:layout_below="#+id/number"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:textSize="50sp"
android:background="#ff0fdf22"
android:layout_marginTop="10dp" />
<Button
android:layout_width="75dp"
android:layout_height="75dp"
android:text="2"
android:id="#+id/button2"
android:textSize="50sp"
android:background="#ff0fdf22"
android:layout_alignTop="#+id/button"
android:layout_toRightOf="#+id/button"
android:layout_marginLeft="10dp" />
<Button
android:layout_width="75dp"
android:layout_height="75dp"
android:text="3"
android:id="#+id/button3"
android:textSize="50sp"
android:background="#ff0fdf22"
android:layout_alignTop="#+id/button2"
android:layout_toRightOf="#+id/button2"
android:layout_marginLeft="10dp" />
<Button
android:layout_width="75dp"
android:layout_height="75dp"
android:text="4"
android:id="#+id/button4"
android:textSize="50sp"
android:background="#ff0fdf22"
android:layout_below="#+id/button"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="10dp" />
<Button
android:layout_width="75dp"
android:layout_height="75dp"
android:text="5"
android:id="#+id/button5"
android:textSize="50sp"
android:background="#ff0fdf22"
android:layout_alignTop="#+id/button4"
android:layout_toRightOf="#+id/button4"
android:layout_marginLeft="10dp" />
<Button
android:layout_width="75dp"
android:layout_height="75dp"
android:text="6"
android:id="#+id/button6"
android:textSize="50sp"
android:background="#ff0fdf22"
android:layout_alignTop="#+id/button5"
android:layout_toRightOf="#+id/button5"
android:layout_marginLeft="10dp" />
<Button
android:layout_width="75dp"
android:layout_height="75dp"
android:text="7"
android:id="#+id/button7"
android:textSize="50sp"
android:background="#ff0fdf22"
android:layout_below="#+id/button4"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="10dp" />
<Button
android:layout_width="75dp"
android:layout_height="75dp"
android:text="8"
android:id="#+id/button8"
android:textSize="50sp"
android:background="#ff0fdf22"
android:layout_alignTop="#+id/button7"
android:layout_toRightOf="#+id/button7"
android:layout_marginLeft="10dp" />
<Button
android:layout_width="75dp"
android:layout_height="75dp"
android:text="9"
android:id="#+id/button9"
android:textSize="50sp"
android:background="#ff0fdf22"
android:layout_alignTop="#+id/button8"
android:layout_toRightOf="#+id/button8"
android:layout_marginLeft="10dp" />
<Button
android:layout_width="75dp"
android:layout_height="75dp"
android:text="0"
android:id="#+id/button11"
android:textSize="50sp"
android:background="#ff0fdf22"
android:layout_below="#+id/button7"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="10dp" />
<Button
android:layout_width="160dp"
android:layout_height="75dp"
android:text="="
android:id="#+id/button12"
android:textSize="50sp"
android:background="#ff0fdf22"
android:layout_alignTop="#+id/button11"
android:layout_toRightOf="#+id/button11"
android:layout_marginLeft="10dp" />
<Button
android:layout_width="75dp"
android:layout_height="75dp"
android:text="+"
android:id="#+id/button13"
android:textSize="50sp"
android:background="#ff0fdf22"
android:layout_alignTop="#+id/button3"
android:layout_toRightOf="#+id/button3"
android:layout_marginLeft="10dp" />
<Button
android:layout_width="75dp"
android:layout_height="75dp"
android:text="-"
android:id="#+id/button14"
android:textSize="50sp"
android:background="#ff0fdf22"
android:layout_alignTop="#+id/button6"
android:layout_toRightOf="#+id/button6"
android:layout_marginLeft="10dp" />
<Button
android:layout_width="75dp"
android:layout_height="75dp"
android:text="*"
android:id="#+id/button15"
android:textSize="50sp"
android:background="#ff0fdf22"
android:layout_alignTop="#+id/button9"
android:layout_toRightOf="#+id/button9"
android:layout_marginLeft="10dp" />
<Button
android:layout_width="75dp"
android:layout_height="75dp"
android:text="/"
android:id="#+id/button16"
android:textSize="50sp"
android:background="#ff0fdf22"
android:layout_alignTop="#+id/button12"
android:layout_toRightOf="#+id/button12"
android:layout_marginLeft="10dp" />
Logcat:
07-24 16:30:07.894 26564-26564/com.example.david.calculator D/AndroidRuntime﹕ Shutting down VM
07-24 16:30:07.894 26564-26564/com.example.david.calculator W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x4190aba8)
07-24 16:30:07.899 26564-26564/com.example.david.calculator E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.david.calculator, PID: 26564
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.david.calculator/com.example.david.calculator.MyActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2110)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at android.app.Activity.findViewById(Activity.java:1884)
at com.example.david.calculator.MyActivity.<init>(MyActivity.java:18)
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1208)
at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2101)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Thank you very much for all the replies.
            
You are setting your EditText in your main class and not in your classes onCreate method. You can't find a view if the activity hasn't been created yet.
public class MyActivity extends Activity {
EditText results;
private int number;
final EditText result = (EditText) findViewById(R.id.number);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
Button one = (Button) findViewById(R.id.button);
one.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
BtnPressed(1);
}
});
}
Should become
public class MyActivity extends Activity {
EditText results;
private int number;
private EditText result;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
result = (EditText) findViewById(R.id.number);
Button one = (Button) findViewById(R.id.button);
one.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
BtnPressed(1);
}
});
}
You were getting a NullPointerException in your log, this should fix it.
You should move
final EditText result = (EditText) findViewById(R.id.number);
inside onCreate(...) after setContentView(..)
Corrected Code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
EditText result = (EditText) findViewById(R.id.number);
Button one = (Button) findViewById(R.id.button);
one.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
BtnPressed(1);
}
});
}
Check your code:
final EditText result = (EditText) findViewById(R.id.number);
This should come after setContentView() method just like with the button.
You should do this:
final EditText result = (EditText) findViewById(R.id.number);
in your onCreate after the setContentView.

'NoSuchMethodException' even though the method really does exist

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).

java.lang.NullPointerException on onClickListener

Can you see if there is anything wrong with my code?
I tried to create dialog box when the button is pressed.
I don't see something wrong here, But the logcat shows java.lang.NullPointerException in this line "agree.setOnClickListener(new OnClickListener() {"
package com.sociyo;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); //Lock Orientation
requestWindowFeature(Window.FEATURE_NO_TITLE); //Hide Action menu
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); //Load main activity
//viewPager default page
ViewPagerAdapter adapter = new ViewPagerAdapter();
ViewPager myPager = (ViewPager) findViewById(R.id.pager);
myPager.setAdapter(adapter);
myPager.setCurrentItem(0);
//textView clickable
Button agree = (Button)findViewById(R.id.btnTerms);
agree.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
AlertDialog.Builder tpDialog = new AlertDialog.Builder(null);
tpDialog.setTitle("Terms and Policy");
tpDialog.setMessage(R.string.action_settings)
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
MainActivity.this.finish();
}
});
}
});
}
#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;
}
}
And this is the complete log cat :
E/AndroidRuntime(13076): FATAL EXCEPTION: main
E/AndroidRuntime(13076): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.sociyo/com.sociyo.MainActivity}: java.lang.NullPointerException
E/AndroidRuntime(13076): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2070)
E/AndroidRuntime(13076): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2095)
E/AndroidRuntime(13076): at android.app.ActivityThread.access$600(ActivityThread.java:137)
E/AndroidRuntime(13076): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1206)
E/AndroidRuntime(13076): at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(13076): at android.os.Looper.loop(Looper.java:213)
E/AndroidRuntime(13076): at android.app.ActivityThread.main(ActivityThread.java:4793)
E/AndroidRuntime(13076): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(13076): at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime(13076): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
E/AndroidRuntime(13076): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:556)
E/AndroidRuntime(13076): at dalvik.system.NativeStart.main(Native Method)
**E/AndroidRuntime(13076): Caused by: java.lang.NullPointerException**
E/AndroidRuntime(13076): at com.sociyo.MainActivity.onCreate(MainActivity.java:34)
E/AndroidRuntime(13076): at android.app.Activity.performCreate(Activity.java:5008)
E/AndroidRuntime(13076): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
E/AndroidRuntime(13076): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2034)
E/AndroidRuntime(13076): ... 11 more
My activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:background="#drawable/background"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true" >
</android.support.v4.view.ViewPager>
</RelativeLayout>
And my activity_register.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:background="#android:color/transparent"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:orientation="vertical" >
<TextView
android:id="#+id/tvRegisterTitle"
style="#style/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="#string/register_text"
android:textAppearance="?android:attr/textAppearanceLarge" />
<EditText
android:id="#+id/etNameReg"
style="#style/textfield"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/spMlmList"
android:layout_centerHorizontal="true"
android:layout_marginTop="15dp"
android:ems="10"
android:hint="#string/name_hint"
android:inputType="textPersonName" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/etEmailReg"
style="#style/textfield"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/etNameReg"
android:layout_centerHorizontal="true"
android:layout_marginTop="15dp"
android:ems="10"
android:hint="#string/email_hint"
android:inputType="textEmailAddress" />
<EditText
android:id="#+id/etPasswordReg"
style="#style/textfield"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/etEmailReg"
android:layout_below="#+id/etEmailReg"
android:layout_centerVertical="true"
android:layout_marginTop="15dp"
android:ems="10"
android:hint="#string/password_hint"
android:inputType="textPassword" />
<Spinner
android:id="#+id/spMlmList"
style="#style/textfield"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/tvRegisterTitle"
android:layout_below="#+id/tvRegisterTitle"
android:layout_marginTop="15dp"
android:entries="#array/mlm_list" />
<Button
android:id="#+id/btnRegister"
style="#style/buttonBlue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/etPasswordReg"
android:layout_below="#+id/chkAgree"
android:layout_marginTop="15dp"
android:text="#string/register_text" />
<CheckBox
android:id="#+id/chkAgree"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/etPasswordReg"
android:text="#string/agree_text"
android:layout_marginTop="15dp"
style="#style/checkbox"/>
<Button
android:id="#+id/btnTerms"
android:background="#android:color/transparent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/chkAgree"
android:layout_alignBottom="#+id/chkAgree"
android:layout_toRightOf="#+id/tvRegisterTitle"
android:layout_marginLeft="10dp"
android:text="#string/terms_policy"
style="#style/smallLink"/>
</RelativeLayout>
Yes the button doesnt exist at that point.
Your R.id.btnTermsR.id.btnTerms is defined in activity_register.xml, but that layout is never inflated. or not accessible at that point :)
Its the button that has the Problem, not the OnClickListener. A nullpointer within the Listener would appear the moment you click the button, not while attaching it.
// Before Replace
AlertDialog.Builder tpDialog = new AlertDialog.Builder(null);
// After Replace
AlertDialog.Builder tpDialog = new AlertDialog.Builder(MainActivity.this);
AlertDialog.Builder tpDialog = new AlertDialog.Builder(null);
change this line too
AlertDialog.Builder tpDialog = new AlertDialog.Builder(MainActivity.this);

Categories