My connection and fetching from the server is successful using php code below
<?php
define('DB_USER', "root"); // db user
define('DB_PASSWORD', ""); // db password (mention your db password here)
define('DB_DATABASE', "Test"); // database name
define('DB_SERVER', "localhost"); // db server
// array for JSON response
$response = array();
class DB_CONNECT {
// constructor
function __construct() {
// connecting to database
$this->connect();
}
// destructor
function __destruct() {
// closing db connection
$this->close();
}
/**
* Function to connect with database
*/
function connect() {
// import database connection variables
// require_once __DIR__ . '/db_config.php';
// Connecting to mysql database
$con = mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die(mysql_error());
// Selecing database
$db = mysql_select_db(DB_DATABASE) or die(mysql_error()) or die(mysql_error());
// returing connection cursor
return $con;
}
/**
* Function to close db connection
*/
function close() {
// closing db connection
mysql_close();
}
}
// connecting to db
$db = new DB_CONNECT();
// get all test from BF table
$result = mysql_query("SELECT *FROM BF") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) {
// looping through all results
// Airnet node
$response["BF"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$product = array();
$product["C"] = $row["C"];
$product["B"] = $row["B"];
$product["I"] = $row["I"];
$product["It"] = $row["It"];
$product["CurDate"] = $row["CurDate"];
$product["Value"] = $row["Value"];
// push single product into final response array
array_push($response["BF"], $product);
}
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "No Test Database Found";
// echo no users JSON
echo json_encode($response);
}
?>
On the DBHelper i have
package com.s.t.android;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.content.BroadcastReceiver;
import android.app.Activity;
//class database helper
public class DBHelper extends SQLiteOpenHelper{
public SQLiteDatabase DB;
public String DBPath;
public static String DBName = "Test";
public static final int version = '2';
public static Context currentContext;
public static String tableName = "BF";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
//private static final String TAG_ID = "Id";
private static final String TAG_C = "C";
private static final String TAG_B = "B";
private static final String TAG_I = "I";
private static final String TAG_IT = "It";
private static final String TAG_CUR_DATE = "Cur_Date";
private static final String TAG_VALUE = "Value";
//String id;
String c;
String b;
String i;
String it;
String cur_date;
String value;
// products JSONArray
JSONArray products = null;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
private static String url_all_products = "http://192.168.0.5/android_connect/fetchdata.php";
public DBHelper(Context context) {
super(context, DBName, null, version);
currentContext = context;
DBPath = "/data/data/" + context.getPackageName() + "/databases/";
createDatabase();
//new WIFIStatistics();
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
private void createDatabase() {
boolean DbExists = checkDbExists();
if (DbExists) {
}
else {
DB = currentContext.openOrCreateDatabase(DBName, 0, null);
DB.execSQL("CREATE TABLE IF NOT EXISTS " +
tableName +
" (C TEXT, B TEXT, I TEXT, It TEXT, " +
"Cur_Date DATE, Value DOUBLE);");
updateDB();
}
}
private boolean checkDbExists() {
SQLiteDatabase checkDB = null;
try {
if(countRows() == 10043){
String myPath = DBPath + DBName;
checkDB = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);
}
}
catch (SQLiteException e) {
// database does't exist yet.
e.printStackTrace();
}
/*catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}
/**
* getting All Data from url
* */
protected String updateDB(String... args) {
new WIFIStatistics();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
//id = c.getString(TAG_ID);
c = c.getString(TAG_C);
b = c.getString(TAG_B);
i = c.getString(TAG_I);
it = c.getString(TAG_IT);
cur_date = c.getString(TAG_CUR_DATE);
value = c.getString(TAG_VALUE);
String myPath = DBPath + DBName;
SQLiteDatabase myDB = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);
myDB.execSQL("INSERT INTO " +
tableName +
" VALUES ('"+c+"','"+b+"','"+i+"','"+it+"','"+cur_date+"','"+value+"');");
}
} else {
// no products found
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
public double countRows(){
double rows = 0;
String myPath = DBPath + DBName;
SQLiteDatabase myDB = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);
Cursor count = myDB.rawQuery("SELECT * FROM BF", null);
rows += count.getCount();
return rows;
}
public String checkDate(){
String maxDate = "0000-00-00";
String myPath = DBPath + DBName;
SQLiteDatabase myDB = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);
Cursor c = myDB.rawQuery("SELECT MAX(Cur_Date) FROM BF Limit 1", null);
maxDate = c.getString(0);
return maxDate;
}
/*
public void copyDataBase() throws IOException{
//Open your local db as the input stream
InputStream myInput = currentContext.getAssets().open("Airnet");
// Path to the just created empty db
String outFileName = DBPath + DBName;
//Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
//transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[10240];
int length;
while ((length = myInput.read(buffer))>0){
myOutput.write(buffer, 0, length);
}
//Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
*/
class WIFIStatistics extends Activity{
WifiManager wifi;
public Device device;
public TChart chart;
Dialog dialog;
TextView description;
Button okButton, scanButton, cancelButton;
BroadcastReceiver receiver;
@SuppressWarnings("static-access")
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
while (wifi.getWifiState() == wifi.WIFI_STATE_ENABLING) {
}
if (wifi.isWifiEnabled()) {
}
else {
dialog = new Dialog(WIFIStatistics.this);
dialog.setContentView(R.layout.acceptcancel);
dialog.show();
dialog.setTitle("Wifi not enabled");
description = (TextView) dialog.findViewById(R.id.descriptionText1);
description
.setText("Wifi is not enabled\nWould you like to enable WiFi? OK/CANCEL");
description.setTextColor(0xFFFFFFFF);
okButton = (Button) dialog.findViewById(R.id.okButton);
okButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
wifi.setWifiEnabled(true);
dialog.cancel();
Intent myIntent = new Intent(v.getContext(),
DBHelper.class);
startActivityForResult(myIntent, 0);
finish();
}
});
cancelButton = (Button) dialog.findViewById(R.id.buttonCancel);
cancelButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dialog.cancel();
finish();
}
});
}
}
}
}
I understand that i should use ASYNCTASK but am not sure how i will implement that class or if their is any other simpler way i can load my data into sqlite database from mysql keeping in mind that the data is consists of 10 tables and each table has 30000 rows. the above code i was just testing one table. Thanks for your help
this eror comes With HoneyComb(3.0 or Later).
you can not perform a networking operation on its main thread as documentation says. to getting ride of this you must use handler or asynctask. AFAIK There is no another way to do it.
you can See this for More Details WHY ICS Crashes your App
Try Using Below Code Snippet