-3

我正在尝试将解析的数据保存到数据库中,但存在实例化异常。我正在使用 Parcelable 将解析的数组列表从一个活动传递到另一个活动。我需要将这些数组列表从一个活动传递到另一个活动并将其存储在 sqlite 中。

public class AndroidXMLParsingActivity extends ListActivity implements Parcelable{
//private ScheduleClient scheduleClient;
public Calendar cal;
//TextView desciption1;
TextView name1;
    private GetData mGetData;
// All static variables
static final String URL = "http address";
// XML node keys
static final String KEY_ITEM = "group_header"; // parent node
static String KEY_NAME = "name";
static  String KEY_ID = "group_day";
static  String KEY_COST = "day_sun_mrg";
static String KEY_DESC = "day_sun_evn";
static final String KEY_COST1 = "day_mon_mrg";
static final String KEY_DESC1 = "day_mon_evn";
static final String KEY_COST2 = "day_tue_mrg";
static final String KEY_DESC2 = "day_tue_evn";
static final String KEY_COST3 = "day_wed_mrg";
static final String KEY_DESC3 = "day_wed_evn";
static final String KEY_COST4 = "day_thu_mrg";
static final String KEY_DESC4 = "day_thu_evn";
static final String KEY_COST5 = "day_fri_mrg";
static final String KEY_DESC5 = "day_fri_evn";
static final String KEY_COST6 = "day_sat_mrg";
static final String KEY_DESC6 = "day_sat_evn";

ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();

// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);



    XMLParser parser = new XMLParser();
    String xml = parser.getXmlFromUrl(URL); // getting XML
    Document doc = parser.getDomElement(xml); // getting DOM element

    NodeList nl = doc.getElementsByTagName(KEY_ITEM);
    // looping through all item nodes <item>
    for (int i = 0; i < nl.getLength(); i++) {

        Element e = (Element) nl.item(i);
        // adding each child node to HashMap key => value
        map.put(KEY_ID, parser.getValue(e,   KEY_ID));
        map.put(KEY_NAME, parser.getValue(e, KEY_NAME));
        map.put(KEY_COST,parser.getValue(e,  KEY_COST));
        map.put(KEY_DESC, parser.getValue(e, KEY_DESC));
        map.put(KEY_COST1,parser.getValue(e, KEY_COST1));
        map.put(KEY_DESC1, parser.getValue(e,KEY_DESC1));
        map.put(KEY_COST2,parser.getValue(e, KEY_COST2));
        map.put(KEY_DESC2, parser.getValue(e,KEY_DESC2));
        map.put(KEY_COST3,parser.getValue(e, KEY_COST3));
        map.put(KEY_DESC3, parser.getValue(e,KEY_DESC3));
        map.put(KEY_COST4,parser.getValue(e, KEY_COST4));
        map.put(KEY_DESC4, parser.getValue(e,KEY_DESC4));
        map.put(KEY_COST5,parser.getValue(e, KEY_COST5));
        map.put(KEY_DESC5, parser.getValue(e,KEY_DESC5));
        map.put(KEY_COST6,parser.getValue(e, KEY_COST6));
        map.put(KEY_DESC6, parser.getValue(e,KEY_DESC6));

        // adding HashList to ArrayList
        menuItems.add(map);

        //Passing Data to Store Page
        mGetData.addLoad(menuItems);
        //putStringArrayListExtra(menuItems, ArrayList<String> menuItems);



}
    // Adding menuItems to ListView
    ListAdapter adapter = new SimpleAdapter(this, menuItems,
            R.layout.list_item,
            new String[] { KEY_NAME, KEY_DESC, KEY_COST }, new int[] {
            R.id.name, R.id.desciption, R.id.cost});

    setListAdapter(adapter);

    // selecting single ListView item
    ListView lv = getListView();

    lv.setOnItemClickListener(new OnItemClickListener() {

        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            // getting values from selected ListItem
            String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
            String cost = ((TextView) view.findViewById(R.id.cost)).getText().toString();
            String description = ((TextView) view.findViewById(R.id.desciption)).getText().toString();

            // Starting new intent
            Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
            in.putExtra(KEY_NAME, name);
            in.putExtra(KEY_COST, cost);
            in.putExtra(KEY_DESC, description);

            startActivity(in);


        }

    });
}

public int describeContents() {
    // TODO Auto-generated method stub
    return 0;
}

public void writeToParcel(Parcel dest, int flags) {
    // TODO Auto-generated method stub
    dest.writeString(KEY_NAME);
    dest.writeString(KEY_COST);
    dest.writeString(KEY_DESC);
}

public AndroidXMLParsingActivity(Parcel source){
    KEY_NAME=source.readString();
    KEY_COST=source.readString();
    KEY_DESC=source.readString();
    source.readArrayList(getClassLoader());
}

我的sqlite代码如下[WORKS]

public class DBAdapter {

// Contacts Table Columns names
public static final String KEY_ROWID = "_id";
private static final String KEY_NAME = "group_id";
private static final String KEY_SUNM = "sunm";
private static final String KEY_SUNE = "sune";
private static final String KEY_MONM = "monm";
private static final String KEY_MONE = "mone";
private static final String KEY_TUEM = "tuem";
private static final String KEY_TUEE = "tuee";
private static final String KEY_WEDM = "wedm";
private static final String KEY_WEDE = "wede";
private static final String KEY_THUM = "thum";
private static final String KEY_THUE = "thue";
private static final String KEY_FRIM = "frim";
private static final String KEY_FRIE = "frie";
private static final String KEY_SATM = "satm";
private static final String KEY_SATE = "sate";

AsyncTask sch;

// Database Name
private static final String DATABASE_NAME = "DB_NAME";

// Contacts table name
private static final String DATABASE_TABLE= "TABLE_NAME";

// Database Version
 private static final int DATABASE_VERSION = 1;

 // Creating Tables
 private static final String DATABASE_CREATE ="create table if not exists TABLE_NAME (_id integer primary key autoincrement,group_id text,sunm text ,sune text ,monm text,mone text ,tuem text,tuee text,wedm text ,wede text ,thum text,thue text ,frim text ,frie text ,satm text,sate text )";

 private final Context context;

 private DatabaseHelper DBHelper;

 private static SQLiteDatabase db;

 public DBAdapter(Context ctx)
 {
      this.context = ctx;
      DBHelper = new DatabaseHelper(context);
 }

 private static class DatabaseHelper extends SQLiteOpenHelper 
 {
     private static final String TAG = null;

    DatabaseHelper(Context context) 
     {
         super(context, DATABASE_NAME, null, DATABASE_VERSION);
     }

     @Override
     public void onCreate(SQLiteDatabase db) 
     {
         db.execSQL(DATABASE_CREATE);  
     }

     @Override
     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) 
     {
         Log.e(TAG, "Upgrading database from version " + oldVersion + " to "
                 + newVersion + ", which will destroy all old data");

         db.execSQL("DROP TABLE IF EXISTS schedules");
         onCreate(db);
     }
 }    

 //---opens the database---
 public DBAdapter open() throws SQLException 
 {
     db = DBHelper.getWritableDatabase();
     return this;
 }

 //---closes the database---    
 public void close() 
 {
     DBHelper.close();
 }

 //Inserting data into the table 
public void insertData(String group_id, String sunm, String sune, String monm, String mone, String tuem, String tuee, 
        String wedm, String wede, String thum, String thue, String frim, String frie, String satm, String sate) {
    try{
        Cursor cur = db.rawQuery("SELECT COUNT(*) FROM schedules", null);
     if (cur!=null && cur.getCount() > 0){
         cur.moveToFirst();
         if (cur.getInt(0) <= 6) {//put in these statements contained in array
             Log.i("DB getCount", " getcount less than 0, should read array");//log message

             String insertQuery ="INSERT INTO schedules(group_id,sunm,sune,monm,mone,tuem,tuee,wedm,wede,thum,thue,frim,frie," +
                    "satm,sate)"+ "VALUES" + "("+"'"+group_id+"'"+","+"'"+sunm+"'"+","+"'"+sune+"'"+","+"'"+monm+"'"+"," +
                    ""+"'"+mone+"'"+","+"'"+tuem+"'"+","+"'"+tuee+"'"+","+"'"+wedm+"'"+","+"'"+wede+"'"+","+"'"+thum+"'"+"," +
                            ""+"'"+thue+"'"+","+"'"+frim+"'"+","+"'"+frie+"'"+","+"'"+satm+"'"+","+"'"+sate+"'"+")";
             db.execSQL(insertQuery);

             Log.e("a", ""+cur.getCount());
         }
     }
     else{
           //do nothing everything's as it should be
         Log.i("DB getCount", " getcount greater than 0");  //log message  
     }
     cur.close();
    db.close();

     }
    catch(SQLiteException e){System.err.println("Exception @ rawQuery: " + e.getMessage());}
}

  //---retrieves all the title--- 
 public Cursor getAllTitles() 
 {
     return db.query(DATABASE_TABLE, new String[] {KEY_ROWID,KEY_NAME,KEY_SUNM,KEY_SUNE,KEY_MONM,KEY_MONE,KEY_MONM,KEY_TUEM,
     KEY_TUEE,KEY_WEDM,KEY_WEDE,KEY_THUM,KEY_THUE,KEY_FRIM,KEY_FRIE,KEY_SATM,KEY_SATE}, null, null, null, null, null, null);         
 }

 //---retrieves a particular title---
public ScheduleItem getSelectedItem(String group){

 ScheduleItem schedule = new ScheduleItem();

    // Select All Query
    String searchQuery = "select * from schedules where group_id = '"+group+"'";
    Log.e("DBAdapter", group);
        try{
            //Database not open error
             Cursor cur = db.rawQuery(searchQuery, null);

         if (cur!=null && cur.getCount() > 0){
          cur.moveToFirst();
        //Setting DB value to model scheduleitem.java
          schedule.setName(cur.getString(cur.getColumnIndex("group_id")));
          schedule.setSunm(cur.getString(cur.getColumnIndex("sunm")));
          schedule.setSune(cur.getString(cur.getColumnIndex("sune")));
          schedule.setMonm(cur.getString(cur.getColumnIndex("monm")));
          schedule.setMone(cur.getString(cur.getColumnIndex("mone")));
          schedule.setTuem(cur.getString(cur.getColumnIndex("tuem")));
          schedule.setTuee(cur.getString(cur.getColumnIndex("tuee")));
          schedule.setWedm(cur.getString(cur.getColumnIndex("wedm")));
          schedule.setWede(cur.getString(cur.getColumnIndex("wede")));
          schedule.setThum(cur.getString(cur.getColumnIndex("thum")));
          schedule.setThue(cur.getString(cur.getColumnIndex("thue")));
          schedule.setFrim(cur.getString(cur.getColumnIndex("frim")));
          schedule.setFrie(cur.getString(cur.getColumnIndex("frie")));
          schedule.setSatm(cur.getString(cur.getColumnIndex("satm")));
          schedule.setSate(cur.getString(cur.getColumnIndex("sate")));
          }

         cur.close();
         db.close();
         return schedule;

         }catch(SQLiteException e){System.err.println("Exception @ rawQuery: " + e.getMessage());}
      return schedule;
     }

    public void scheduleupdate(){

        Log.e(DATABASE_NAME, "Data Removed");
        //String delQuery="DELETE FROM TABLE schedules";
        context.deleteDatabase(DATABASE_NAME);
        //db.execSQL(delQuery);
        db.close();

    }
}

帮帮我Logcat错误

09-18 13:11:03.362: E/AndroidRuntime(471): FATAL EXCEPTION: main
09-18 13:11:03.362: E/AndroidRuntime(471): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.mokshya.multinodeparse/com.mokshya.multinodeparse.parse.AndroidXMLParsingActivity}: java.lang.InstantiationException: 
09-18 13:11:03.362: E/AndroidRuntime(471):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2585)
09-18 13:11:03.362: E/AndroidRuntime(471):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
09-18 13:11:03.362: E/AndroidRuntime(471):  at android.app.ActivityThread.access$2300(ActivityThread.java:125)
09-18 13:11:03.362: E/AndroidRuntime(471):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
09-18 13:11:03.362: E/AndroidRuntime(471):  at android.os.Handler.dispatchMessage(Handler.java:99)
09-18 13:11:03.362: E/AndroidRuntime(471):  at android.os.Looper.loop(Looper.java:123)
09-18 13:11:03.362: E/AndroidRuntime(471):  at android.app.ActivityThread.main(ActivityThread.java:4627)
09-18 13:11:03.362: E/AndroidRuntime(471):  at java.lang.reflect.Method.invokeNative(Native Method)
09-18 13:11:03.362: E/AndroidRuntime(471):  at java.lang.reflect.Method.invoke(Method.java:521)
09-18 13:11:03.362: E/AndroidRuntime(471):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
09-18 13:11:03.362: E/AndroidRuntime(471):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
09-18 13:11:03.362: E/AndroidRuntime(471):  at dalvik.system.NativeStart.main(Native Method)
09-18 13:11:03.362: E/AndroidRuntime(471): Caused by: java.lang.InstantiationException: com.mokshya.multinodeparse.parse.AndroidXMLParsingActivity
09-18 13:11:03.362: E/AndroidRuntime(471):  at java.lang.Class.newInstanceImpl(Native Method)
 09-18 13:11:03.362: E/AndroidRuntime(471):     at java.lang.Class.newInstance(Class.java:1429)
09-18 13:11:03.362: E/AndroidRuntime(471):  at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
09-18 13:11:03.362: E/AndroidRuntime(471):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2577)
09-18 13:11:03.362: E/AndroidRuntime(471):  ... 11 more
com.mokshya.multinodeparse.parse.AndroidXMLParsingActivity
4

3 回答 3

0

我认为您尚未在 AndroidManifest.xml 中注册您的活动

请在您的 AndroidManifest.xml 中注册您的活动。

每当您创建新活动时,您必须在 AndroidManifest.xml 中注册该活动。

于 2012-09-18T07:40:15.617 回答
0

您正在为AndroidXMLParsingActivity.

我不认为你应该重写构造函数。也不要让你的活动Serializable。创建一个自定义 Serializable 类,其中包含要传递的数据的字段。然后通过这个课程,而不是你的活动

于 2012-09-18T07:45:43.337 回答
0

我认为这可能会帮助一些新手解决问题,所以我发布了我的答案。在这里,我已经解析了值并使用 AsyncTask 直接将其从同一函数传递给 sqlite。代码如下:

public class LoadScheduleAsyncTask extends AsyncTask<String, String, String> {

DBAdapter dba;

Boolean isInternetPresent = false;

// Connection Detector Class
ConnectionDetector cd;

private ProgressDialog pDialog;

// Alert Dialog Manager
AlertDialogManager alert = new AlertDialogManager();

// XML Parsing URL
static final String URL = "url address";

// XML node keys
static final String KEY_ITEM = "group_header"; // Parent Node
static final String KEY_ROWID = "_id";
static final String KEY_NAME = "name";
static final String KEY_SUNM = "day_sun_mrg";
static final String KEY_SUNE = "day_sun_evn";
static final String KEY_MONM = "day_mon_mrg";
static final String KEY_MONE = "day_mon_evn";
static final String KEY_TUEM = "day_tue_mrg";
static final String KEY_TUEE = "day_tue_evn";
static final String KEY_WEDM = "day_wed_mrg";
static final String KEY_WEDE = "day_wed_evn";
static final String KEY_THUM = "day_thu_mrg";
static final String KEY_THUE = "day_thu_evn";
static final String KEY_FRIM = "day_fri_mrg";
static final String KEY_FRIE = "day_fri_evn";
static final String KEY_SATM = "day_sat_mrg";
static final String KEY_SATE = "day_sat_evn";

public static ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();

// Creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Context context;

public LoadScheduleAsyncTask(Context ctxt){
    dba=new DBAdapter(ctxt);
    context=ctxt;
}

/**
 * Before starting background thread Show Progress Dialog
 **/
@SuppressLint("NewApi")
@Override
protected void onPreExecute() {
    super.onPreExecute();
    pDialog = new ProgressDialog(context);
    pDialog.setMessage("Updating Data ...");
    pDialog.setIndeterminate(false);
    pDialog.setCancelable(false);
    pDialog.show();
}

/**
 * getting Schedule XML
 **/
protected String doInBackground(String... args) {
    XMLParser parser = new XMLParser();
    String xml = parser.getXmlFromUrl(URL); // getting XML
    Document doc = parser.getDomElement(xml); // getting DOM element
    NodeList nl = doc.getElementsByTagName(KEY_ITEM);
    // looping through all item nodes <item>
    for (int i = 0; i < nl.getLength(); i++) {
        Element e = (Element) nl.item(i);
        // adding each child node to HashMap key => value
        map.put(KEY_NAME, parser.getValue(e, KEY_NAME));
        map.put(KEY_SUNM, parser.getValue(e, KEY_SUNM));
        map.put(KEY_SUNE, parser.getValue(e, KEY_SUNE));
        map.put(KEY_MONM, parser.getValue(e, KEY_MONM));
        map.put(KEY_MONE, parser.getValue(e, KEY_MONE));
        map.put(KEY_TUEM, parser.getValue(e, KEY_TUEM));
        map.put(KEY_TUEE, parser.getValue(e, KEY_TUEE));
        map.put(KEY_WEDM, parser.getValue(e, KEY_WEDM));
        map.put(KEY_WEDE, parser.getValue(e, KEY_WEDE));
        map.put(KEY_THUM, parser.getValue(e, KEY_THUM));
        map.put(KEY_THUE, parser.getValue(e, KEY_THUE));
        map.put(KEY_FRIM, parser.getValue(e, KEY_FRIM));
        map.put(KEY_FRIE, parser.getValue(e, KEY_FRIE));
        map.put(KEY_SATM, parser.getValue(e, KEY_SATM));
        map.put(KEY_SATE, parser.getValue(e, KEY_SATE));
        // adding HashList to ArrayList
        menuItems.add(map);

        /**
         * Updating parsed JSON data into ListView
         **/
        String group_id = map.get(KEY_NAME);
        String sunm = map.get(KEY_SUNM);
        String sune = map.get(KEY_SUNE);
        String monm = map.get(KEY_MONM);
        String mone = map.get(KEY_MONE);
        String tuem = map.get(KEY_TUEM);
        String tuee = map.get(KEY_TUEE);
        String wedm = map.get(KEY_WEDM);
        String wede = map.get(KEY_WEDE);
        String thum = map.get(KEY_THUM);
        String thue = map.get(KEY_THUE);
        String frim = map.get(KEY_FRIM);
        String frie = map.get(KEY_FRIE);
        String satm = map.get(KEY_SATM);
        String sate = map.get(KEY_SATE);

        try {
            dba.open();
        } catch (SQLException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        dba.insertData(group_id, sunm, sune, monm, mone, tuem, tuee, wedm,
                wede, thum, thue, frim, frie, satm, sate);
        dba.close();
    }
    return null;
}

/**
 * After completing background task Dismiss the progress dialog
 **/
protected void onPostExecute(String file_url) {
    // dismiss the dialog after getting all schedules
    pDialog.dismiss();

}
}

这个答案基于与我的问题不同的方法。

于 2013-03-19T04:19:35.887 回答