App crashes when changing activities
I volunteered to help out a community I am a part of in developing an Android application since I have programming experience. Part of this application is the need to change from one Activity to another. When I try to run the code to do this, the program crashes with the following exception in 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)
After googling the issue for a little while, I came across some suggestions that it could be that the second activity is not registered properly in my AndroidManifest.xml file. I added the second Activity through eclipse's GUI, so I'm pretty sure it's fine, but just in case, here is the Application node of the XML file
<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>
I've tried with and without the short cut "." in front of "Card" for the name of the activity. Both result in the same error in the LogCat.
Just for good measure, here is the code I am using to try to get to the second activity:
Intent i = new Intent(this, Card.class);
i.putExtra("id", id);
i.putExtra("searchText", m_SearchText.getText());
startActivityForResult(i, 1);
What could be causing this? If it would help for me to post anything else, please let me know. This error has held me up for a couple of days now and I can't find much at all on it.
EDIT: Here is the code for the second activity. Not sure what could be causing it, so posted it all.
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
}
}
}
You should be overriding onCreate(Bundle)
instead of filling out the default class constructor. Like so:
public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.card); .... }
If you aren't familiar with Activity lifecycles, its a good idea to take some time to read up on them. Instead of calling the class constructor to start an Activity, the system will automatically call onCreate()
, onDestroy()
and a lot more methods as necessary to allocate and free resources.
I am not sure but there may be problem of current Activity Context
. So I would suggest you should try like:
Intent i = new Intent(Main.this, Card.class);
Also post code of Second Activity here.
I think you are missing a period before the Card class in the manifest. See below:
From:
http://developer.android.com/guide/topics/manifest/activity-element.html
android:name
The name of the class that implements the activity, a subclass of Activity. The attribute value should be a fully qualified class name (such as, "com.example.project.ExtracurricularActivity"
). However, as a shorthand, if the first character of the name is a period (for example, ".ExtracurricularActivity"
), it is appended to the package name specified in the element.
There is no default. The name must be specified.
I was able to fix my issue by having both Activities extend Activity. Initially, it was crashing because the first Activity extended Activity whereas the second extend AppCompatActivity.
精彩评论