从json存储到sqlite db中

时间:2014-01-25 08:54:14

标签: android json eclipse sqlite

我对这个编程很新,并试图做几件事。我尝试了这里提供的示例代码。我不知道我错在哪里。我想将json存储到sqlite db中,但它显示错误。请告诉我解决方案。提前致谢。

我的Json文件格式如下:

[{"Companies":"Agriculture Development Bank","Tran.":"94","Max.":"484","Min.":"469","Close":"480","Volume":"13779","Amount":"6598289","Last Close":"478","Net Chg":"[TABLE]","":"","id":0},{"Companies":"Alliance Insurance Co. Ltd.","Tran.":"2","Max.":"550","Min.":"539","Close":"539","Volume":"750","Amount":"407000","Last Close":"550","Net Chg":"[TABLE]","":"","id":1}

我的loginactivity.java文件是这样的

package com.example.merostock;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.annotation.TargetApi;
import android.widget.TextView;

public class LoginActivity extends Activity {

DBAdapter myDb;
private ProgressDialog pDialog;

// URL to get contacts JSON
private static String url = "http://www.dreamsint.com.np/nepse.json.php";

// JSON Node names
private static final String TAG_COMPANIES = "Companies";
private static final String TAG_TRAN = "Tran.";
private static final String TAG_MAX = "Max.";
private static final String TAG_MIN = "Min.";
private static final String TAG_CLOSE = "Close";
private static final String TAG_VOLUME = "Volume";
private static final String TAG_AMOUNT = "Amount";
private static final String TAG_LASTCLOSE = "Last Close";


public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // setting default screen to login.xml
    setContentView(R.layout.login);

    //openDB();
    myDb = new DBAdapter(this);
    myDb.open();
    TextView registerScreen = (TextView) findViewById(R.id.link_to_register);

    // Listening to register new account link
    registerScreen.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            // Switching to Register screen
            Intent i = new Intent(getApplicationContext(), RegisterActivity.class);
            startActivity(i);
        }
    });
    new GetContacts().execute();
    }
    protected void onDestroy() {
        super.onDestroy();  
        closeDB();
    }


    private void openDB() {
        myDb = new DBAdapter(this);
        myDb.open();
    }
    private void closeDB() {
        myDb.close();
    }
    private class GetContacts extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            pDialog = new ProgressDialog(LoginActivity.this);
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(false);
            pDialog.show();

        }

        @TargetApi(19)
        @Override
        protected Void doInBackground(Void... arg0) {
             // Creating JSON Parser instance
            JSONArray arr = null;
            JSONParser jParser = new JSONParser();

            // getting JSON string from URL
            JSONObject json = jParser.getJSONFromUrl(url);

            try {
                // Getting Array of Contacts
                arr = new JSONArray(json);
                //contacts = json.getJSONArray(TAG_CONTACTS);

                // looping through All Contacts
                for (int i = 0; i < arr.length(); i++) {
                    JSONObject c = arr.getJSONObject(i);

                    // Storing each json item in variable
                    String companies = c.getString(TAG_COMPANIES);
                    String tran = c.getString(TAG_TRAN);
                    String max = c.getString(TAG_MAX);
                    String min = c.getString(TAG_MIN);
                    String close = c.getString(TAG_CLOSE);
                    String volume = c.getString(TAG_VOLUME);
                    String amt = c.getString(TAG_AMOUNT);
                    String lastclose = c.getString(TAG_LASTCLOSE);
                    myDb.insertRow(companies, tran, max, min, close, volume, amt, lastclose); 
                    }
        }catch (JSONException e) {
            e.printStackTrace();

        }
          return null;
          }}
          }

我的DBAdapter.java文件

  

// ------------------------------------ DBADapter.java ------ ---------------------------------------

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



  public class DBAdapter {

/////////////////////////////////////////////////////////////////////
//  Constants & Data
/////////////////////////////////////////////////////////////////////
// For logging:
private static final String TAG = "DBAdapter";

// DB Fields
public static final String KEY_ROWID = "id";
public static final int COL_ROWID = 0;
/*
 * CHANGE 1:
 */
// TODO: Setup your fields here:
public static final String KEY_COMPANIES = "companies";
public static final String KEY_TRANSACTIONS = "transactions";
public static final String KEY_MAX = "max";
public static final String KEY_MIN = "min";
public static final String KEY_CLOSE = "close";
public static final String KEY_VOLUME = "volume";
public static final String KEY_AMOUNT = "amt";
public static final String KEY_LASTCLOSE = "lastclose";

// TODO: Setup your field numbers here (0 = KEY_ROWID, 1=...)
public static final int COL_NAME = 1;
public static final int COL_STUDENTNUM = 2;
public static final int COL_FAVCOLOUR = 3;


public static final String[] ALL_KEYS = new String[] {KEY_ROWID, KEY_COMPANIES, KEY_TRANSACTIONS, KEY_MAX, KEY_MIN, KEY_CLOSE, KEY_VOLUME, KEY_AMOUNT, KEY_LASTCLOSE};

// DB info: it's name, and the table we are using (just one).
public static final String DATABASE_NAME = "MyDb.db";
public static final String DATABASE_TABLE = "mainTable";
// Track DB version if a new version of your app changes the format.
public static final int DATABASE_VERSION = 2;   

private static final String DATABASE_CREATE_SQL = 
        "create table " + DATABASE_TABLE 
        + " (" + KEY_ROWID + " integer primary key autoincrement, "

        /*
         * CHANGE 2:
         */
        // TODO: Place your fields here!
        // + KEY_{...} + " {type} not null"
        //  - Key is the column name you created above.
        //  - {type} is one of: text, integer, real, blob
        //      (http://www.sqlite.org/datatype3.html)
        //  - "not null" means it is a required field (must be given a value).
        // NOTE: All must be comma separated (end of line!) Last one must have NO comma!!
        + KEY_COMPANIES + " text not null, "
        + KEY_TRANSACTIONS + " text not null, "
        + KEY_MAX + " text not null, "
        + KEY_MIN + " text not null, "
        + KEY_CLOSE + " text not null, "
        + KEY_VOLUME + " text not null, "
        + KEY_AMOUNT + " text not null, "
        + KEY_LASTCLOSE + "text not null "
        // Rest  of creation:
        + ");";

// Context of application who uses us.
private final Context context;

private DatabaseHelper myDBHelper;
private SQLiteDatabase db;

/////////////////////////////////////////////////////////////////////
//  Public methods:
/////////////////////////////////////////////////////////////////////

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

// Open the database connection.
public DBAdapter open() {
    db = myDBHelper.getWritableDatabase();
    return this;
}

// Close the database connection.
public void close() {
    myDBHelper.close();
}

// Add a new set of values to the database.
public long insertRow(String companies, String tran, String max, String min, String close, String volume, String amt, String lastclose ) {
    /*
     * CHANGE 3:
     */     
    // TODO: Update data in the row with new fields.
    // TODO: Also change the function's arguments to be what you need!
    // Create row's data:
    ContentValues initialValues = new ContentValues();
    initialValues.put(KEY_COMPANIES, companies);
    initialValues.put(KEY_TRANSACTIONS, tran);
    initialValues.put(KEY_MAX, max);
    initialValues.put(KEY_MIN, min);
    initialValues.put(KEY_CLOSE, close);
    initialValues.put(KEY_VOLUME, volume);
    initialValues.put(KEY_AMOUNT, amt);
    initialValues.put(KEY_LASTCLOSE, lastclose);

    // Insert it into the database.
    return db.insert(DATABASE_TABLE, null, initialValues);
}

// Delete a row from the database, by rowId (primary key)
public boolean deleteRow(long rowId) {
    String where = KEY_ROWID + "=" + rowId;
    return db.delete(DATABASE_TABLE, where, null) != 0;
}

public void deleteAll() {
    Cursor c = getAllRows();
    long rowId = c.getColumnIndexOrThrow(KEY_ROWID);
    if (c.moveToFirst()) {
        do {
            deleteRow(c.getLong((int) rowId));              
        } while (c.moveToNext());
    }
    c.close();
}

// Return all data in the database.
public Cursor getAllRows() {
    String where = null;
    Cursor c =  db.query(true, DATABASE_TABLE, ALL_KEYS, 
                        where, null, null, null, null, null);
    if (c != null) {
        c.moveToFirst();
    }
    return c;
}

// Get a specific row (by rowId)
public Cursor getRow(long rowId) {
    String where = KEY_ROWID + "=" + rowId;
    Cursor c =  db.query(true, DATABASE_TABLE, ALL_KEYS, 
                    where, null, null, null, null, null);
    if (c != null) {
        c.moveToFirst();
    }
    return c;
}

// Change an existing row to be equal to new data.
public boolean updateRow(long rowId, String name, int studentNum, String favColour) {
    String where = KEY_ROWID + "=" + rowId;

    /*
     * CHANGE 4:
     */
    // TODO: Update data in the row with new fields.
    // TODO: Also change the function's arguments to be what you need!
    // Create row's data:
    ContentValues newValues = new ContentValues();
    newValues.put(KEY_COMPANIES, name);
    newValues.put(KEY_TRANSACTIONS, studentNum);
    newValues.put(KEY_MAX, favColour);

    // Insert it into the database.
    return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}



/////////////////////////////////////////////////////////////////////
//  Private Helper Classes:
/////////////////////////////////////////////////////////////////////

/**
 * Private class which handles database creation and upgrading.
 * Used to handle low-level database access.
 */
private static class DatabaseHelper extends SQLiteOpenHelper
{
    DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase _db) {
        _db.execSQL(DATABASE_CREATE_SQL);           
    }

    @Override
    public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {
        Log.w(TAG, "Upgrading application's database from version " + oldVersion
                + " to " + newVersion + ", which will destroy all old data!");

        // Destroy old database:
        _db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);

        // Recreate new database:
        onCreate(_db);
    }
}
    }

我的JSONParser.java文件

package com.example.merostock;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}

public JSONObject getJSONFromUrl(String url) {

// Making HTTP request
try {
    // defaultHttpClient
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(url);

    HttpResponse httpResponse = httpClient.execute(httpPost);
    HttpEntity httpEntity = httpResponse.getEntity();
    is = httpEntity.getContent();           

} catch (UnsupportedEncodingException e) {
    e.printStackTrace();
} catch (ClientProtocolException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

try {
    BufferedReader reader = new BufferedReader(new InputStreamReader(
            is, "iso-8859-1"), 8);
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
        sb.append(line + "\n");
    }
    is.close();
    json = sb.toString();
} catch (Exception e) {
    Log.e("Buffer Error", "Error converting result " + e.toString());
}

// try parse the string to a JSON object
try {
    jObj = new JSONObject(json);
} catch (JSONException e) {
    Log.e("JSON Parser", "Error parsing data " + e.toString());
}

// return JSON String
return jObj;

}
} 

Logcat

01-25 07:05:35.849: E/JSON Parser(1483): Error parsing data org.json.JSONException: Value [{"id":0,"":"","--":"--","#VALUE!":"--"},{"id":1,"":"","--":"--","#VALUE!":"--"},{"id":2,"":"","--":"--","#VALUE!":"--"},{"id":3,"":"","--":"--","#VALUE!":"--"},{"id":4,"":"","--":"--","#VALUE!":"--"},{"id":5,"":"","--":"--","#VALUE!":"--"},{"id":6,"":"","--":"--","#VALUE!":"--"},{"id":7,"":"","--":"--","#VALUE!":"--"},{"id":8,"":"","--":"--","#VALUE!":"--"},{"id":9,"":"1\/25\/2014 17:50:00","--":"--","#VALUE!":"--"},{"id":10,"":"","--":"--
01-25 07:05:35.849: W/dalvikvm(1483): threadid=11: thread exiting with uncaught exception (group=0xb3af5ba8)
01-25 07:05:35.889: I/Choreographer(1483): Skipped 36 frames!  The application may be doing too much work on its main thread.
01-25 07:05:36.549: E/AndroidRuntime(1483): FATAL EXCEPTION: AsyncTask #1
01-25 07:05:36.549: E/AndroidRuntime(1483): Process: com.example.merostock, PID: 1483
01-25 07:05:36.549: E/AndroidRuntime(1483): java.lang.RuntimeException: An error occured while executing doInBackground()
01-25 07:05:36.549: E/AndroidRuntime(1483):     at android.os.AsyncTask$3.done(AsyncTask.java:300)
01-25 07:05:36.549: E/AndroidRuntime(1483):     at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
01-25 07:05:36.549: E/AndroidRuntime(1483):     at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
01-25 07:05:36.549: E/AndroidRuntime(1483):     at java.util.concurrent.FutureTask.run(FutureTask.java:242)
01-25 07:05:36.549: E/AndroidRuntime(1483):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
01-25 07:05:36.549: E/AndroidRuntime(1483):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
01-25 07:05:36.549: E/AndroidRuntime(1483):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
01-25 07:05:36.549: E/AndroidRuntime(1483):     at java.lang.Thread.run(Thread.java:841)
01-25 07:05:36.549: E/AndroidRuntime(1483): Caused by: java.lang.NullPointerException
01-25 07:05:36.549: E/AndroidRuntime(1483):     at org.json.JSONArray.<init>(JSONArray.java:115)
01-25 07:05:36.549: E/AndroidRuntime(1483):     at com.example.merostock.LoginActivity$GetContacts.doInBackground(LoginActivity.java:96)
01-25 07:05:36.549: E/AndroidRuntime(1483):     at com.example.merostock.LoginActivity$GetContacts.doInBackground(LoginActivity.java:1)
01-25 07:05:36.549: E/AndroidRuntime(1483):     at android.os.AsyncTask$2.call(AsyncTask.java:288)
01-25 07:05:36.549: E/AndroidRuntime(1483):     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
01-25 07:05:36.549: E/AndroidRuntime(1483):     ... 4 more
01-25 07:05:36.819: I/Choreographer(1483): Skipped 63 frames!  The application may be doing too much work on its main thread.
01-25 07:05:37.179: I/Choreographer(1483): Skipped 92 frames!  The application may be doing too much work on its main thread.
01-25 07:05:37.439: I/Choreographer(1483): Skipped 67 frames!  The application may be doing too much work on its main thread.
01-25 07:05:37.649: I/Choreographer(1483): Skipped 49 frames!  The application may be doing too much work on its main thread.
01-25 07:05:37.919: I/Choreographer(1483): Skipped 67 frames!  The application may be doing too much work on its main thread.
01-25 07:05:39.499: I/Choreographer(1483): Skipped 39 frames!  The application may be doing too much work on its main thread.
01-25 07:05:39.639: I/Choreographer(1483): Skipped 34 frames!  The application may be doing too much work on its main thread.
01-25 07:05:39.929: I/Choreographer(1483): Skipped 47 frames!  The application may be doing too much work on its main thread.
 01-25 07:05:40.269: I/Choreographer(1483): Skipped 53 frames!  The application may be doing too much work on its main thread.
01-25 07:05:40.519: I/Choreographer(1483): Skipped 30 frames!  The application may be doing too much work on its main thread.
01-25 07:05:40.709: I/Choreographer(1483): Skipped 44 frames!  The application may be doing too much work on its main thread.
01-25 07:05:42.419: E/WindowManager(1483): android.view.WindowLeaked: Activity com.example.merostock.LoginActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{b3eb3888 V.E..... R.....ID 0,0-456,144} that was originally added here
01-25 07:05:42.419: E/WindowManager(1483):  at android.view.ViewRootImpl.<init>(ViewRootImpl.java:348)
01-25 07:05:42.419: E/WindowManager(1483):  at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:248)
01-25 07:05:42.419: E/WindowManager(1483):  at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
01-25 07:05:42.419: E/WindowManager(1483):  at android.app.Dialog.show(Dialog.java:286)
01-25 07:05:42.419: E/WindowManager(1483):  at com.example.merostock.LoginActivity$GetContacts.onPreExecute(LoginActivity.java:80)
01-25 07:05:42.419: E/WindowManager(1483):  at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
01-25 07:05:42.419: E/WindowManager(1483):  at android.os.AsyncTask.execute(AsyncTask.java:535)
01-25 07:05:42.419: E/WindowManager(1483):  at com.example.merostock.LoginActivity.onCreate(LoginActivity.java:56)
 01-25 07:05:42.419: E/WindowManager(1483):     at android.app.Activity.performCreate(Activity.java:5231)
 01-25 07:05:42.419: E/WindowManager(1483):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
01-25 07:05:42.419: E/WindowManager(1483):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
01-25 07:05:42.419: E/WindowManager(1483):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
01-25 07:05:42.419: E/WindowManager(1483):  at android.app.ActivityThread.access$800(ActivityThread.java:135)
01-25 07:05:42.419: E/WindowManager(1483):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
01-25 07:05:42.419: E/WindowManager(1483):  at android.os.Handler.dispatchMessage(Handler.java:102)
01-25 07:05:42.419: E/WindowManager(1483):  at android.os.Looper.loop(Looper.java:136)
01-25 07:05:42.419: E/WindowManager(1483):  at android.app.ActivityThread.main(ActivityThread.java:5017)
01-25 07:05:42.419: E/WindowManager(1483):  at java.lang.reflect.Method.invokeNative(Native Method)
01-25 07:05:42.419: E/WindowManager(1483):  at java.lang.reflect.Method.invoke(Method.java:515)
01-25 07:05:42.419: E/WindowManager(1483):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
01-25 07:05:42.419: E/WindowManager(1483):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
01-25 07:05:42.419: E/WindowManager(1483):  at dalvik.system.NativeStart.main(Native Method)
01-25 07:10:36.829: I/Process(1483): Sending signal. PID: 1483 SIG: 9

0 个答案:

没有答案