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 6877983
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T04:40:02+00:00 2026-05-27T04:40:02+00:00

I am trying to writing code so that my android application can query a

  • 0

I am trying to writing code so that my android application can query a MySQL database and then retrieve the data in JSON which it then parses. I would then like to take the data and insert it into the application’s local database on SQLite. I would like this data to be updated at a set frequency as well.

This is the JSON array and HTTP Get protocol activity.

package com.connector;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.LinearLayout;
import android.widget.TextView;


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

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_121)); 



}
public static final String KEY_121 = "http://xx.xx.xxx.xxx/hellomysql/mysqlcon.php"; //i use my real ip here



private String getServerData(String returnString) {

InputStream is = null;

String result = "";
//the year data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("publisher","Penguin Books UK"));

//http post
try{
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(KEY_121);
        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);
                Log.i("log_tag","id: "+json_data.getInt("id")+
                        ", isbn: "+json_data.getString("isbn")+
                        ", title: "+json_data.getString("title")+
                        ", publisher: "+json_data.getString("publisher")
                );
                //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 following two are the database related activities.

package com.example.database;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DBAdapter {
public static final String KEY_ROWID = "_id";
public static final String KEY_ISBN = "isbn";
public static final String KEY_TITLE = "title";
public static final String KEY_PUBLISHER = "publisher";    
private static final String TAG = "DBAdapter";

private static final String DATABASE_NAME = "books";
private static final String DATABASE_TABLE = "titles";
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_CREATE =
    "create table titles (_id integer primary key autoincrement, "
    + "isbn text not null, title text not null, " 
    + "publisher text not null);";

private final Context context; 

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

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 title into the database---
public long insertTitle(String isbn, String title, String publisher) 
{
    ContentValues initialValues = new ContentValues();
    initialValues.put(KEY_ISBN, isbn);
    initialValues.put(KEY_TITLE, title);
    initialValues.put(KEY_PUBLISHER, publisher);
    return db.insert(DATABASE_TABLE, null, initialValues);
}
//---deletes a particular title---
public boolean deleteTitle(long rowId) 
{
    return db.delete(DATABASE_TABLE, KEY_ROWID + 
     "=" + rowId, null) > 0;
}
//---retrieves all the titles---
public Cursor getAllTitles() 
{
    return db.query(DATABASE_TABLE, new String[] {
            KEY_ROWID,
            KEY_ISBN,
            KEY_TITLE,
            KEY_PUBLISHER}, 
            null, 
            null, 
            null, 
            null, 
            null);
}
//---retrieves a particular title---
public Cursor getTitle(long rowId) throws SQLException 
{
    Cursor mCursor =
            db.query(true, DATABASE_TABLE, new String[] {
             KEY_ROWID,
            KEY_ISBN, 
            KEY_TITLE,
            KEY_PUBLISHER
            }, 
        KEY_ROWID + "=" + rowId, 
        null,
        null, 
        null, 
        null, 
        null);
    if (mCursor != null) {
        mCursor.moveToFirst();
    }
    return mCursor;
}
//---updates a title---
public boolean updateTitle(long rowId, String isbn, 
String title, String publisher) 
{
    ContentValues args = new ContentValues();
    args.put(KEY_ISBN, isbn);
    args.put(KEY_TITLE, title);
    args.put(KEY_PUBLISHER, publisher);
    return db.update(DATABASE_TABLE, args, 
                     KEY_ROWID + "=" + rowId, null) > 0;
}
}

The second one is:

public class DatabaseActivity extends Activity {
DBAdapter db;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    db = new DBAdapter(this); 
    System.out.println("bool1");
    insert();
disAll();
    //update();
    //dis(3);
    //del(5);
}
private void update(){ 

    db.open();
if (db.updateTitle(1, 
     "0470285818", 
"C# 2008 Programmer's Reference",
"Wrox Press"))
        Toast.makeText(this, "Update successful.", 
            Toast.LENGTH_LONG).show();
    else
        Toast.makeText(this, "Update failed.", 
            Toast.LENGTH_LONG).show();
    //-------------------
    //---retrieve the same title to verify---
    Cursor c = db.getTitle(1);
    if (c.moveToFirst())        
        DisplayTitle(c);
    else
        Toast.makeText(this, "No title found", 
         Toast.LENGTH_LONG).show();        
    //-------------------        
db.close();

}
private void insert(){ 

    db.open();        
    long id;
    id = db.insertTitle(
     "0470285819",
    "Teach yourself Java",
    "Wrox");        
    id = db.insertTitle(
    "047017661y",
    "Professional Windows 07 Gadgets Programming",
    "Wrox");
    System.out.println("bool211");
    db.close();
}
private void disAll(){

    db.open();
/*Cursor c = db.getAllTitles();
    if (c.moveToFirst())
    {
        do {          
         System.out.println("bool2");
            DisplayTitle(c);
        } while (c.moveToNext());
    }
    else
     System.out.println("boo3l");*/
    try{
Cursor c = db.getAllTitles();
        if (c.moveToFirst())
        {
            do {          
System.out.println("bool2");
                DisplayTitle(c);
            } while (c.moveToNext());
        }
    }catch(Exception e){
     System.out.println(e);
    }
    db.close();
}

private void   dis(   int   j){

    db.open();
    Cursor c = db.getTitle(j);
    if (c.moveToFirst())        
        DisplayTitle(c);
    else
        Toast.makeText(this, "No title found", 
         Toast.LENGTH_LONG).show();
    db.close();
}        

 private void   del(   int   j){

    db.open();
    if (db.deleteTitle(j))
        Toast.makeText(this, "Delete successful.", 
            Toast.LENGTH_LONG).show();
    else
        Toast.makeText(this, "Delete failed.", 
            Toast.LENGTH_LONG).show();            
    db.close();        
}
public void DisplayTitle(Cursor c)
{
 System.out.println("bool");
    Toast.makeText(this, 
            "id: " + c.getString(0) + "\n" +
            "ISBN: " + c.getString(1) + "\n" +
            "TITLE: " + c.getString(2) + "\n" +
            "PUBLISHER:  " + c.getString(3),
            Toast.LENGTH_LONG).show();        
} 
}

If anyone is able to help it would be much appreciated.

  • 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-27T04:40:03+00:00Added an answer on May 27, 2026 at 4:40 am

    your getServerData method will return a JSONString. In your getServerData method u have a Log Statement, which is actually parsing the JSONObject. Instead of logging it u can call the insertTitle in the dbAdapter class.

    To make this work u have to do some changes. Ur DBAdapter constructor should look like this

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

    Ur create statement should look like this. U r getting the id from the server. So there is no point having the id as auto increment.

    private static final String DATABASE_CREATE =
        "create table titles (_id integer primary key , "
        + "isbn text not null, title text not null, " 
        + "publisher text not null);";
    

    Ur insertTitle should be like this. Similarly change ur update and other methods.

    public long insertTitle(String _id,String isbn, String title, String publisher) 
    {
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_ID, _id);
        initialValues.put(KEY_ISBN, isbn);
        initialValues.put(KEY_TITLE, title);
        initialValues.put(KEY_PUBLISHER, publisher);
        return db.insert(DATABASE_TABLE, null, initialValues);
    }
    

    But make sure u create the dbAdapter object outside the for loop. Hope this will help

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

Sidebar

Related Questions

I'm trying to code a native android application that takes certain parts of a
I'm writing some code in python and I'm having trouble when trying to retrieve
I'm writing code that evaluates .NET Expression trees. I'm trying to create a C#
I am writing an application where the user inputs song information that will then
I've got a java code that is writing a Linux bash script out, then
I'm writing an Android application that allows a user to maintain a list of
I writing an application that draws in openGL es 1.0 in the Android NDK
I'm writing an Android application that would like to verify that a string produced
I am writing an HTML5 application that is gathering data from a few different
I'm trying to send a JSON string, from an Android 2.3 application, using Java

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.