当我刚刚启动我的第一个 Android 应用程序时,我已经获得了我的第一个问题。
下面的代码非常简单,唯一的目标是从 MainActivity.java 导航到 IMC.java 但是,我一直在寻找很多教程的解决方案,但我真的不明白我做错了什么......
package com.example.firstapp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.view.View;
import android.view.View.OnClickListener;
public class MainActivity extends Activity {
Button IMC;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
IMC = (Button) findViewById(R.id.buttonIMC);
IMC.setOnClickListener(IMCListener);
}
// Listener du bouton IMC
private OnClickListener IMCListener = new OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this,IMC.class);
startActivity(i);
}
};
}
在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: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=".IMC" >
<Button
android:id="@+id/buttonIMC"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:text="IMC" />
</RelativeLayout>
堆栈跟踪是
11-03 16:30:04.877: E/AndroidRuntime(619): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.firstapp/com.example.firstapp.IMC}: java.lang.NullPointerException
11-03 16:30:04.877: E/AndroidRuntime(619): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
11-03 16:30:04.877: E/AndroidRuntime(619): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
11-03 16:30:04.877: E/AndroidRuntime(619): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
11-03 16:30:04.877: E/AndroidRuntime(619): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
11-03 16:30:04.877: E/AndroidRuntime(619): at android.os.Handler.dispatchMessage(Handler.java:99)
11-03 16:30:04.877: E/AndroidRuntime(619): at android.os.Looper.loop(Looper.java:123)
11-03 16:30:04.877: E/AndroidRuntime(619): at android.app.ActivityThread.main(ActivityThread.java:4627)
11-03 16:30:04.877: E/AndroidRuntime(619): at java.lang.reflect.Method.invokeNative(Native Method)
11-03 16:30:04.877: E/AndroidRuntime(619): at java.lang.reflect.Method.invoke(Method.java:521)
11-03 16:30:04.877: E/AndroidRuntime(619): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
11-03 16:30:04.877: E/AndroidRuntime(619): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
11-03 16:30:04.877: E/AndroidRuntime(619): at dalvik.system.NativeStart.main(Native Method)
11-03 16:30:04.877: E/AndroidRuntime(619): Caused by: java.lang.NullPointerException
11-03 16:30:04.877: E/AndroidRuntime(619): at com.example.firstapp.IMC.onCreate(IMC.java:57)
11-03 16:30:04.877: E/AndroidRuntime(619): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
11-03 16:30:04.877: E/AndroidRuntime(619): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
list 在下面
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.firstapp"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.firstapp.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="com.example.firstapp.MainActivity2"
android:label="@string/title_activity_main_activity2" >
</activity>
<activity
android:name="com.example.firstapp.IMCActivity"
android:label="@string/title_activity_imc" >
</activity>
<activity
android:name="com.example.firstapp.Interest"
android:label="@string/title_activity_interest" >
</activity>
<activity
android:name="com.example.firstapp.IMC"
android:label="@string/title_activity_imc" >
</activity>
</application>
</manifest>
Activity IMC 已经设置好并且工作正常(基本上,它只是一个简单的计算) 在这里完全详尽的是:
package com.example.firstapp;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import android.text.TextWatcher;
import android.text.Editable;
public class IMC extends Activity {
// La chaîne de caractères par défaut
private final String defaut = "Vous devez cliquer sur le bouton « Calculer l'IMC » pour obtenir un résultat.";
// La chaîne de caractères de la megafonction
private final String megaString = "Vous faites un poids parfait ! Wahou ! Trop fort ! On dirait Brad Pitt (si vous êtes un homme)/Angelina Jolie (si vous êtes une femme)/Willy (si vous êtes un orque) !";
Button envoyer = null;
Button raz = null;
EditText poids = null;
EditText taille = null;
RadioGroup group = null;
TextView result = null;
CheckBox mega = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// On récupère toutes les vues dont on a besoin
envoyer = (Button)findViewById(R.id.calcul);
raz = (Button)findViewById(R.id.raz);
taille = (EditText)findViewById(R.id.taille);
poids = (EditText)findViewById(R.id.poids);
mega = (CheckBox)findViewById(R.id.mega);
group = (RadioGroup)findViewById(R.id.group);
result = (TextView)findViewById(R.id.result);
// On attribue un listener adapté aux vues qui en ont besoin
envoyer.setOnClickListener(envoyerListener);
raz.setOnClickListener(razListener);
taille.addTextChangedListener(textWatcher);
poids.addTextChangedListener(textWatcher);
// Solution avec des onKey
//taille.setOnKeyListener(modificationListener);
//poids.setOnKeyListener(modificationListener);
mega.setOnClickListener(checkedListener);
}
/*
// Se lance à chaque fois qu'on appuie sur une touche en étant sur un EditText
private OnKeyListener modificationListener = new OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
// On remet le texte à sa valeur par défaut pour ne pas avoir de résultat incohérent
result.setText(defaut);
return false;
}
};*/
private TextWatcher textWatcher = new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
result.setText(defaut);
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void afterTextChanged(Editable s) {
}
};
// Uniquement pour le bouton "envoyer"
private OnClickListener envoyerListener = new OnClickListener() {
@Override
public void onClick(View v) {
if(!mega.isChecked()) {
// Si la megafonction n'est pas activée
// On récupère la taille
String t = taille.getText().toString();
// On récupère le poids
String p = poids.getText().toString();
float tValue = Float.valueOf(t);
// Puis on vérifie que la taille est cohérente
if(tValue == 0)
Toast.makeText(IMC.this, "Hého, tu es un Minipouce ou quoi ?", Toast.LENGTH_SHORT).show();
else {
float pValue = Float.valueOf(p);
// Si l'utilisateur a indiqué que la taille était en centimètres
// On vérifie que la Checkbox sélectionnée est la deuxième à l'aide de son identifiant
if(group.getCheckedRadioButtonId() == R.id.radio2)
tValue = tValue / 100;
tValue = (float)Math.pow(tValue, 2);
float imc = pValue / tValue;
result.setText("Votre IMC est " + String.valueOf(imc));
}
} else
result.setText(megaString);
}
};
// Listener du bouton de remise à zéro
private OnClickListener razListener = new OnClickListener() {
@Override
public void onClick(View v) {
poids.getText().clear();
taille.getText().clear();
result.setText(defaut);
}
};
// Listener du bouton de la megafonction.
private OnClickListener checkedListener = new OnClickListener() {
@Override
public void onClick(View v) {
// On remet le texte par défaut si c'était le texte de la megafonction qui était écrit
if(!((CheckBox)v).isChecked() && result.getText().equals(megaString))
result.setText(defaut);
}
};
}
(上面这段代码不是我写的,是来自openclassroom的教程)
你有什么想法吗,不胜感激:)
谢谢!
最佳答案
Line 57 of IMC.java envoyer.setOnClickListener(envoyerListener)
看起来 envoyer 为空。
你有
setContentView(R.layout.activity_main);
您的 activity_main.xml 没有具有该 ID R.id.calcul 的按钮。
你需要改变这个
setContentView(R.layout.imc); // layout xml for IMC Activity
确保它有一个 ID 为 R.id.calcul 的按钮,它会起作用。
关于android - 无法启动 Activity ComponentInfo{...} : java. lang.NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19755282/
我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-
我对最新版本的Rails有疑问。我创建了一个新应用程序(railsnewMyProject),但我没有脚本/生成,只有脚本/rails,当我输入ruby./script/railsgeneratepluginmy_plugin"Couldnotfindgeneratorplugin.".你知道如何生成插件模板吗?没有这个命令可以创建插件吗?PS:我正在使用Rails3.2.1和ruby1.8.7[universal-darwin11.0] 最佳答案 随着Rails3.2.0的发布,插件生成器已经被移除。查看变更日志here.现在
我尝试运行2.x应用程序。我使用rvm并为此应用程序设置其他版本的ruby:$rvmuseree-1.8.7-head我尝试运行服务器,然后出现很多错误:$script/serverNOTE:Gem.source_indexisdeprecated,useSpecification.Itwillberemovedonorafter2011-11-01.Gem.source_indexcalledfrom/Users/serg/rails_projects_terminal/work_proj/spohelp/config/../vendor/rails/railties/lib/r
我正在尝试在我的centos服务器上安装therubyracer,但遇到了麻烦。$geminstalltherubyracerBuildingnativeextensions.Thiscouldtakeawhile...ERROR:Errorinstallingtherubyracer:ERROR:Failedtobuildgemnativeextension./usr/local/rvm/rubies/ruby-1.9.3-p125/bin/rubyextconf.rbcheckingformain()in-lpthread...yescheckingforv8.h...no***e
我花了三天的时间用头撞墙,试图弄清楚为什么简单的“rake”不能通过我的规范文件。如果您遇到这种情况:任何文件夹路径中都不要有空格!。严重地。事实上,从现在开始,您命名的任何内容都没有空格。这是我的控制台输出:(在/Users/*****/Desktop/LearningRuby/learn_ruby)$rake/Users/*******/Desktop/LearningRuby/learn_ruby/00_hello/hello_spec.rb:116:in`require':cannotloadsuchfile--hello(LoadError) 最佳
我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/
最近,当我启动我的Rails服务器时,我收到了一长串警告。虽然它不影响我的应用程序,但我想知道如何解决这些警告。我的估计是imagemagick以某种方式被调用了两次?当我在警告前后检查我的git日志时。我想知道如何解决这个问题。-bcrypt-ruby(3.1.2)-better_errors(1.0.1)+bcrypt(3.1.7)+bcrypt-ruby(3.1.5)-bcrypt(>=3.1.3)+better_errors(1.1.0)bcrypt和imagemagick有关系吗?/Users/rbchris/.rbenv/versions/2.0.0-p247/lib/ru
我在pry中定义了一个函数:to_s,但我无法调用它。这个方法去哪里了,怎么调用?pry(main)>defto_spry(main)*'hello'pry(main)*endpry(main)>to_s=>"main"我的ruby版本是2.1.2看了一些答案和搜索后,我认为我得到了正确的答案:这个方法用在什么地方?在irb或pry中定义方法时,会转到Object.instance_methods[1]pry(main)>defto_s[1]pry(main)*'hello'[1]pry(main)*end=>:to_s[2]pry(main)>defhello[2]pry(main)
我使用的是Firefox版本36.0.1和Selenium-Webdrivergem版本2.45.0。我能够创建Firefox实例,但无法使用脚本继续进行进一步的操作无法在60秒内获得稳定的Firefox连接(127.0.0.1:7055)错误。有人能帮帮我吗? 最佳答案 我遇到了同样的问题。降级到firefoxv33后一切正常。您可以找到旧版本here 关于ruby-无法在60秒内获得稳定的Firefox连接(127.0.0.1:7055),我们在StackOverflow上找到一个类
当我尝试安装Ruby时遇到此错误。我试过查看this和this但无济于事➜~brewinstallrubyWarning:YouareusingOSX10.12.Wedonotprovidesupportforthispre-releaseversion.Youmayencounterbuildfailuresorotherbreakages.Pleasecreatepull-requestsinsteadoffilingissues.==>Installingdependenciesforruby:readline,libyaml,makedepend==>Installingrub