android.webkit.WebView cannot be cast to android.widget.Button - java

I was working on a GUI inside of my app. I originally had a crappy look to it that just contained all of the basic stuff to test my java functions in. After I had all the functions up and running I redisgned the GUI using the graphical editor in Eclipse. The next time I ran my app I had the android.webkit.WebView cannot be cast to android.widget.Button in my LogCat. I didn't change anything in the java and all the declarations in the GUI are the same as far as I can tell. I can easily revert the GUI back to the crappy version but that doesn't help me much. I hope someone on here can help me find my problem. I have posted the xml, java, and LogCat.
05-09 13:25:19.756: E/AndroidRuntime(10424): FATAL EXCEPTION: main
05-09 13:25:19.756: E/AndroidRuntime(10424): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.dcc/com.example.dcc.ActionItem}:
java.lang.ClassCastException: android.webkit.WebView cannot be cast to android.widget.Button
05-09 13:25:19.756: E/AndroidRuntime(10424): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
05-09 13:25:19.756: E/AndroidRuntime(10424): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
05-09 13:25:19.756: E/AndroidRuntime(10424): at android.app.ActivityThread.access$600(ActivityThread.java:130)
05-09 13:25:19.756: E/AndroidRuntime(10424): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
05-09 13:25:19.756: E/AndroidRuntime(10424): at android.os.Handler.dispatchMessage(Handler.java:99)
05-09 13:25:19.756: E/AndroidRuntime(10424): at android.os.Looper.loop(Looper.java:137)
05-09 13:25:19.756: E/AndroidRuntime(10424): at android.app.ActivityThread.main(ActivityThread.java:4745)
05-09 13:25:19.756: E/AndroidRuntime(10424): at java.lang.reflect.Method.invokeNative(Native Method)
05-09 13:25:19.756: E/AndroidRuntime(10424): at java.lang.reflect.Method.invoke(Method.java:511)
05-09 13:25:19.756: E/AndroidRuntime(10424): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
05-09 13:25:19.756: E/AndroidRuntime(10424): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
05-09 13:25:19.756: E/AndroidRuntime(10424): at dalvik.system.NativeStart.main(Native Method)
05-09 13:25:19.756: E/AndroidRuntime(10424): Caused by: java.lang.ClassCastException: android.webkit.WebView cannot be cast to android.widget.Button
05-09 13:25:19.756: E/AndroidRuntime(10424): at com.example.dcc.ActionItem.onCreate(ActionItem.java:54)
05-09 13:25:19.756: E/AndroidRuntime(10424): at android.app.Activity.performCreate(Activity.java:5008)
05-09 13:25:19.756: E/AndroidRuntime(10424): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
05-09 13:25:19.756: E/AndroidRuntime(10424): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
05-09 13:25:19.756: E/AndroidRuntime(10424): ... 11 more
<GridLayout 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:columnCount="4" >
<LinearLayout
android:layout_width="212dp"
android:layout_height="match_parent"
android:layout_column="0"
android:layout_columnSpan="3"
android:layout_gravity="left"
android:layout_row="0"
android:orientation="vertical" >
<Button
android:id="#+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/Button1_name"
android:drawableRight="#drawable/news"/>
<Button
android:id="#+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/Button2_name" />
<Button
android:id="#+id/button3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/Button3_name"
android:drawableRight="#drawable/cal"/>
<Button
android:id="#+id/button4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/Button4_name"
android:drawableRight="#drawable/mail"/>
<Button
android:id="#+id/button5"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/Button5_name"
android:drawableRight="#drawable/gallery" />
<Button
android:id="#+id/button6"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/Button6_name"
android:drawableRight="#drawable/report" />
<Button
android:id="#+id/button7"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/Button7_name"
android:drawableRight="#drawable/ep" />
<Button
android:id="#+id/button8"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/Button8_name"
android:drawableRight="#drawable/directory" />
</LinearLayout>
<GridLayout
android:id="#+id/a"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_column="1"
android:layout_columnSpan="2"
android:layout_gravity="left"
android:layout_row="0"
android:columnCount="2" >
</GridLayout>
<ImageView
android:id="#+id/imageView1"
android:layout_width="10dp"
android:layout_height="fill_parent"
android:layout_column="2"
android:layout_gravity="left"
android:layout_row="0"
android:background="#drawable/black"
tools:ignore="ContentDescription" />
 
<ScrollView
android:id="#+id/scrollView1"
android:layout_width="238dp"
android:layout_height="fill_parent"
android:layout_column="3"
android:layout_gravity="left|top"
android:layout_row="0"
android:background="#android:color/black" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/feedtitle"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/feeddescribtion"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/feedpubdate"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/feedlink"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:autoLink="web" />
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="594dp" >
</ListView>
<TextView
android:id="#android:id/empty"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="waiting" />
</LinearLayout>
</ScrollView>
<WebView
android:id="#+id/webView1"
android:layout_width="830dp"
android:layout_height="555dp"
android:layout_column="3"
android:layout_gravity="right|bottom"
android:layout_row="0" />
<Button
android:id="#+id/email_button1"
android:layout_width="585dp"
android:layout_height="114dp"
android:layout_column="3"
android:layout_gravity="center_horizontal|top"
android:layout_row="0"
android:text="Submit Action Item Now" />
<TextView
android:id="#+id/actionView"
android:layout_width="243dp"
android:layout_height="113dp"
android:layout_column="3"
android:layout_gravity="right|top"
android:layout_row="0"
android:text="Loading" />
</GridLayout>
package com.example.dcc;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import android.app.ListActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
public class ActionItem extends ListActivity implements OnClickListener {
// Create buttons Globally so they are available to all methods
public static RSSFeed myRssFeed = null;
private Button btnEmail = null;
static WebView webView;
Button newsB;
Button loginB;
Button calB;
Button mailB;
Button photoB;
Button reportB;
Button actionB;
Button directoryB;
String currentItem;
TextView thisAction;
int currentLocation;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.action_item);
btnEmail = (Button) findViewById(R.id.email_button1);
newsB = (Button) findViewById(R.id.button1);
loginB = (Button) findViewById(R.id.button2);
calB = (Button) findViewById(R.id.button3);
mailB = (Button) findViewById(R.id.button4);
photoB = (Button) findViewById(R.id.button5);
reportB = (Button) findViewById(R.id.button6);
actionB = (Button) findViewById(R.id.button7);
directoryB = (Button) findViewById(R.id.button8);
thisAction = (TextView) findViewById(R.id.actionView);
newsB.setOnClickListener(this);
loginB.setOnClickListener(this);
calB.setOnClickListener(this);
mailB.setOnClickListener(this);
photoB.setOnClickListener(this);
reportB.setOnClickListener(this);
actionB.setOnClickListener(this);
directoryB.setOnClickListener(this);
btnEmail.setOnClickListener(this);
new MyTask().execute();
// this portion of the onCreate is dedicated to running the webView
// another webpage: http://creflodollarministries.org/
// main webpage: http://www.virtualDiscoveryCenter.net
webView = (WebView) findViewById(R.id.webView1);
webView.setWebViewClient(new WebViewClient());
webView.loadUrl("http://www.virtualDiscoveryCenter.net");
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
Uri data = getIntent().getData();
if (savedInstanceState == null) {
String url = getIntent().getDataString();
// do something with this URL.
webView.loadUrl(url);
}
}
private class MyTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0) {
try {
URL rssUrl = new URL(
"http://www.virtualdiscoverycenter.net/feed/");// http://www.virtualdiscoverycenter.net/feed/
SAXParserFactory mySAXParserFactory = SAXParserFactory
.newInstance();
SAXParser mySAXParser = mySAXParserFactory.newSAXParser();
XMLReader myXMLReader = mySAXParser.getXMLReader();
RSSHandler myRSSHandler = new RSSHandler();
myXMLReader.setContentHandler(myRSSHandler);
InputSource myInputSource = new InputSource(rssUrl.openStream());
myXMLReader.parse(myInputSource);
myRssFeed = myRSSHandler.getFeed();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
if (myRssFeed != null) {
TextView feedTitle = (TextView) findViewById(R.id.feedtitle);
TextView feedDescribtion = (TextView) findViewById(R.id.feeddescribtion);
TextView feedPubdate = (TextView) findViewById(R.id.feedpubdate);
TextView feedLink = (TextView) findViewById(R.id.feedlink);
feedTitle.setText(myRssFeed.getTitle());
feedDescribtion.setText(myRssFeed.getDescription());
feedPubdate.setText(myRssFeed.getPubdate());
feedLink.setText(myRssFeed.getLink());
ArrayAdapter<RSSItem> adapter = new ArrayAdapter<RSSItem>(
getApplicationContext(),
android.R.layout.simple_list_item_1,
myRssFeed.getList());
setListAdapter(adapter);
thisAction.setText(myRssFeed.getItem(0).getTitle());
} else {
TextView textEmpty = (TextView) findViewById(android.R.id.empty);
textEmpty.setText("No Feed Found!");
}
super.onPostExecute(result);
}
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// Uri feedUri = Uri.parse(myRssFeed.getItem(position).getLink());
// Intent myIntent = new Intent(Intent.ACTION_VIEW, feedUri);
// startActivity(myIntent);
String url = myRssFeed.getItem(position).getLink();
currentItem = myRssFeed.getItem(position).getTitle();
currentLocation = position;
thisAction.setText(currentItem);
webView.loadUrl(url);
}
public void sendEmail(View v) {
// The following code is the implementation of Email client
Intent i = new Intent(android.content.Intent.ACTION_SEND);
i.setType("text/plain");
String[] address = { "bevins2012#hotmail.com" };
i.putExtra(android.content.Intent.EXTRA_EMAIL, address);
i.putExtra(android.content.Intent.EXTRA_SUBJECT, myRssFeed.getItem(currentLocation).getDescription());
i.putExtra(android.content.Intent.EXTRA_TEXT,
"Action Item from DCC app.");
startActivityForResult((Intent.createChooser(i, "Email")), 1);
}
public void onClick(View v) {
// this switch listens for any and all click actions in the app
// each case is a button in the menu.
switch (v.getId()) {
case R.id.button1:
startActivity(new Intent(this, AndroidRssReader.class));
break;
case R.id.button2:
startActivity(new Intent(this, MainActivity.class));
break;
case R.id.button3:
startActivity(new Intent(this, MainActivity.class));
break;
case R.id.button4:
startActivity(new Intent(this, EmailMain.class));
break;
case R.id.button5:
startActivity(new Intent(this, CustomizedListView.class));
break;
case R.id.button6:
startActivity(new Intent(this, LaunchActivity.class));
break;
case R.id.button7:
startActivity(new Intent(this, ActionItem.class));
break;
case R.id.button8:
startActivity(new Intent(this, MainActivity.class));
finish();
break;
case R.id.email_button1:
// Calling sendEmail from the activity class
sendEmail(v);
break;
}
}
}

Perhaps the auto-generated R class is messed up. Try to clean and rebuild your project by using Project > Clean... in Eclipse.

Related

Error with new intent ANDROID STUDIO [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
package com.example.alex.askii;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
//Alex Levin
public class Login extends AppCompatActivity {
Button login;
Button signUp;
EditText userNameET;
EditText passWordET;
DatabaseHelper helper = new DatabaseHelper(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
login = (Button)findViewById(R.id.Login);
signUp = (Button)findViewById(R.id.signUp);
userNameET = (EditText)findViewById(R.id.username);
passWordET = (EditText)findViewById(R.id.password);
login.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
//get text valiues
String userName = userNameET.getText().toString();
String passWord = passWordET.getText().toString();
//Query in java the username
String actualPassword = helper.searchPass(userName);
//If Correct
if(passWord.equals(actualPassword)){
Toast.makeText(getApplicationContext(),
"Redirecting...", Toast.LENGTH_SHORT).show();
/*
Intent i = new Intent(mainActivity.this, display.class);
i.putExtra("UserName", str);
startActivity(i)
Example code to go to next activity ^^
*/
}else{
Toast.makeText(getApplicationContext(), "Invalid Username Or Password", Toast.LENGTH_SHORT).show();
}
}
});
signUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Login.this, signUP.class);
startActivity(i);
}
});
}
}
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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="com.example.alex.askii.Login">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Askii Login"
android:textSize = "30dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.033"
tools:layout_constraintRight_creator="1"
tools:layout_constraintLeft_creator="1" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text= "Username:"
android:textSize="20dp"
app:layout_constraintRight_toLeftOf="#+id/username"
tools:layout_constraintRight_creator="1"
tools:layout_constraintBottom_creator="1"
app:layout_constraintBottom_toBottomOf="#+id/username"
android:layout_marginEnd="7dp"
android:layout_marginBottom="4dp"
android:layout_marginRight="7dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text= "Password:"
android:textSize="20dp"
android:id="#+id/textView"
tools:layout_constraintBottom_creator="1"
android:layout_marginStart="16dp"
app:layout_constraintBottom_toBottomOf="parent"
tools:layout_constraintLeft_creator="1"
android:layout_marginBottom="169dp"
app:layout_constraintLeft_toLeftOf="parent"
android:layout_marginLeft="16dp" />
<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/Login"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Login"
android:onClick="login"
tools:layout_constraintRight_creator="1"
tools:layout_constraintBottom_creator="1"
app:layout_constraintBottom_toBottomOf="parent"
android:layout_marginEnd="84dp"
app:layout_constraintRight_toRightOf="parent"
android:layout_marginBottom="88dp"
android:layout_marginRight="130dp" />
<EditText
android:id="#+id/password"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPassword"
tools:layout_constraintRight_creator="1"
app:layout_constraintRight_toRightOf="#+id/username"
app:layout_constraintBaseline_toBaselineOf="#+id/textView"
tools:layout_constraintBaseline_creator="1"
tools:layout_constraintLeft_creator="1"
app:layout_constraintLeft_toLeftOf="#+id/username" />
<EditText
android:id="#+id/username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName"
android:text="Enter Username"
tools:layout_constraintBottom_creator="1"
app:layout_constraintBottom_toTopOf="#+id/password"
android:layout_marginStart="11dp"
tools:layout_constraintLeft_creator="1"
android:layout_marginBottom="20dp"
app:layout_constraintLeft_toRightOf="#+id/textView"
android:layout_marginLeft="11dp" />
<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/signUp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Sign Up"
tools:layout_constraintRight_creator="1"
tools:layout_constraintBottom_creator="1"
app:layout_constraintBottom_toBottomOf="parent"
android:layout_marginEnd="84dp"
app:layout_constraintRight_toRightOf="parent"
android:layout_marginRight="216dp"
android:layout_marginBottom="47dp" />
</android.support.constraint.ConstraintLayout>
package com.example.alex.askii;
import android.app.Activity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
/**
* Created by Alex on 12/30/2017.
*/
public class signUP extends AppCompatActivity{
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.signup);
}
Button signUpOnPage = (Button)findViewById(R.id.signUpOnPage);
public void onSignUpOnPage(View v){
if(v.getId() == R.id.signUpOnPage){
EditText userName = (EditText)findViewById(R.id.newUserName);
EditText passWord = (EditText)findViewById(R.id.newPassWord);
EditText confPassword = (EditText)findViewById(R.id.newUserName);
String userNameString = userName.getText().toString();
String passWordString = passWord.getText().toString();
String confPasswordString = confPassword.getText().toString();
if(!passWordString.equals(confPasswordString)){
Toast check = Toast.makeText(signUP.this, "Passwords Don't Match", Toast.LENGTH_SHORT);
check.show();
}
}
}
}
For some reason I am getting the following error
12-30 02:39:59.308 1969-1969/com.example.alex.askii E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.alex.askii/com.example.alex.askii.signUP}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1880)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
at android.app.ActivityThread.access$600(ActivityThread.java:123)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
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:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at android.support.v7.app.AppCompatDelegateImplBase.<init>(AppCompatDelegateImplBase.java:118)
at android.support.v7.app.AppCompatDelegateImplV9.<init>(AppCompatDelegateImplV9.java:152)
at android.support.v7.app.AppCompatDelegateImplV11.<init>(AppCompatDelegateImplV11.java:29)
at android.support.v7.app.AppCompatDelegateImplV14.<init>(AppCompatDelegateImplV14.java:53)
at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:204)
at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:184)
at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:518)
at android.support.v7.app.AppCompatActivity.findViewById(AppCompatActivity.java:189)
at com.example.alex.askii.signUP.<init>(signUP.java:16)
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1319)
at android.app.Instrumentation.newActivity(Instrumentation.java:1023)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1871)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981) 
at android.app.ActivityThread.access$600(ActivityThread.java:123) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:137) 
at android.app.ActivityThread.main(ActivityThread.java:4424) 
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:784) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551) 
at dalvik.system.NativeStart.main(Native Method) 
I am really unsure why this is happening maybe it is something wrong with my manifests but I doubt it because the manifest was autogenerated. Please help I can't find the answer online because it seems like I followed everything online correctly this is the last place I came to for help I am so frustrated right now!
Move
signUpOnPage = (Button)findViewById(R.id.signUpOnPage);
to onCreate()

How to pass user input from one activity to another in Android

I'm creating a basic conversion app which converts the users input from km-knots or vice versa. At present it displays the result in the same place as where the user initially type in their figure. I'm wondering how is it possible to display the result in a new activity? Currently I've only managed to make it appear, as I said, in the same place as where the user initially type in their figure and a second afterwards the second activity pops up. What am I missing here? Please look at my code, thanks:
MainActivity.java
package winfield.joe.wind.v1;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;
public class MainActivity extends Activity {
// public var
private EditText text;
// default func
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Toast.makeText(this, "onCreate!", Toast.LENGTH_LONG).show();
setContentView(R.layout.activity_main);
// findViewById = Finds a view that was identified by the id attribute
// from the XML that was processed in onCreate(Bundle).
// (EditText) = typecast
text = (EditText) findViewById(R.id.userInput);
}
//Will be executed by clicking on the calculate button because we assigned "calc" to the "onClick" Property
public void calc(View view) {
RadioButton toKilometers = (RadioButton) findViewById(R.id.toKilometers);
RadioButton toKnots = (RadioButton) findViewById(R.id.toKnots);
if (text.getText().length() == 0) {
// if the text field is empty show the message "enter a valid number" via toast message
Toast.makeText(this, "enter a valid number", Toast.LENGTH_LONG).show();
} else {
int result = R.string.userInput;
Intent i = new Intent(MainActivity.this, SecondActivity.class);
putExtra("userInput", result);
startActivity(i);
// parse input Value from Text Field
double inputValue = Double.parseDouble(text.getText().toString());
// convert to...
if (toKilometers.isChecked()) {
text.setText(String.valueOf(convertToKM(inputValue)));
// uncheck "to km" Button
toKilometers.setChecked(false);
// check "to knots" Button
toKnots.setChecked(true);
} else { /* if toKnots button isChecked() */
text.setText(String.valueOf(convertToKnots(inputValue)));
// uncheck "to knots" Button
toKnots.setChecked(false);
// check "to km" Button
toKilometers.setChecked(true);
}
}
}
private void putExtra(String string, int result) {
// TODO Auto-generated method stub
}
private double convertToKM(double inputValue) {
// convert knots to km
return (inputValue * 1.8);
}
private double convertToKnots(double inputValue) {
// convert km to knots
return (inputValue * 0.539956803);
}
}
SecondActivity.java
package winfield.joe.wind.v1;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class SecondActivity extends Activity {
Bundle extras = getIntent().getExtras();
int result = extras.getInt("results");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
}
//onClick GoBack method assigned to the Go Back? button which returns the user to main activity from the second activity
public void GoBack(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Are you sure?");
// set dialog message
builder .setCancelable(false)
.setPositiveButton("Convert Again",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
//You return to Main Activity
Intent intent = new Intent(SecondActivity.this, MainActivity.class);
startActivity(intent);
}
})
.setNeutralButton("Back to Home",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
//You return to the home page
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
startActivity(intent);
}
})
.setNegativeButton("View Results",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, just close the dialog box and do nothing
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/LinearLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:background="#color/bgColor"
android:orientation="vertical">
<!--TITLE-->
<TextView
android:id="#+id/titleMain"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="22dp"
android:gravity="center"
android:text="#string/titleMain"
android:textColor="#color/textColor"
android:textColorHint="#color/textColor"
android:textColorLink="#ffffff"
android:textSize="30sp" />
<!--USER-INPUT-->
<EditText
android:id="#+id/userInput"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:ems="10"
android:hint="#+string/userInput"
android:inputType="numberDecimal"
android:paddingEnd="40dp"
android:paddingStart="20dp"
android:paddingTop="30dp" >
<requestFocus />
</EditText>
<!--TWO RADIO BUTTONS-->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="10dp">
<!--toKNOTS-->
<RadioButton
android:id="#+id/toKnots"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginStart="10dp"
android:layout_marginTop="10dp"
android:layout_weight="0.04"
android:checked="true"
android:text="#string/toKnots" />
<!--toKM-->
<RadioButton
android:id="#+id/toKilometers"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginEnd="20dp"
android:layout_marginTop="10dp"
android:text="#string/toKilometers" />
</LinearLayout>
<!--CALCULATE-->
<Button
android:id="#+id/valueCalc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginEnd="10dp"
android:layout_marginStart="10dp"
android:layout_marginTop="30dp"
android:onClick="calc"
android:text="#string/valueCalc" />
</LinearLayout>
activity_second.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/LinearLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:background="#color/bgColor"
android:orientation="vertical"
tools:context="${relativePackage}.${activityClass}" >
<!-- TITLE -->
<TextView
android:id="#+id/titleResults"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="24dp"
android:gravity="center"
android:text="#string/titleResults"
android:textColor="#color/textColor"
android:textColorHint="#color/textColor"
android:textColorLink="#ffffff"
android:textSize="25sp" />
<EditText
android:id="#+id/results"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="20dp"
android:layout_marginTop="30dp"
android:ems="10"
android:hint="#string/results"
android:inputType="numberDecimal"
android:textColorHint="#color/textColor" >
<requestFocus />
</EditText>
<Button
android:id="#+id/GoBack"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="40dp"
android:text="#string/GoBack"
android:onClick="GoBack" />
</LinearLayout>
LOGCAT
03-09 12:27:35.692: E/AndroidRuntime(2911): java.lang.RuntimeException: Unable to start activity ComponentInfo{winfield.joe.wind.v1/winfield.joe.wind.v1.SecondActivity}: java.lang.NullPointerException
03-09 12:27:35.692: E/AndroidRuntime(2911): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
03-09 12:27:45.262: E/AndroidRuntime(2934): java.lang.RuntimeException: Unable to start activity ComponentInfo{winfield.joe.wind.v1/winfield.joe.wind.v1.SecondActivity}: java.lang.NullPointerException
03-09 12:27:45.262: E/AndroidRuntime(2934): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
03-09 12:29:52.172: E/AndroidRuntime(2989): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{winfield.joe.wind.v1/winfield.joe.wind.v1.SecondActivity}: java.lang.NullPointerException
03-09 12:29:52.172: E/AndroidRuntime(2989): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
03-09 12:32:29.322: E/AndroidRuntime(3056): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{winfield.joe.wind.v1/winfield.joe.wind.v1.SecondActivity}: java.lang.NullPointerException
03-09 12:32:29.322: E/AndroidRuntime(3056): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
03-09 12:36:29.872: E/AndroidRuntime(3112): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{winfield.joe.wind.v1/winfield.joe.wind.v1.SecondActivity}: java.lang.NullPointerException
03-09 12:36:29.872: E/AndroidRuntime(3112): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
03-09 12:44:25.022: E/AndroidRuntime(3172): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{winfield.joe.wind.v1/winfield.joe.wind.v1.SecondActivity}: java.lang.NullPointerException
03-09 12:44:25.022: E/AndroidRuntime(3172): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
03-09 12:53:38.802: E/AndroidRuntime(3242): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{winfield.joe.wind.v1/winfield.joe.wind.v1.SecondActivity}: java.lang.NullPointerException
03-09 12:53:38.802: E/AndroidRuntime(3242): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
03-09 13:19:58.122: E/AndroidRuntime(3299): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{winfield.joe.wind.v1/winfield.joe.wind.v1.SecondActivity}: java.lang.NullPointerException
03-09 13:19:58.122: E/AndroidRuntime(3299): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
If you want to pass any content from one activity to another, you can do it by using putExtra with intent, it will send data from one activity to another, and in another activity get that data by using getExtras.
To send data,
String str = "value";
Intent launchResult = new Intent(MainActivity.this, SecondActivity.class);
putExtra("key", str);
startActivity(launchResult);
To receive data in another activity,
Bundle extras = getIntent().getExtras();
String str = extras.getStr("key");
Edit:
In my answer key is any unique value that must remain same in both Sender Activity and Receiver Activity.
You are getting the error because you have passed a string value where you had to pass key, and the key in receiver activity in not matching either.
See the change below, it should work
MainActivity.class
int result = R.string.userInput;
Intent i = new Intent(MainActivity.this, SecondActivity.class);
putExtra("userInput", result);
startActivity(i);
SecondActivity.class
Bundle extras = getIntent().getExtras();
int result = extras.getInt("userInput");
Use below code to pass values from one Activity to Another
Intent launchResult = new Intent(MainActivity.this, SecondActivity.class);
launchResult.putExtra("output",result);

Error Inflating Layout caused by Binary XML File

So I am writing an android application that starts an activity after a notification has been clicked. I am getting this in my LogCat:
`
05-01 13:43:49.435: E/AndroidRuntime(28224): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.chowpalv21/com.example.chowpalv21.SmsViewActivity}: android.view.InflateException: Binary XML file line #21: Error inflating class com.android.internal.widget.ActionBarOverlayLayout
05-01 13:43:49.435: E/AndroidRuntime(28224): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2295)
05-01 13:43:49.435: E/AndroidRuntime(28224): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2349)
05-01 13:43:49.435: E/AndroidRuntime(28224): at android.app.ActivityThread.access$700(ActivityThread.java:159)
05-01 13:43:49.435: E/AndroidRuntime(28224): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1316)
05-01 13:43:49.435: E/AndroidRuntime(28224): at android.os.Handler.dispatchMessage(Handler.java:99)
05-01 13:43:49.435: E/AndroidRuntime(28224): at android.os.Looper.loop(Looper.java:137)
05-01 13:43:49.435: E/AndroidRuntime(28224): at android.app.ActivityThread.main(ActivityThread.java:5419)
05-01 13:43:49.435: E/AndroidRuntime(28224): at java.lang.reflect.Method.invokeNative(Native Method)
05-01 13:43:49.435: E/AndroidRuntime(28224): at java.lang.reflect.Method.invoke(Method.java:525)
05-01 13:43:49.435: E/AndroidRuntime(28224): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1187)
05-01 13:43:49.435: E/AndroidRuntime(28224): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
05-01 13:43:49.435: E/AndroidRuntime(28224): at dalvik.system.NativeStart.main(Native Method)
05-01 13:43:49.435: E/AndroidRuntime(28224): Caused by: android.view.InflateException: Binary XML file line #21: Error inflating class com.android.internal.widget.ActionBarOverlayLayout
05-01 13:43:49.435: E/AndroidRuntime(28224): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:719)
05-01 13:43:49.435: E/AndroidRuntime(28224): at android.view.LayoutInflater.inflate(LayoutInflater.java:470)
05-01 13:43:49.435: E/AndroidRuntime(28224): at android.view.LayoutInflater.inflate(LayoutInflater.java:398)
05-01 13:43:49.435: E/AndroidRuntime(28224): at android.view.LayoutInflater.inflate(LayoutInflater.java:354)
05-01 13:43:49.435: E/AndroidRuntime(28224): at com.android.internal.policy.impl.PhoneWindow.generateLayout(PhoneWindow.java:3553)
05-01 13:43:49.435: E/AndroidRuntime(28224): at com.android.internal.policy.impl.PhoneWindow.installDecor(PhoneWindow.java:3616)
05-01 13:43:49.435: E/AndroidRuntime(28224): at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:357)
05-01 13:43:49.435: E/AndroidRuntime(28224): at android.app.Activity.setContentView(Activity.java:1956)
05-01 13:43:49.435: E/AndroidRuntime(28224): at com.example.chowpalv21.SmsViewActivity.onCreate(SmsViewActivity.java:80)
05-01 13:43:49.435: E/AndroidRuntime(28224): at android.app.Activity.performCreate(Activity.java:5372)
05-01 13:43:49.435: E/AndroidRuntime(28224): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
05-01 13:43:49.435: E/AndroidRuntime(28224): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2257)
05-01 13:43:49.435: E/AndroidRuntime(28224): ... 11 more
05-01 13:43:49.435: E/AndroidRuntime(28224): Caused by: java.lang.NullPointerException
05-01 13:43:49.435: E/AndroidRuntime(28224): at com.example.chowpalv21.SmsViewActivity.onCreateView(SmsViewActivity.java:121)
05-01 13:43:49.435: E/AndroidRuntime(28224): at android.app.Activity.onCreateView(Activity.java:4924)
05-01 13:43:49.435: E/AndroidRuntime(28224): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:695)
05-01 13:43:49.435: E/AndroidRuntime(28224): ... 22 more
`
I have scoured StackOverflow for answers because it seems others have had similar problems - I tried rebuilding and cleaning the project and restarting ADT as well as creating a new file. I was wondering if anyone here has a guidance.
Here is my layout file:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/scroll_view_sms"
android:layout_width="wrap_content"
android:layout_height="match_parent" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="4dp"
android:orientation="vertical" >
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical" >
<TextView
style="?android:listSeparatorTextViewStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/food_title_label" />
<EditText
android:id="#+id/food_title_sms"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginRight="16dp" />
</LinearLayout>
</LinearLayout>
<TextView
style="?android:listSeparatorTextViewStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Units of Measurement:" />
<TableRow
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<CheckBox
android:id="#+id/imperial_checkBox_sms"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Imperial" />
<CheckBox
android:id="#+id/metric_checkBox_sms"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Metric" />
</TableRow>
<TextView
style="?android:listSeparatorTextViewStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Number of Servings:" />
<EditText
android:id="#+id/food_servings_sms"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="number" >
</EditText>
<TableRow
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/ingredient_text_sms"
style="?android:listSeparatorTextViewStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Ingredients" />
</TableRow>
<View
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="#android:color/darker_gray" />
<TableRow
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<Spinner
android:id="#+id/imperial_spinner_sms"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:entries="#array/imperial_array"
android:visibility="gone" />
<Spinner
android:id="#+id/metric_spinner_sms"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:entries="#array/metric_array"
android:visibility="gone" />
</RelativeLayout>
<EditText
android:id="#+id/amount_text_sms"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="numberDecimal" />
<EditText
android:id="#+id/ing_name_sms"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:ems="10" />
</TableRow>
<!-- second ingredient -->
<TextView
style="?android:listSeparatorTextViewStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Directions" />
<EditText
android:id="#+id/directions_text_sms"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textMultiLine" />
<TextView
style="?android:listSeparatorTextViewStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Options" />
<Button
android:id="#+id/save_button_sms"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Save Recipe" />
<Button
android:id="#+id/dismiss_button_sms"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Dismiss" />
<!-- DONE -->
</LinearLayout>
</ScrollView>
ALSO Here is the code for SMSViewActivity:
* File: SmsViewActivity.java
package com.example.chowpalv21;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.CompoundButton.OnCheckedChangeListener;
public class SmsViewActivity extends Activity {
private static final String TAG = "SmsViewActivity";
private FoodJSONSerializer mSerializer;
// protected TextView mReceivedFromView;
public Button mSaveButton, mDismissButton;
public int mNotificationId;
public String message;
private EditText mTitleField;
private CheckBox mImperialCheckBox;
private CheckBox mMetricCheckBox;
private EditText mServingsField;
private EditText mDirectionsField;
// set up spinners. allows for up to ten ingredients.
private Spinner mMetricSpinner;
private Spinner mImperialSpinner;
Food mFood;
//----------------------
------------------------
public void onCreate(Bundle savedInstanceState){
setContentView(R.layout.view_sms);
//super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(String name, Context context, AttributeSet attrs) {
//View v = findViewById(R.layout.sms_view);
View v = super.onCreateView(name, context, attrs);
mSaveButton = (Button) findViewById(R.id.save_button_sms);
mDismissButton = (Button) findViewById(R.id.dismiss_button_sms);
// ------------------------------------------------------------
// Get extras and display information in view
//String sender = getIntent().getStringExtra("sender");
String msg = getIntent().getStringExtra("message");
try {
JSONObject jsonRecipe = new JSONObject(msg);
Food mFood = new Food(jsonRecipe);
Log.i(TAG, "Food = " + mFood);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// -----------------------------------------------------------------------
mNotificationId = getIntent().getIntExtra("notificationid", 0);
if (mNotificationId == 0) {
Log.e(TAG, "Could not retrieve notification ID.");
Toast.makeText(this, "A fatal error has occurred in SMS viewer.",
Toast.LENGTH_LONG).show();
finish();
}
// Cancel the notification
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager notificationMgr = (NotificationManager) getSystemService(ns);
notificationMgr.cancel(mNotificationId);
// --------------------------------------------------
mTitleField = (EditText)v. findViewById(R.id.food_title_sms);
mTitleField.setText(mFood.getTitle());
mServingsField = (EditText)v. findViewById(R.id.food_servings_sms);
mServingsField.setText(mFood.getServings());
mDirectionsField = (EditText)v. findViewById(R.id.directions_text_sms);
mDirectionsField.setText(mFood.getDirections());
// --------------------------------------------------
// Listener for Save button click
mSaveButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
finish();
}
});
// Listener for Dismiss button click
mDismissButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
backToList();
finish();
}
});
return v;
}
public void backToList() {
Intent i = new Intent(this, FoodListFragment.class);
startActivity(i);
}
}
The odd part is, the exception is on a widget named ActionBarOverlayLayout which is not in my layout. If anyone knows that would help a lot! (project due Monday!)
Claudia
Why are you override onCreateView? In onCreate() you are setting the content using a layout resource. Your other initilization code should go here or onResume() depending on what it's doing. Try this...
public class SmsViewActivity extends Activity {
private static final String TAG = "SmsViewActivity";
private FoodJSONSerializer mSerializer;
public Button mSaveButton, mDismissButton;
public int mNotificationId;
public String message;
private EditText mTitleField;
private CheckBox mImperialCheckBox;
private CheckBox mMetricCheckBox;
private EditText mServingsField;
private EditText mDirectionsField;
private Spinner mMetricSpinner;
private Spinner mImperialSpinner;
Food mFood;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.view_sms);
mSaveButton = (Button) findViewById(R.id.save_button_sms);
mDismissButton = (Button) findViewById(R.id.dismiss_button_sms);
// ------------------------------------------------------------
// Get extras and display information in view
//String sender = getIntent().getStringExtra("sender");
String msg = getIntent().getStringExtra("message");
try {
JSONObject jsonRecipe = new JSONObject(msg);
Food mFood = new Food(jsonRecipe);
Log.i(TAG, "Food = " + mFood);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// -----------------------------------------------------------------------
mNotificationId = getIntent().getIntExtra("notificationid", 0);
if (mNotificationId == 0) {
Log.e(TAG, "Could not retrieve notification ID.");
Toast.makeText(this, "A fatal error has occurred in SMS viewer.",
Toast.LENGTH_LONG).show();
finish();
}
// Cancel the notification
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager notificationMgr = (NotificationManager) getSystemService(ns);
notificationMgr.cancel(mNotificationId);
// --------------------------------------------------
mTitleField = (EditText)v. findViewById(R.id.food_title_sms);
mTitleField.setText(mFood.getTitle());
mServingsField = (EditText)v. findViewById(R.id.food_servings_sms);
mServingsField.setText(mFood.getServings());
mDirectionsField = (EditText)v. findViewById(R.id.directions_text_sms);
mDirectionsField.setText(mFood.getDirections());
// --------------------------------------------------
// Listener for Save button click
mSaveButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
finish();
}
});
// Listener for Dismiss button click
mDismissButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
backToList();
finish();
}
});
return v;
}
public void backToList() {
Intent i = new Intent(this, FoodListFragment.class);
startActivity(i);
}
}

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

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