1

我是android和java的新手。我试图根据示例检查我的代码,但不知何故,当示例运行良好时,应用程序会强制关闭。我需要帮助!提前致谢!我只是将名称更改为字符串而不是 int。我不知道我对 HistoryActivity 的 ArrayAdapter 是否正确

日志猫:

07-31 17:26:56.485: E/ArrayAdapter(20248): You must supply a resource ID for a TextView
07-31 17:26:56.490: D/AndroidRuntime(20248): Shutting down VM
07-31 17:26:56.490: W/dalvikvm(20248): threadid=1: thread exiting with uncaught exception (group=0x40fdb2a0)
07-31 17:26:56.505: E/AndroidRuntime(20248): FATAL EXCEPTION: main
07-31 17:26:56.505: E/AndroidRuntime(20248): java.lang.IllegalStateException: ArrayAdapter requires the resource ID to be a TextView
07-31 17:26:56.505: E/AndroidRuntime(20248):    at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:386)
07-31 17:26:56.505: E/AndroidRuntime(20248):    at android.widget.ArrayAdapter.getView(ArrayAdapter.java:362)
07-31 17:26:56.505: E/AndroidRuntime(20248):    at android.widget.AbsListView.obtainView(AbsListView.java:2465)
07-31 17:26:56.505: E/AndroidRuntime(20248):    at android.widget.ListView.makeAndAddView(ListView.java:1775)
07-31 17:26:56.505: E/AndroidRuntime(20248):    at android.widget.ListView.fillDown(ListView.java:678)
07-31 17:26:56.505: E/AndroidRuntime(20248):    at android.widget.ListView.fillFromTop(ListView.java:739)
07-31 17:26:56.505: E/AndroidRuntime(20248):    at android.widget.ListView.layoutChildren(ListView.java:1628)
07-31 17:26:56.505: E/AndroidRuntime(20248):    at android.widget.AbsListView.onLayout(AbsListView.java:2300)
07-31 17:26:56.505: E/AndroidRuntime(20248):    at android.view.View.layout(View.java:14072)
07-31 17:26:56.505: E/AndroidRuntime(20248):    at android.view.ViewGroup.layout(ViewGroup.java:4607)
07-31 17:26:56.505: E/AndroidRuntime(20248):    at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1655)
07-31 17:26:56.505: E/AndroidRuntime(20248):    at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1513)
07-31 17:26:56.505: E/AndroidRuntime(20248):    at android.widget.LinearLayout.onLayout(LinearLayout.java:1426)
07-31 17:26:56.505: E/AndroidRuntime(20248):    at android.view.View.layout(View.java:14072)
07-31 17:26:56.505: E/AndroidRuntime(20248):    at android.view.ViewGroup.layout(ViewGroup.java:4607)
07-31 17:26:56.505: E/AndroidRuntime(20248):    at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
07-31 17:26:56.505: E/AndroidRuntime(20248):    at android.view.View.layout(View.java:14072)
07-31 17:26:56.505: E/AndroidRuntime(20248):    at android.view.ViewGroup.layout(ViewGroup.java:4607)
07-31 17:26:56.505: E/AndroidRuntime(20248):    at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1655)
07-31 17:26:56.505: E/AndroidRuntime(20248):    at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1513)
07-31 17:26:56.505: E/AndroidRuntime(20248):    at android.widget.LinearLayout.onLayout(LinearLayout.java:1426)
07-31 17:26:56.505: E/AndroidRuntime(20248):    at android.view.View.layout(View.java:14072)
07-31 17:26:56.505: E/AndroidRuntime(20248):    at android.view.ViewGroup.layout(ViewGroup.java:4607)
07-31 17:26:56.505: E/AndroidRuntime(20248):    at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
07-31 17:26:56.505: E/AndroidRuntime(20248):    at android.view.View.layout(View.java:14072)
07-31 17:26:56.505: E/AndroidRuntime(20248):    at android.view.ViewGroup.layout(ViewGroup.java:4607)
07-31 17:26:56.505: E/AndroidRuntime(20248):    at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:1997)
07-31 17:26:56.505: E/AndroidRuntime(20248):    at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1818)
07-31 17:26:56.505: E/AndroidRuntime(20248):    at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1115)
07-31 17:26:56.505: E/AndroidRuntime(20248):    at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4526)
07-31 17:26:56.505: E/AndroidRuntime(20248):    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:725)
07-31 17:26:56.505: E/AndroidRuntime(20248):    at android.view.Choreographer.doCallbacks(Choreographer.java:555)
07-31 17:26:56.505: E/AndroidRuntime(20248):    at android.view.Choreographer.doFrame(Choreographer.java:525)
07-31 17:26:56.505: E/AndroidRuntime(20248):    at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:711)
07-31 17:26:56.505: E/AndroidRuntime(20248):    at android.os.Handler.handleCallback(Handler.java:615)
07-31 17:26:56.505: E/AndroidRuntime(20248):    at android.os.Handler.dispatchMessage(Handler.java:92)
07-31 17:26:56.505: E/AndroidRuntime(20248):    at android.os.Looper.loop(Looper.java:137)
07-31 17:26:56.505: E/AndroidRuntime(20248):    at android.app.ActivityThread.main(ActivityThread.java:4921)
07-31 17:26:56.505: E/AndroidRuntime(20248):    at java.lang.reflect.Method.invokeNative(Native Method)
07-31 17:26:56.505: E/AndroidRuntime(20248):    at java.lang.reflect.Method.invoke(Method.java:511)
07-31 17:26:56.505: E/AndroidRuntime(20248):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
07-31 17:26:56.505: E/AndroidRuntime(20248):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
07-31 17:26:56.505: E/AndroidRuntime(20248):    at dalvik.system.NativeStart.main(Native Method)
07-31 17:26:56.505: E/AndroidRuntime(20248): Caused by: java.lang.ClassCastException: android.widget.LinearLayout cannot be cast to android.widget.TextView
07-31 17:26:56.505: E/AndroidRuntime(20248):    at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:379)
07-31 17:26:56.505: E/AndroidRuntime(20248):    ... 42 more

联系人.java

 package com.Elson.ProjectVersion;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteException;
import android.util.Log;

public class Contacts implements Comparable<Contacts> {

    private long id;
    private String name;
    private int Phone;
    private int Email;
    private Date date;
    private double runningAverage;




    public Contacts(String name, int Phone,  Date date) {
        this.name = name;
        this.Phone = Phone;
        this.date = date;
    }

    public Contacts(long id, String name,int Phone) {
        this.id=id;
        this.Phone=Phone;
        this.name= (name);

    }


    public long getId() {

        return id;
    }
    public void setId(long id) {
        this.id = id;
    }

    public int getPhone() {
        return Phone;
    }
    public void setPhone(int Phone) {
        this.Phone = Phone;
    }
    public String getname() {
        return name;
    }
    public void setname(String name) {
        this.name = name;
    }
    public Date getDate() {
        return date;
    }

    public long getDateEpoch(){
        return date.getTime()/1000;
    }
    public void setDateEpoch(long seconds){
        date= new Date (seconds*1000);
    }
    public void setDate(Date date) {
        this.date = date;
    }




    public void setRunningAverage(double runningAverage) {
        this.runningAverage = runningAverage;
    }
    public boolean equals(Object that){
        Contacts bs = (Contacts) that;

        return this.date.equals(bs.date);
      }


    @Override



    public String toString() {
        String result;

        // "ID" + id +" "
        DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);
        result = df.format(date) + "" + name + "" + Phone ; 



        return result;
    }

    @Override
    public int compareTo(Contacts another) {
        // TODO Auto-generated method stub
        return 0;
    }

}

联系人活动应用程序:

package com.Elson.ProjectVersion;

import java.util.ArrayList;

import android.app.Application;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import static com.Elson.ProjectVersion.MyContactSQL.*;

public class EnterContactsActivity extends Activity {

private Button saveButton;
private EditText NameEditText;
private EditText PhoneEditText;
private Button ExitButton;
private EditText EmailEditText;
private TextView date;

private int month;//private within class
private int day;
private int year;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_addcontacts);

    setUpViews();

    Calendar calendar =Calendar.getInstance();
    year = calendar.get(Calendar.YEAR);
    month = calendar.get(Calendar.MONTH);
    day = calendar.get(Calendar.DAY_OF_MONTH);

    Date today = calendar.getTime();
    DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM);
    String cs = df.format(today);
    date.setText(cs);
}


public void saveClickHandler(View v){

    String ContactsScore;
    ContactsScore= NameEditText.getText().toString();
    String name = String.format(ContactsScore, null);
    ContactsScore= PhoneEditText.getText().toString();
    int Phone = Integer.parseInt(ContactsScore);

    Log.d("EnterContacts" , "I hear the Save Button");

    if( isValid(Phone) ) {
        Contacts contacts;
        Date dateofGames= new GregorianCalendar(year,month,day).getTime();
        contacts = new Contacts (name , Phone ,  dateofGames);

        ContactsActivityApplication app  = (ContactsActivityApplication) getApplication();
        //might be wrong

        Log.d("DeBUGGING", "app is this type: " + app.getClass().getName());
        //need add the function addBowlingScores
        app.addallContacts(contacts);

        Toast.makeText(getApplicationContext(), "Your Contact has been Saved!", Toast.LENGTH_SHORT).show();

}

    else{
        //pop up a dialog that data is invalid
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Invalid Phone Number")
               .setMessage("Phone numbers cannot have more than 8 numbers")
               .setCancelable(false)
               .setPositiveButton("OK", 

                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub
                        dialog.cancel(); 
                    }
                });

        AlertDialog alert = builder.create();
        alert.show();
    }
    }



private boolean isValid(int Phone ) {

    if(Phone > 0 && Phone <100000000)
        return true;
    return false;
    // TODO Auto-generated method stub
}


public void handleShowHistoryClick (View v) {

    Intent intent = new Intent(this, HistoryActivity.class);
    startActivity(intent);
}


private void setUpViews()
{
    ExitButton = (Button) findViewById(R.id.BtnExit);
    saveButton =(Button) findViewById(R.id.BtnSave);
    NameEditText= (EditText) findViewById(R.id.NameEditText);
    PhoneEditText= (EditText) findViewById(R.id.PhoneEditText);
    EmailEditText= (EditText) findViewById(R.id.EmailEditText);
    date = (TextView) findViewById(R.id.DateTextView);

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.addcontacts, menu);
    return true;
}

}

EnterContactsActivity:

package com.Elson.ProjectVersion;

import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class EnterContactsActivity extends Activity {

private Button saveButton;
private EditText NameEditText;
private EditText PhoneEditText;
private Button ExitButton;
private EditText EmailEditText;
private TextView date;

private int month;//private within class
private int day;
private int year;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_addcontacts);

    setUpViews();

    Calendar calendar =Calendar.getInstance();
    year = calendar.get(Calendar.YEAR);
    month = calendar.get(Calendar.MONTH);
    day = calendar.get(Calendar.DAY_OF_MONTH);

    Date today = calendar.getTime();
    DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM);
    String cs = df.format(today);
    date.setText(cs);
}


public void saveClickHandler(View v){

    String ContactsScore;
    ContactsScore= NameEditText.getText().toString();
    int name = Integer.parseInt(ContactsScore);
    ContactsScore= PhoneEditText.getText().toString();
    int Phone = Integer.parseInt(ContactsScore);
    ContactsScore = EmailEditText.getText().toString();
    int Email = Integer.parseInt(ContactsScore);

    Log.d("EnterContacts" , "I hear the Save Button");

    if( isValid(name) && isValid(Phone) && isValid(Email) ) {
        Contacts contacts;
        Date dateofGames= new GregorianCalendar(year,month,day).getTime();
        contacts = new Contacts (name , Phone , Email, dateofGames);

        ContactsActivityApplication app  = (ContactsActivityApplication) getApplication();
        //might be wrong

        Log.d("DeBUGGING", "app is this type: " + app.getClass().getName());
        //need add the function addBowlingScores
        app.addallContacts(contacts);

        Toast.makeText(getApplicationContext(), "Your Contact has been Saved!", Toast.LENGTH_SHORT).show();

}

    else{
        //pop up a dialog that data is invalid
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Invalid Phone Number")
               .setMessage("Phone numbers cannot have more than 8 numbers")
               .setCancelable(false)
               .setPositiveButton("OK", 

                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub
                        dialog.cancel(); 
                    }
                });

        AlertDialog alert = builder.create();
        alert.show();
    }
    }
private boolean isValid(int phone) {

    if(phone <= 0 && phone >=100000000)
        return true;
    return false;
    // TODO Auto-generated method stub
}


private void setUpViews()
{
    ExitButton = (Button) findViewById(R.id.BtnExit);
    saveButton =(Button) findViewById(R.id.BtnSave);
    NameEditText= (EditText) findViewById(R.id.NameEditText);
    PhoneEditText= (EditText) findViewById(R.id.PhoneEditText);
    EmailEditText= (EditText) findViewById(R.id.EmailEditText);
    date = (TextView) findViewById(R.id.DateTextView);

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.addcontacts, menu);
    return true;
}

 }

我的联系人 SQL:

package com.Elson.ProjectVersion;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteException;
import android.util.Log;

公共类 MyContactSQL 扩展 SQLiteOpenHelper {

public static final String DB_NAME ="MyContactSQL.SQLite";
public static final int DB_VERSION = 1;
public static String CONTACT_LIST_TABLE = "ContactListTable";
public static String RECORD_ID ="ID";
public  static String NAME = "NAME";
public static String PHONE_NUMBER="PhoneNumber";

public MyContactSQL(Context context) {
    super(context, DB_NAME, null, DB_VERSION);

}

@Override
public void onCreate(SQLiteDatabase contactListDB) {


    String sqlStatement = "create table " + CONTACT_LIST_TABLE 
            + " ("
            + RECORD_ID + " integer primary key autoincrement not null,"
            + NAME + " long,"
            + PHONE_NUMBER +" integer"
            +");";


           Log.d("Contact Database", sqlStatement);

           contactListDB.execSQL(sqlStatement);

}

@Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {

}

}

历史活动:

import java.util.ArrayList;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.os.Bundle; 
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class HistoryActivity extends ListActivity {

Bundle savedInstanceState;
private ArrayList <Contacts> allContacts;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.savedInstanceState = savedInstanceState;
    setContentView(R.layout.history_layout);

    //get data from the App
    ContactsActivityApplication app = (ContactsActivityApplication) getApplication();
    allContacts = app.getAllContacts();


    //View  --- Adapter  ------ Data 

    setListAdapter(
            new ArrayAdapter<Contacts> (this, R.layout.history_row,
                    allContacts
                    ));

        ListView listView = this.getListView();
        listView.setOnItemClickListener(
                 new OnItemClickListener() {

                    @Override
                    public void onItemClick(AdapterView<?> parent, View view,
                            int position, long id) {
                        verifyDeleteRow(position);
                        Log.d("DEBUG", "I hear item selected:" + position);
                        // TODO Auto-generated method stub

                    }

                 }

                 );
 }

private void verifyDeleteRow(final int position){
    //pop up a dialog to confirm delete row
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Delete this Series?")
           .setMessage("Do you want to delete this data?" + allContacts.get(position))
           .setCancelable(false)
           .setNegativeButton("NO! Leave it there!", 

                   new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub
                    dialog.cancel(); 
                }
            })
           .setPositiveButton("Delete", 

            new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {

                    Contacts toDelete = allContacts.get(position);

                    ContactsActivityApplication app = (ContactsActivityApplication) getApplication();
                    app.deleteBowlingScores(toDelete);
                    // TODO Auto-generated method stub
                    onCreate(savedInstanceState);
                }
            });

    AlertDialog alert = builder.create();
    alert.show();

}
}
4

2 回答 2

1

date您传递给的对象df.format是 NULL,这导致NullPointerException

public String toString() {
    String result;

    // "ID" + id +" "
    DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);
    result = df.format(date) + "" + name + "" + Phone ; 
             ^^^^^^^^^^^^^^^
             date object is null above


    return result;
}

您需要对实例进行空检查date

if(date != null) {
        DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);
        result = df.format(date) + "" + name + "" + Phone ; 
}
else {
      result = name + "" + Phone ; 
}
于 2013-07-31T09:12:11.630 回答
1

我认为date当您尝试在此处使用它进行解析时,该变量未初始化:

result = df.format(date) + "" + name + "" + Phone ; 

因此,请确保在将其传递给解析之前已对其进行了初始化。

只发布与您的问题相关的代码。除非需要,否则不是整个代码。它造成了很多混乱

于 2013-07-31T09:14:26.300 回答