由于我有编程经验,因此我自愿帮助开发Android应用程序的社区。此应用程序的一部分是需要从一个Activity更改为另一个Activity。当我尝试运行代码来执行此操作时,程序在LogCat中崩溃并出现以下异常:
03-16 20:25:29.164: ERROR/AndroidRuntime(497): FATAL EXCEPTION: main
03-16 20:25:29.164: ERROR/AndroidRuntime(497): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.a.android.app/com.a.android.app.Card}: java.lang.InstantiationException: com.a.android.app.Card
03-16 20:25:29.164: ERROR/AndroidRuntime(497): at android.app.ActivityThread.performLaunchActivity(A ctivityThread.java:2585)
03-16 20:25:29.164: ERROR/AndroidRuntime(497): at android.app.ActivityThread.handleLaunchActivity(Ac tivityThread.java:2679)
03-16 20:25:29.164: ERROR/AndroidRuntime(497): at android.app.ActivityThread.access$2300(ActivityThr ead.java:125)
03-16 20:25:29.164: ERROR/AndroidRuntime(497): at android.app.ActivityThread$H.handleMessage(Activit yThread.java:2033)
03-16 20:25:29.164: ERROR/AndroidRuntime(497): at android.os.Handler.dispatchMessage(Handler.java:99 )
03-16 20:25:29.164: ERROR/AndroidRuntime(497): at android.os.Looper.loop(Looper.java:123)
03-16 20:25:29.164: ERROR/AndroidRuntime(497): at android.app.ActivityThread.main(ActivityThread.jav a:4627)
03-16 20:25:29.164: ERROR/AndroidRuntime(497): at java.lang.reflect.Method.invokeNative(Native Method)
03-16 20:25:29.164: ERROR/AndroidRuntime(497): at java.lang.reflect.Method.invoke(Method.java:521)
03-16 20:25:29.164: ERROR/AndroidRuntime(497): at com.android.internal.os.ZygoteInit$MethodAndArgsCa ller.run(ZygoteInit.java:868)
03-16 20:25:29.164: ERROR/AndroidRuntime(497): at com.android.internal.os.ZygoteInit.main(ZygoteInit .java:626)
03-16 20:25:29.164: ERROR/AndroidRuntime(497): at dalvik.system.NativeStart.main(Native Method)
03-16 20:25:29.164: ERROR/AndroidRuntime(497): Caused by: java.lang.InstantiationException: com.a.android.app.Card
03-16 20:25:29.164: ERROR/AndroidRuntime(497): at java.lang.Class.newInstanceImpl(Native Method)
03-16 20:25:29.164: ERROR/AndroidRuntime(497): at java.lang.Class.newInstance(Class.java:1429)
03-16 20:25:29.164: ERROR/AndroidRuntime(497): at android.app.Instrumentation.newActivity(Instrument ation.java:1021)
03-16 20:25:29.164: ERROR/AndroidRuntime(497): at android.app.ActivityThread.performLaunchActivity(A ctivityThread.java:2577)
在谷歌搜索了一段时间后,我发现了一些建议,可能是我的AndroidManifest.xml文件中没有正确注册第二个活动。我通过eclipse的GUI添加了第二个Activity,所以我很确定它很好,但以防万一,这里是XML文件的Application节点
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".Main"
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:icon="@drawable/icon" android:name="Card" android:label="@string/app_name"></activity>
</application>
我尝试过没有捷径“。”在“卡片”前面的活动名称。两者都会导致LogCat中出现相同的错误。
只是好好衡量,这是我用来尝试进入第二个活动的代码:
Intent i = new Intent(this, Card.class);
i.putExtra("id", id);
i.putExtra("searchText", m_SearchText.getText());
startActivityForResult(i, 1);
可能导致这种情况的原因是什么?如果它有助于我发布任何其他内容,请告诉我。这个错误让我忍受了几天,我根本找不到多少。
编辑:这是第二个活动的代码。不确定是什么导致它,所以发布了所有。
public class Card extends Activity
{
private int m_Id;
private EditText m_SearchText;
public Card(Bundle savedInstanceState)
{
try
{
super.onCreate(savedInstanceState);
setContentView(R.layout.card);
Bundle extras = getIntent().getExtras();
if(extras == null)
{
// nothing to do here
return;
}
m_Id = extras.getInt("id");
m_SearchText = (EditText)findViewById(R.id.txtSearch2);
m_SearchText.setText(extras.getString("searchText"));
Button search = (Button)findViewById(R.id.btnSearch2);
search.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
ReturnToMain(m_SearchText.getText());
}
});
m_SearchText.addTextChangedListener(new TextWatcher(){
public void afterTextChanged(Editable s) { }
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
ReturnToMain(s);
}
public void onTextChanged(CharSequence s, int start, int before, int count) {}
});
new LongOperation().execute(this);
}
catch(Exception ex)
{
ShowError(ex.getMessage() + "\n" + ex.toString(), "Create Card");
ex.printStackTrace();
}
}
private void ReturnToMain(CharSequence s)
{
Intent i = new Intent();
i.putExtra("searchText", s);
setResult(RESULT_OK, i);
}
private void ShowError(String message, String title)
{
new AlertDialog.Builder(this)
.setTitle("Error! - " + title)
.setMessage(message)
.setNeutralButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) { }
})
.show();
}
private class LongOperation extends AsyncTask<Context, Void, String> {
String cardNumber;
String sortName;
String cardName;
String cardType;
String tr3CardType;
String attribute;
String level;
String icon;
String atk;
String def;
String cardText;
String cardRulings;
Context currentContext;
@Override
protected String doInBackground(Context... params) {
try {
currentContext = params[0];
// search the database for everything with given id
DataBaseHelper myHelper = new DataBaseHelper(currentContext);
try
{
myHelper.createDataBase();
}
catch(IOException ioe)
{
ShowError(ioe.getMessage(), "CDB");
}
try
{
myHelper.openDataBase();
}
catch(SQLException sqle)
{
ShowError(sqle.getMessage(), "ODB");
}
Cursor results = myHelper.ExecSql("SELECT [CardNumber], [SortName], [CardName], [CardType], [Tr3CardType], [Attribute], [Level], [Icon], [ATK], [DEF], [CardText], [CardRulings] FROM Card WHERE _id = " + String.valueOf(m_Id), null);
results.moveToPosition(0);
cardNumber = results.getString(1);
sortName = results.getString(2);
cardName = results.getString(3);
cardType = results.getString(4);
tr3CardType = results.getString(5);
attribute = results.getString(6);
level = results.getString(7);
icon = results.getString(8);
atk = results.getString(9);
def = results.getString(10);
cardText = results.getString(11);
cardRulings = results.getString(12);
results.close();
results = myHelper.ExecSql("SELECT [CardName], [CardRulings] FROM Card WHERE CardRulings LIKE '%" + cardName + "%'", null);
results.moveToFirst();
while(!results.isAfterLast())
{
String[] individualRulings = results.getString(2).split("<br>");
for (int i = 0; i < individualRulings.length; i++)
{
if (individualRulings[i].contains(cardName))
{
cardRulings += "\n\n[" + results.getString(1) + "]: " + individualRulings[i];
}
}
results.moveToNext();
}
results.close();
myHelper.close();
} catch (Exception e) {
ShowError(e.toString() + "\n" + e.getMessage(), "Thread");
}
return "";
}
/* (non-Javadoc)
* @see android.os.AsyncTask#onPostExecute(java.lang.Object)
*/
@Override
protected void onPostExecute(String result) {
try {
// execution of result of Long time consuming operation
((TextView)findViewById(R.id.lblSortName)).setText(sortName);
((TextView)findViewById(R.id.lblCardName)).setText(cardName);
((TextView)findViewById(R.id.lblCardText)).setText(cardText);
((TextView)findViewById(R.id.lblCardNum)).setText("(" + cardNumber + ")");
((TextView)findViewById(R.id.lblCardRulings)).setText(cardRulings);
if(tr3CardType == "Monster")
{
((TextView)findViewById(R.id.lblCardLevelAttr)).setText(", " + level + ", " + attribute);
((TextView)findViewById(R.id.lblCardType)).setText(cardType + ", " + atk + "/" + def);
}
else
{
((TextView)findViewById(R.id.lblCardLevelAttr)).setText("");
if (icon != "")
{
((TextView)findViewById(R.id.lblCardType)).setText(cardType + " (" + icon + ")");
}
else
{
((TextView)findViewById(R.id.lblCardType)).setText(cardType);
}
}
} catch (Exception e) {
ShowError(e.getMessage() + "\n" + e.toString(), "After Thread");
e.printStackTrace();
}
}
/* (non-Javadoc)
* @see android.os.AsyncTask#onPreExecute()
*/
@Override
protected void onPreExecute() {
// Things to be done before execution of long running operation. For example showing ProgessDialog
}
/* (non-Javadoc)
* @see android.os.AsyncTask#onProgressUpdate(Progress[])
*/
@Override
protected void onProgressUpdate(Void... values) {
// Things to be done while execution of long running operation is in progress. For example updating ProgessDialog
}
}
}
答案 0 :(得分:4)
您应该覆盖onCreate(Bundle)
而不是填写默认的类构造函数。像这样:
public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.card); .... }
如果您不熟悉Activity lifecycles,最好花些时间阅读它们。系统将自动调用onCreate()
,onDestroy()
以及更多必要的方法来分配和释放资源,而不是调用类构造函数来启动Activity。
答案 1 :(得分:1)
我不确定但是可能存在当前活动Context
的问题。所以我建议你应该尝试:
Intent i = new Intent(Main.this, Card.class);
此处也发布第二活动代码。
答案 2 :(得分:1)
我认为你错过了清单中Card类之前的一段时间。见下文:
自:
http://developer.android.com/guide/topics/manifest/activity-element.html
android:name
实现活动的类的名称,Activity的子类。属性值应该是完全限定的类名(例如,"com.example.project.ExtracurricularActivity"
)。但是,作为简写,如果名称的第一个字符是句点(例如,".ExtracurricularActivity"
),则它将附加到元素中指定的包名称。
没有默认值。必须指定名称。
答案 3 :(得分:0)
通过让两个活动都扩展活动,我能够解决我的问题。 最初,它崩溃了,因为第一个 Activity 扩展了 Activity 而第二个扩展了 AppCompatActivity。