Php android中的android.os.networkonmainthreadexception在尝试将数据从mysql服务器提取到sqlite时发生异常

Php android中的android.os.networkonmainthreadexception在尝试将数据从mysql服务器提取到sqlite时发生异常,php,android,mysql,sqlite,Php,Android,Mysql,Sqlite,使用下面的php代码,我的连接和从服务器获取成功 <?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");

使用下面的php代码,我的连接和从服务器获取成功

     <?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);
 }
?>

在我的DBHelper上

  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();
            }

        });

    }
}
}

 }
package com.s.t.android;
导入java.io.FileOutputStream;
导入java.io.IOException;
导入java.io.InputStream;
导入java.io.OutputStream;
导入java.util.ArrayList;
导入java.util.HashMap;
导入java.util.List;
导入org.apache.http.NameValuePair;
导入org.json.JSONArray;
导入org.json.JSONException;
导入org.json.JSONObject;
导入android.app.Dialog;
导入android.app.ProgressDialog;
导入android.content.Context;
导入android.content.Intent;
导入android.database.Cursor;
导入android.database.SQLException;
导入android.database.sqlite.SQLiteDatabase;
导入android.database.sqlite.SQLiteException;
导入android.database.sqlite.SQLiteOpenHelper;
导入android.net.wifi.WifiManager;
导入android.os.AsyncTask;
导入android.os.Bundle;
导入android.util.Log;
导入android.view.view;
导入android.view.view.OnClickListener;
导入android.widget.Button;
导入android.widget.TextView;
导入android.content.BroadcastReceiver;
导入android.app.Activity;
//类数据库帮助器
公共类DBHelper扩展了SQLiteOpenHelper{
公共数据库数据库;
公共字符串路径;
公共静态字符串DBName=“Test”;
公共静态最终int版本='2';
公共静态语境;
公共静态字符串tableName=“BF”;
//JSON节点名称
私有静态最终字符串标记_SUCCESS=“SUCCESS”;
私有静态最终字符串TAG_PRODUCTS=“PRODUCTS”;
//私有静态最终字符串标记\u ID=“ID”;
私有静态最终字符串标记_C=“C”;
私有静态最终字符串标记_B=“B”;
私有静态最终字符串标记_I=“I”;
私有静态最终字符串标记_IT=“IT”;
私有静态最终字符串标记\u CUR\u DATE=“CUR\u DATE”;
私有静态最终字符串标记_VALUE=“VALUE”;
//字符串id;
字符串c;
b串;
第i串;
把它串起来;
字符串当前日期;
字符串值;
//产品JSONArray
JSONArray产品=null;
//创建JSON解析器对象
JSONParser jParser=新的JSONParser();
ArrayList productsList;
//获取所有产品列表的url
私有静态字符串url\u所有产品=”http://192.168.0.5/android_connect/fetchdata.php";
公共DBHelper(上下文){
super(上下文、数据库名、null、版本);
currentContext=上下文;
DBPath=“/data/data/”+context.getPackageName()+”/databases/”;
createDatabase();
//新金融统计学();
}
@凌驾
public void onCreate(SQLiteDatabase db){
//TODO自动生成的方法存根
}
@凌驾
public void onUpgrade(SQLiteDatabase db,int-oldVersion,int-newVersion){
//TODO自动生成的方法存根
}
私有void createDatabase(){
布尔值DbExists=checkDbExists();
if(DbExists){
}
否则{
DB=currentContext.openOrCreateDatabase(DBName,0,null);
DB.execSQL(“如果不存在,则创建表”+
表名+
(C文本、B文本、I文本、It文本、+
“Cur_Date,Value DOUBLE);”;
updateDB();
}
}
私有布尔checkDbExists(){
SQLiteDatabase checkDB=null;
试一试{
如果(countRows()==10043){
字符串myPath=DBPath+DBName;
checkDB=SQLiteDatabase.openDatabase(myPath,null,
SQLiteDatabase.OPEN_READONLY);
}
}
catch(sqlitee异常){
//数据库还不存在。
e、 printStackTrace();
} 
/*捕获(IOE异常){
//TODO自动生成的捕捉块
e、 printStackTrace();
}*/
if(checkDB!=null){
checkDB.close();
}
return checkDB!=null?true:false;
}
/**
*从url获取所有数据
* */
受保护的字符串已更新(字符串…参数){
新金融统计学();
//建筑参数
List params=new ArrayList();
//从URL获取JSON字符串
JSONObject json=jParser.makeHttpRequest(url_all_products,“GET”,params);
//检查日志cat中的JSON响应
Log.d(“所有产品:,json.toString());
试一试{
//检查成功标签
int success=json.getInt(TAG_success);
如果(成功==1){
//发现的产品
//获取一系列产品
products=json.getJSONArray(TAG_products);
//在所有产品中循环
对于(int i=0;i android.os.NetworkOnMainThreadException
new Thread(){
    public void run(){
        //do your Code Here    
    }
}.start();