Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7489249
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 29, 20262026-05-29T15:13:14+00:00 2026-05-29T15:13:14+00:00

I am having issues with storing JSON data to sqlite. This is the code

  • 0

I am having issues with storing JSON data to sqlite. This is the code which I am trying to implement right now. The JSON data is not particularly big with only 40 lines in it.

The main activity is:

public class DatabaseActivity extends Activity {
/** Called when the activity is first created. */

public DBAdapter
DBAdapter =new DBAdapter(this);

TextView txt;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Create a crude view - this should really be set via the layout resources  
// but since its an example saves declaring them in the XML.  
LinearLayout rootLayout = new LinearLayout(getApplicationContext());  
txt = new TextView(getApplicationContext());  
rootLayout.addView(txt);  
setContentView(rootLayout);  

// Set the text and call the connect function.  
txt.setText("Connecting..."); 
//call the method to run the data retreival
txt.setText(getServerData(KEY_13)); 

}

public static final String KEY_13 = "http://xxx.xxx.xxx/api/train.php";


private String getServerData(String returnString) {

InputStream is = null;

String result = "";
//the train line to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("code","A"));

//http post
try{
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(KEY_13);
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();

}catch(Exception e){
        Log.e("log_tag", "Error in http connection "+e.toString());
}

//convert response to string
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();
        result=sb.toString();
}catch(Exception e){
        Log.e("log_tag", "Error converting result "+e.toString());
}

//parse json data
try{
        JSONArray jArray = new JSONArray(result);
        for(int i=0;i<jArray.length();i++){
                JSONObject json_data = jArray.getJSONObject(i);
                DBAdapter.insertTrain(json_data.getString("id"),
                                    json_data.getString("code"),
                                    json_data.getString("station"),
                                    json_data.getString("platform"),
                                    json_data.getString("timetillstation"),
                                    json_data.getString("traindestination"),

                //Get an output to the screen
                returnString += "\n\t" + jArray.getJSONObject(i); 
        }
}catch(JSONException e){
        Log.e("log_tag", "Error parsing data "+e.toString());
}
return returnString; 
}    

}

The adapter is:

public class DBAdapter{
public static final String KEY_ID = "id";
public static final String KEY_Code = "code";
public static final String KEY_Station = "station";
public static final String KEY_Platform = "platform";
public static final String KEY_TimeTillStation = "timetillstation";
public static final String KEY_TrainDestination = "traindestination";
private static final String TAG = "DBAdapter";

private static final String DATABASE_NAME = "trains";
private static final String DATABASE_TABLE = "Mekerel";
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_CREATE =
    "create table titles (id integer primary key, "
    + "code text not null,"
    + "station text not null,"
    + "platform text not null,"
    + "timetillstation text not null,"
    + "traindestination text not null);";

private final Context context; 

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

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);        }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, 
    int newVersion) 
    {
        Log.w(TAG, "Upgrading database from version " + oldVersion 
                + " to "
                + newVersion + ", which will destroy all old data");
        db.execSQL("DROP TABLE IF EXISTS titles");
        onCreate(db);
    }
}    

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

//---insert a train into the database---
public long insertTrain(String id, String code, String station, String platform, String timetillstation, String traindestination) 
{
    ContentValues initialValues = new ContentValues();
    initialValues.put(KEY_ID, id);
    initialValues.put(KEY_Code, code);
    initialValues.put(KEY_Station, station);
    initialValues.put(KEY_Platform, platform);
    initialValues.put(KEY_TimeTillStation, timetillstation);
    initialValues.put(KEY_TrainDestination, traindestination);
    return db.insert(DATABASE_TABLE, null, initialValues);
}
//---retrieves all the ttrain---
public Cursor getAllTrains() 
{
    return db.query(DATABASE_TABLE, new String[] {
            KEY_ID,
            KEY_Code,
            KEY_Station,
            KEY_Platform,
            KEY_TimeTillStation,
            KEY_TrainDestination},
            null, 
            null, 
            null, 
            null, 
            null,
            null);
}
//---retrieves a particular train---
public Cursor getTrain(long id) throws SQLException 
{
    Cursor mCursor =
            db.query(true, DATABASE_TABLE, new String[] {
            KEY_ID,
            KEY_Code, 
            KEY_Station,
            KEY_Platform,
            KEY_TimeTillStation,
            KEY_TrainDestination}, 
        KEY_ID + "=" + id, 
        null,
        null, 
        null, 
        null, 
        null);
    if (mCursor != null) {
        mCursor.moveToFirst();
    }
    return mCursor;
}
//---updates a train---
public boolean updateTrain(long id, String code, String station, String platform, String timetillstation, String traindestination) 
{
    ContentValues args = new ContentValues();
    args.put(KEY_Code, code);
    args.put(KEY_Station, station);
    args.put(KEY_Platform, platform);
    args.put(KEY_TimeTillStation, timetillstation);
    args.put(KEY_TrainDestination, traindestination);
    return db.update(DATABASE_TABLE, args, 
                     KEY_ID + "=" + id, null) > 0;
}
}

I am not sure where to go from here as there are still issues. The log cat displays the following:

12-04 12:43:09.691: E/AndroidRuntime(21334): FATAL EXCEPTION: main
12-04 12:43:09.691: E/AndroidRuntime(21334): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{ta.dabase/ta.dabase.DatabaseActivity}: java.lang.NullPointerException
12-04 12:43:09.691: E/AndroidRuntime(21334):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1680)
12-04 12:43:09.691: E/AndroidRuntime(21334):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1784)
12-04 12:43:09.691: E/AndroidRuntime(21334):    at android.app.ActivityThread.access$1500(ActivityThread.java:123)
12-04 12:43:09.691: E/AndroidRuntime(21334):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:939)
12-04 12:43:09.691: E/AndroidRuntime(21334):    at android.os.Handler.dispatchMessage(Handler.java:99)
12-04 12:43:09.691: E/AndroidRuntime(21334):    at android.os.Looper.loop(Looper.java:130)
12-04 12:43:09.691: E/AndroidRuntime(21334):    at android.app.ActivityThread.main(ActivityThread.java:3835)
12-04 12:43:09.691: E/AndroidRuntime(21334):    at java.lang.reflect.Method.invokeNative(Native Method)
12-04 12:43:09.691: E/AndroidRuntime(21334):    at java.lang.reflect.Method.invoke(Method.java:507)
12-04 12:43:09.691: E/AndroidRuntime(21334):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:847)
12-04 12:43:09.691: E/AndroidRuntime(21334):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:605)
12-04 12:43:09.691: E/AndroidRuntime(21334):    at dalvik.system.NativeStart.main(Native Method)
12-04 12:43:09.691: E/AndroidRuntime(21334): Caused by: java.lang.NullPointerException
12-04 12:43:09.691: E/AndroidRuntime(21334):    at android.content.ContextWrapper.openOrCreateDatabase(ContextWrapper.java:203)
12-04 12:43:09.691: E/AndroidRuntime(21334):    at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:118)
12-04 12:43:09.691: E/AndroidRuntime(21334):    at ta.dabase.DBAdapter.<init>(DBAdapter.java:43)
12-04 12:43:09.691: E/AndroidRuntime(21334):    at ta.dabase.DatabaseActivity.<init>(DatabaseActivity.java:32)
12-04 12:43:09.691: E/AndroidRuntime(21334):    at java.lang.Class.newInstanceImpl(Native Method)
12-04 12:43:09.691: E/AndroidRuntime(21334):    at java.lang.Class.newInstance(Class.java:1409)
12-04 12:43:09.691: E/AndroidRuntime(21334):    at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
12-04 12:43:09.691: E/AndroidRuntime(21334):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1672)
12-04 12:43:09.691: E/AndroidRuntime(21334):    ... 11 more

Finally, I was wondering if anyone could help me with debugging in a sense what and where to place appropriate logging code so to detect where code is going wrong exactly?
Thanks

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-29T15:13:14+00:00Added an answer on May 29, 2026 at 3:13 pm

    To solve this problem you must follow this steps

    1) Create the class which contains properties as per your json data.

    2) Deserialize your json data into your class. ( Mapping of json with class)

    3) Store the values of all properties in that class into database(sqllite) (Mapping of class with database )

    4) ****Save your work*** !

    Done ! Enjoy Jsoning !!

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Im having issues getting this to work, maybe its not even possible? I have
I am trying to get facebook wall but I am having issues with JSON
I've been having some issues trying to use cURL and JSON to print out
I am having issues with trying to convert an UTF-8 string to unicode. I
I am having some issues trying to convert a double to C++ string. Here
Having issues referencing $(this) from within a the nested ajax 'success' function... I know
Still having issues with this problem. Please help if you can. So I am
I am having issues serializing correct JSON for date fields in gwt. In gwt,
I'm having issues with the following code, where I use a JComboBox to change
I am having some issues DeSerializing the following Json, it runs, throws no errors

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.