- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我正在制作一个具有 2 个 java 类的应用程序:MainActivity
和 SecondActivity
。 MainActivity
使用 onClick
方法启动 SecondActivity
。
SecondActivity
在 strings.xml 文件中存储了 2 个数组。 SecondActivity
类想要将 strings.xml 中的所有数组变量存储到其自身,以便将其用于某些方法。我认为我这样做的方式是错误的,因为我尝试将数组直接存储在 SecondActivity
中并且它有效,但是当我将数组存储在 strings.xml 中时,它给出了 NullPointerException
。
这是SecondActivity
代码:
package com.android.ict.seneca.androidpocketguide;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class SecondActivity extends Activity {
private final String CLASS_NAME = "SecondActivity";
String [] Vocabularies = getResources().getStringArray(R.array.Vocabularies_array);
String [] meanings = getResources().getStringArray(R.array.meanings_array);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this,
android.R.layout.simple_dropdown_item_1line, Vocabularies);
//ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line, meanings);
AutoCompleteTextView textView =
(AutoCompleteTextView) findViewById(R.id.vocabularies);
textView.setThreshold(2); // minimum number of characters to be typed
textView.setAdapter(adapter); // connect the list of suggestions to the View object
}
public void onStart(){
super.onStart();
Log.d( CLASS_NAME, "onStart invoked!" );
}
public void onPause(){
super.onPause();
Log.d( CLASS_NAME, "onPause invoked!!" );
}
public void onResume(){
super.onResume();
Log.d( CLASS_NAME, "onResume invoked!!" );
}
public void onStop(){
super.onStop();
Log.d( CLASS_NAME, "onStop invoked!!!" );
}
public void onDestroy(){
super.onDestroy();
Log.d( CLASS_NAME, "onDestroy INVOKED!!!" );
}
public void onRestart(){
super.onRestart();
Log.d( CLASS_NAME, "onRestart invoked!!" );
}
// event handler for the button
public void onClick(View view) {
Intent data = new Intent();
EditText usr =
(EditText) findViewById(R.id.vocabularies); // get user input
// set the data part (an URI reference) of an intent
data.setData(Uri.parse(usr.getText().toString()));
String s = data.getData().toString();
int flag = 0;
for(int i=0; i<Vocabularies.length;i++)
{
if(s.equals(Vocabularies[i]))
{
flag = i;
}
}
Toast.makeText(this, "YOU'VE ENTERED: " + s, Toast.LENGTH_LONG ).show();
String m = meanings[flag];
String disp = "Vocabulary: " + s + "\n" + "Meaning: " + m;
TextView textViewObj1 = (TextView) findViewById(R.id.meaning);
textViewObj1.setText(disp);
//finish(); //--- close the activity AND RETURN CONTROL TO THE REQUESTING ACTIVITY
//EditText txt_username = (EditText) findViewById(R.id.txt_username);
} // end onClick
}
这是MainActivity
代码:
package com.android.ict.seneca.androidpocketguide;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private final String CLASS_NAME = "FirstActiviy";
private int request_Code = 1;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d( CLASS_NAME, "onCreate invoked!" );
}
public void onStart(){
super.onStart();
Log.d( CLASS_NAME, "onStart invoked!" );
}
public void onPause(){
super.onPause();
Log.d( CLASS_NAME, "onPause invoked!!" );
}
public void onResume(){
super.onResume();
Log.d( CLASS_NAME, "onResume invoked!!" );
}
public void onStop(){
super.onStop();
Log.d( CLASS_NAME, "onStop invoked!!!" );
}
public void onDestroy(){
super.onDestroy();
Log.d( CLASS_NAME, "onDestroy INVOKED!!!" );
}
public void onRestart(){
super.onRestart();
Log.d( CLASS_NAME, "onRestart invoked!!" );
}
// event handler for the button (activity 2)
public void onClick(View view) {
startActivityForResult( new Intent(
"com.android.ict.seneca.androidpocketguide.second"), // declared by an intent filter
request_Code); // (requesting) activity ID
Log.d( CLASS_NAME, "after startActivityForResult" );
//intent.setData(Uri.parse("com.seneca.lab2b.abbas"));
//startActivity(intent);
}
/*
public void onActivityResult( int requestCode, // used to match the REQUESTING activity ID
int resultCode, // result code set by the sender (i.e. the TARGET activity)
Intent data ) // an intent passed by the sender (i.e. the TARGET activity)
{
if (requestCode == request_Code) {
if (resultCode == RESULT_OK) {
//TextToSpeech(data.getData().toString());
Intent intent = getIntent();
String s = data.getData().toString();
TextView textViewObj1 = (TextView) findViewById(R.id.line);
textViewObj1.setText(s);
Toast.makeText(
this,
"MESSAGE RECEIVED: " + s, // retrieve data from the intent
// API Question: What is the return type of getData()?
Toast.LENGTH_LONG ).show();
}
}
Log.d( CLASS_NAME, "onActivityResult: what is next?" );
}
// event handler for a button (activity 3)
public void onClick3(View view) {
Intent dataIntent = new Intent( this, ThirdActivity.class );//"com.seneca.lab2b.third"); // explicit intent
// the putExtra( ) method
dataIntent.putExtra( "greeting", "Good morning Android!" );
dataIntent.putExtra( "number", 123 );
// create a Bundle object
Bundle bundle = new Bundle();
bundle.putString( "My name", "Abbas Zoeb" );
bundle.putInt( "Student ID", 56789 );
// putExtras( ): store the bundle in the intent
dataIntent.putExtras( bundle );
// launch the third activity
startActivity( dataIntent );
//startActivity( new Intent( this, ThirdActivity.class ) );
}
*/
}
这是错误日志:
09-21 23:43:19.907 26183-26183/com.android.ict.seneca.androidpocketguide E/AndroidRuntime: FATAL EXCEPTION: main Process: com.android.ict.seneca.androidpocketguide, PID: 26183 java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.android.ict.seneca.androidpocketguide/com.android.ict.seneca.androidpocketguide.SecondActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2327) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) at android.app.ActivityThread.-wrap11(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:5417) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference at android.content.ContextWrapper.getResources(ContextWrapper.java:87) at android.view.ContextThemeWrapper.getResources(ContextThemeWrapper.java:81) at com.android.ict.seneca.androidpocketguide.SecondActivity.(SecondActivity.java:22) at java.lang.Class.newInstance(Native Method) at android.app.Instrumentation.newActivity(Instrumentation.java:1067) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2317) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) at android.app.ActivityThread.-wrap11(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:5417) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
这是 string.xml 文件:
<resources>
<string name="app_name">Android Pocket Guide</string>
<string-array name="Vocabularies_array">
<item>activity</item>
<item>AVD</item>
<item>ART</item>
<item>Dalvik</item>
<item>intent</item>
<item>intent filter</item>
<item>explicit intent</item>
<item>implicit intent</item>
<item>LogCat</item>
<item>bundle</item>
<item>Gradle</item>
<item>Android Device Monitor</item>
<item>SDK manager</item>
<item>minSdkVersion</item>
</string-array>
<string-array name="meanings_array">
<item>An activity represents a single screen with a user interface just like window or frame of Java</item>
<item>An Android Virtual Device (AVD) is an emulator configuration that lets you model an actual device by defining hardware and software options to be emulated by the Android Emulator.</item>
<item>Android Runtime (ART) is an application runtime environment used by the Android operating system.</item>
<item>Dalvik is a part of the software stack that makes up the Android platform.</item>
<item>Intent can be defined as a simple message objects which is used to communicate from 1 activity to another.</item>
<item>Specifies the types of intents that an activity, service, or broadcast receiver can respond to</item>
<item>An explicit intent is one that you use to launch a specific app component, such as a particular activity or service in your app</item>
<item>Implicit intents do not name a specific component, but instead declare a general action to perform, which allows a component from another app to handle it.</item>
<item>Logcat is a command-line tool that dumps a log of system messages, including stack traces when the device throws an error and messages that you have written from your app with the Log class.</item>
<item>A Bundle is a set of key/value pairs, where it implements an interface called Parcelable.</item>
<item>Gradle is a custom build tool used to build android packages (apk files) by managing dependencies and providing custom build logic.</item>
<item>Android Device Monitor is a standalone tool that provides a UI for several Android application debugging and analysis tools.</item>
<item>A software development kit that enables developers to create applications for the Android platform.</item>
<item>An integer designating the minimum API Level required for the application to run.</item>
</string-array>
</resources>
最佳答案
试试这个方法
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Vocabularies = getResources().getStringArray(R.array.Vocabularies_array);
meanings = getResources().getStringArray(R.array.meanings_array);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this,
android.R.layout.simple_dropdown_item_1line, Vocabularies);
//ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line, meanings);
AutoCompleteTextView textView =
(AutoCompleteTextView) findViewById(R.id.vocabularies);
textView.setThreshold(2); // minimum number of characters to be typed
textView.setAdapter(adapter); // connect the list of suggestions to the View object
}
关于java - android数组空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39629987/
我正在编写一个具有以下签名的 Java 方法。 void Logger(Method method, Object[] args); 如果一个方法(例如 ABC() )调用此方法 Logger,它应该
我是 Java 新手。 我的问题是我的 Java 程序找不到我试图用作的图像文件一个 JButton。 (目前这段代码什么也没做,因为我只是得到了想要的外观第一的)。这是我的主课 代码: packag
好的,今天我在接受采访,我已经编写 Java 代码多年了。采访中说“Java 垃圾收集是一个棘手的问题,我有几个 friend 一直在努力弄清楚。你在这方面做得怎么样?”。她是想骗我吗?还是我的一生都
我的 friend 给了我一个谜语让我解开。它是这样的: There are 100 people. Each one of them, in his turn, does the following
如果我将使用 Java 5 代码的应用程序编译成字节码,生成的 .class 文件是否能够在 Java 1.4 下运行? 如果后者可以工作并且我正在尝试在我的 Java 1.4 应用程序中使用 Jav
有关于why Java doesn't support unsigned types的问题以及一些关于处理无符号类型的问题。我做了一些搜索,似乎 Scala 也不支持无符号数据类型。限制是Java和S
我只是想知道在一个 java 版本中生成的字节码是否可以在其他 java 版本上运行 最佳答案 通常,字节码无需修改即可在 较新 版本的 Java 上运行。它不会在旧版本上运行,除非您使用特殊参数 (
我有一个关于在命令提示符下执行 java 程序的基本问题。 在某些机器上我们需要指定 -cp 。 (类路径)同时执行java程序 (test为java文件名与.class文件存在于同一目录下) jav
我已经阅读 StackOverflow 有一段时间了,现在我才鼓起勇气提出问题。我今年 20 岁,目前在我的家乡(罗马尼亚克卢日-纳波卡)就读 IT 大学。足以介绍:D。 基本上,我有一家提供簿记应用
我有 public JSONObject parseXML(String xml) { JSONObject jsonObject = XML.toJSONObject(xml); r
我已经在 Java 中实现了带有动态类型的简单解释语言。不幸的是我遇到了以下问题。测试时如下代码: def main() { def ks = Map[[1, 2]].keySet()
一直提示输入 1 到 10 的数字 - 结果应将 st、rd、th 和 nd 添加到数字中。编写一个程序,提示用户输入 1 到 10 之间的任意整数,然后以序数形式显示该整数并附加后缀。 public
我有这个 DownloadFile.java 并按预期下载该文件: import java.io.*; import java.net.URL; public class DownloadFile {
我想在 GUI 上添加延迟。我放置了 2 个 for 循环,然后重新绘制了一个标签,但这 2 个 for 循环一个接一个地执行,并且标签被重新绘制到最后一个。 我能做什么? for(int i=0;
我正在对对象 Student 的列表项进行一些测试,但是我更喜欢在 java 类对象中创建硬编码列表,然后从那里提取数据,而不是连接到数据库并在结果集中选择记录。然而,自从我这样做以来已经很长时间了,
我知道对象创建分为三个部分: 声明 实例化 初始化 classA{} classB extends classA{} classA obj = new classB(1,1); 实例化 它必须使用
我有兴趣使用 GPRS 构建车辆跟踪系统。但是,我有一些问题要问以前做过此操作的人: GPRS 是最好的技术吗?人们意识到任何问题吗? 我计划使用 Java/Java EE - 有更好的技术吗? 如果
我可以通过递归方法反转数组,例如:数组={1,2,3,4,5} 数组结果={5,4,3,2,1}但我的结果是相同的数组,我不知道为什么,请帮助我。 public class Recursion { p
有这样的标准方式吗? 包括 Java源代码-测试代码- Ant 或 Maven联合单元持续集成(可能是巡航控制)ClearCase 版本控制工具部署到应用服务器 最后我希望有一个自动构建和集成环境。
我什至不知道这是否可能,我非常怀疑它是否可能,但如果可以,您能告诉我怎么做吗?我只是想知道如何从打印机打印一些文本。 有什么想法吗? 最佳答案 这里有更简单的事情。 import javax.swin
我是一名优秀的程序员,十分优秀!