2017-09-02 90 views
-1

我从另一篇文章中看到了下面的代码并使用它。如何从android到PHP获取JSON数组

此代码获取我的Android SQLite数据库中的所有行并将其转换为JSON数组。我想用PHP将JSON数组存储到我的在线数据库中。

我该怎么办?

这是我使用的代码:

private JSONArray getResults() 
{ 

    String myPath = this.getDatabasePath("cart.db").toString();// Set path to your database 

    String myTable = CartContract.CartEntry.TABLE_NAME;//Set name of your table 

    SQLiteDatabase myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY); 

    String searchQuery = "SELECT * FROM " + myTable; 
    Cursor cursor = myDataBase.rawQuery(searchQuery, null); 

    JSONArray resultSet  = new JSONArray(); 

    cursor.moveToFirst(); 
    while (cursor.isAfterLast() == false) { 

     int totalColumn = cursor.getColumnCount(); 
     JSONObject rowObject = new JSONObject(); 

     for(int i=0 ; i< totalColumn ; i++) 
     { 
      if(cursor.getColumnName(i) != null) 
      { 
       try 
       { 
        if(cursor.getString(i) != null) 
        { 
         Log.d("TAG_NAME", cursor.getString(i)); 
         rowObject.put(cursor.getColumnName(i) , cursor.getString(i)); 
        } 
        else 
        { 
         rowObject.put(cursor.getColumnName(i) , ""); 
        } 
       } 
       catch(Exception e) 
       { 
        Log.d("TAG_NAME", e.getMessage() ); 
       } 
      } 
     } 
     resultSet.put(rowObject); 
     cursor.moveToNext(); 
    } 
    cursor.close(); 
    Log.d("FINAL RESULT", resultSet.toString()); 
    return resultSet; 
} 

这是输出:

FINAL RESULT: [{"id":"1","food_id":"52","food_price":"30","food_name":"Pink Lemonade","quantity":"5","amount":"150","special_request":""},{"id":"2","food_id":"51","food_price":"30","food_name":"House Blend Iced Tea","quantity":"3","amount":"90","special_request":""}] 

更新:我使用了一些@克里斯托弗 - 罗宾法伊Feysenbe代码和它的工作!非常感谢你

+2

通过POST向服务器发送像这样的数据是有意义的。 PHP脚本可以接受数据并通过[_POST](http://php.net/manual/de/reserved.variables.post.php)变量获取。 在Android方面,您可以使用像[Retrofit](http://square.github.io/retrofit/)这样的http库来发送数据。 –

+0

使用Okhttp ...等有更多的库进行HTTP调用.... –

+0

这只是一个字符串...你有没有尝试发送任何数据到PHP呢? –

回答

0

你可能想用这个。

package com.your.app.name; 

import android.content.Context; 
import android.util.Log; 
import android.widget.Toast; 

import com.android.volley.NetworkError; 
import com.android.volley.Request; 
import com.android.volley.RequestQueue; 
import com.android.volley.Response; 
import com.android.volley.TimeoutError; 
import com.android.volley.VolleyError; 
import com.android.volley.toolbox.StringRequest; 
import com.android.volley.toolbox.Volley; 

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

import java.util.Iterator; 
import java.util.Map; 


/** 
* Helper Class to handle Network Requests 
* with Volley 
*/ 
public class Network { 
    private static Network network; 
    private RequestQueue mRequestQueue; 
    private static Context mCtx; 
    public final String TAG = "Network Helper"; 

    /** 
    * Constructor 
    */ 
    private Network(Context c) { 
     mCtx = c; 
     mRequestQueue = getRequestQueue(); 
    } 


    public interface INetworkCallback { 
     void NetworkSuccess(String response); 

     void NetworkError(String error); 

    } 

    public static synchronized Network getInstance(Context c) { 
     if (network == null) { 
      network = new Network(c); 
     } 
     return network; 
    } 

    public RequestQueue getRequestQueue() { 
     if (mRequestQueue == null) { 
      mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext()); 
     } 
     return mRequestQueue; 
    } 

    /** 
    * Perform a POST Request to a specified url; 
    * 
    * @param host 
    * @param url 
    * @param params 
    * @param callback new INetworkCallback() 
    */ 
    public void postRequest(final String host, final String url, final Map params, final INetworkCallback callback) { 

     try { 

      StringRequest postRequest = new StringRequest(Request.Method.POST, (host + url), 
        new Response.Listener<String>() { 
         @Override 
         public void onResponse(String response) { 
          Log.v(TAG, response); 
          //make successCallback 
          callback.NetworkSuccess(response); 
         } 
        }, new Response.ErrorListener() { 
       @Override 
       public void onErrorResponse(VolleyError error) { 
        if (error instanceof NetworkError) { 
         //no response from compound URL 
         callback.NetworkError(error.toString()); 
         Toast.makeText(mCtx, "No internet connection", Toast.LENGTH_LONG).show(); 
        } else if (error.networkResponse != null && error.networkResponse.statusCode == 500 || 
          error.networkResponse != null && error.networkResponse.statusCode == 301) { 
         //Show errorMessage and log Error 
         callback.NetworkError(error.networkResponse.headers.get("message")); 
         String mess = error.networkResponse.headers.get("message"); 
         if (mess != null && !mess.isEmpty()) { 
          Toast.makeText(mCtx, error.networkResponse.headers.get("message"), Toast.LENGTH_LONG).show(); 
         } 
        } else { 
         //some unexpected Error occurred 
         callback.NetworkError("Network Error: " + error.toString()); 
        } 
       } 
      }) { 
       @Override 
       protected Map<String, String> getParams() { 
        return params; 
       } 
      }; 


      //add request to queue 
      addToRequestQueue(postRequest); 

     } catch (Exception e) { 
      callback.NetworkError("Error performing Request: - " + e.toString()); 
     } 
    } 

    public void getRequest(final String host, final String url, final Map params, final INetworkCallback callback) { 
     String paramsString = makeGetURL(params); 
     Log.v(TAG, "======= " + paramsString + " ======="); 
     try { 

      StringRequest getRequest = new StringRequest(Request.Method.GET, (host + url + paramsString), 
        new Response.Listener<String>() { 

         @Override 
         public void onResponse(String response) { 
          Log.v(TAG, response); 

          //make successCallback 
          callback.NetworkSuccess(response); 
         } 
        }, new Response.ErrorListener() { 
       @Override 
       public void onErrorResponse(VolleyError error) { 
        if (error instanceof NetworkError) { 
         //no response from compound URL 
         callback.NetworkError(error.toString()); 
         Toast.makeText(mCtx, "No internet connection", Toast.LENGTH_LONG).show(); 
        } else if (error instanceof TimeoutError) { 
         //no response from compound URL 
         callback.NetworkError(error.toString()); 
         Toast.makeText(mCtx, "No server connection", Toast.LENGTH_LONG).show(); 
        } else if (error.networkResponse != null && error.networkResponse.statusCode == 500) { 
         //Show errorMessage and log Error 
         callback.NetworkError(error.networkResponse.headers.get("message")); 
         String mess = error.networkResponse.headers.get("message"); 
         if (mess != null && !mess.isEmpty()) { 
          Toast.makeText(mCtx, error.networkResponse.headers.get("message"), Toast.LENGTH_LONG).show(); 
         } 
        } else { 
         //some unexpected Error occurred 
         callback.NetworkError("NetworkError: " + error.toString()); 
        } 
       } 
      }); 

      //add request to queue 
      addToRequestQueue(getRequest); 
     } catch (Exception e) { 
      callback.NetworkError("Error performing request: " + e.toString()); 
     } 
    } 

    /** 
    * Iterates over all Set entries of HashMap and 
    * generates a GET URL Link base on the key, value pairs 
    * 
    * @param params 
    * @return 
    */ 
    private String makeGetURL(Map params) { 
     String qm; 
     String url = ""; 

     if (params != null) { 
      qm = (params.size() > 0) ? "?" : ""; 

      //add ? if there ara parameters 
      url += qm; 

      Iterator it = params.entrySet().iterator(); 
      while (it.hasNext()) { 
       Map.Entry param = (Map.Entry) it.next(); 
       url += param.getKey() + "=" + param.getValue() + "&"; 
      } 

      //erase last char 
      try { 
       url = url.substring(0, url.length() - 1); 
      } catch (Exception e) { 
       //IF FAILS it means no parameters have been putted 
       Log.i(TAG, "no parameters found for get request"); 
      } 
     } 

     return url; 
    } 

    public <T> void addToRequestQueue(Request<T> req) { 
     getRequestQueue().add(req); 
    } 
} 

您可以使用我编写的代码来处理帖子并使用Volley获取请求。如何配置排球可以取消here。只需使用名称Network创建一个新的Java Class并复制粘贴代码即可。

为了使POST请求只是这样做:

import android.database.Cursor; 
import android.database.sqlite.SQLiteDatabase; 
import android.support.v7.app.AppCompatActivity; 
import android.util.Log; 
import org.json.JSONArray; 
import org.json.JSONObject; 

import java.util.HashMap; 


public class Test extends AppCompatActivity { 

    private JSONArray getResults() 
    { 

     String myPath = this.getDatabasePath("cart.db").toString();// Set path to your database 

     String myTable = CartContract.CartEntry.TABLE_NAME;//Set name of your table 

     SQLiteDatabase myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY); 

     String searchQuery = "SELECT * FROM " + myTable; 
     Cursor cursor = myDataBase.rawQuery(searchQuery, null); 

     JSONArray resultSet  = new JSONArray(); 

     cursor.moveToFirst(); 
     while (cursor.isAfterLast() == false) { 

      int totalColumn = cursor.getColumnCount(); 
      JSONObject rowObject = new JSONObject(); 

      for(int i=0 ; i< totalColumn ; i++) 
      { 
       if(cursor.getColumnName(i) != null) 
       { 
        try 
        { 
         if(cursor.getString(i) != null) 
         { 
          Log.d("TAG_NAME", cursor.getString(i)); 
          rowObject.put(cursor.getColumnName(i) , cursor.getString(i)); 
         } 
         else 
         { 
          rowObject.put(cursor.getColumnName(i) , ""); 
         } 
        } 
        catch(Exception e) 
        { 
         Log.d("TAG_NAME", e.getMessage() ); 
        } 
       } 
      } 
      resultSet.put(rowObject); 
      cursor.moveToNext(); 
     } 
     cursor.close(); 
     Log.d("FINAL RESULT", resultSet.toString()); 
     return resultSet; 
    } 

    private void sendResult(String resultJSONString) { 
     //perform post request 
     HashMap<String, String> params = new HashMap<>(); 
     params.put("data", resultJSONString); 

     Network.getInstance(this).postRequest("www.some-adress.com/", "do_stuff.php", params, new Network.INetworkCallback() { 
      @Override 
      public void NetworkSuccess(String response) { 
       // 
       Log.i("RECEIVED RESPONSE", response); 
      } 

      @Override 
      public void NetworkError(String error) { 
       // 
       Log.e("ERROR SENDING DATA", error); 
      } 
     }); 


    } 


    public void sendData(String value) { 
     this.sendResult(getResults().toString()); 
    } 

} 

那么你的服务器或本地testsystem上,你可以收到这样

do_stuff.php

<?php 
//include my example script db.php 
include_once(dirname(__DIR__) . "/Server/DB/DB.php"); 


$json = '[{"id":"1","food_id":"52","food_price":"30","food_name":"Pink Lemonade","quantity":"5","amount":"150","special_request":""},{"id":"2","food_id":"51","food_price":"30","food_name":"House Blend Iced Tea","quantity":"3","amount":"90","special_request":""}]'; 
//decode JSON data 
$data = json_decode($json, TRUE); 

var_dump($data); 

$multiQuery = ""; 

foreach ($data as $item) { 

    $foodId = $item['food_id']; 
    $foodPrice = $item['food_price']; 
    $foodName = $item['food_name']; 
    $quantity = $item['quantity']; 
    $amount = $item['amount']; 
    $specialRequest = $item['special_request']; 

    $insertQuery = "INSERT INTO your_table_name (food_id, food_price, food_name, quantity, amount, special_request) VALUES ($foodId, $foodPrice, $foodName, $quantity, $amount, $specialRequest);"; 

    $multiQuery .= $insertQuery; 
} 

$db = new DB(); 

if($db->multiQuery($multiQuery)) { 
    //data was saved 
} else { 
    $db->getErrorMessage(); 
} 

?> 

数据PHP的数据库类 - db.php

<?php 



/** 
* Class DB 
* 
* Handles database access and Errors 
*/ 
class DB 
{ 

    private $host = "localhost"; 
    private $user = "root"; 
    private $pw = ""; 
    private $dbName = "yourDbNameHere"; 
    private $con; 

    /** 
    * Class constructor Method 
    */ 
    public function __construct() 
    { 
     $this->connect($this->host, $this->user, $this->pw, $this->dbName); 
     header('Content-Type: text/html; charset=utf-8'); 
    } 

    /** 
    * Makes Database connection an 
    * 
    * @param $host 
    * @param $user 
    * @param $pw 
    * @param $dbName 
    */ 
    public function connect($host, $user, $pw, $dbName) 
    { 
     $this->con = mysqli_connect($host, $user, $pw, $dbName); 
     if($this->con != null) { 
      $this->con->set_charset('utf8'); 
     } else { 
      $this->dbError("Keine Verbindung zur Datenbank"); 
     } 
    } 

    public function escapeQuery($query) 
    { 
     $result = null; 
     if (!empty($query)) { 
      return mysqli_real_escape_string($this->con, $query); 
     } else { 
      return false; 
     } 
    } 

    /** 
    * Performs a query against the database and returns the mysqli_result 
    * 
    * @param $query 
    * @return bool|mysqli_result 
    */ 
    public function query($query) 
    { 
     $result = null; 
     if (!empty($query)) { 
      return mysqli_query($this->con, $query); 
     } else { 
      $this->dbError("empty query String"); 
      return false; 
     } 
    } 


    /** 
    * 
    * 
    * @param $query 
    * @return array|bool 
    */ 
    public function multiQuery($query) 
    { 
     $result = null; 
     if (!empty($query)) { 
      $data = array(); 

      if (mysqli_multi_query($this->con, $query)) { 
       do { 
        // Store first result set 
        if ($result = mysqli_store_result($this->con)) { 
         // Fetch one and one row 
         while ($row = mysqli_fetch_assoc($result)) { 
          $data[] = $row; 
         } 
         // Free result set 
         mysqli_free_result($result); 
        } 
       } while (mysqli_next_result($this->con)); 
      } 

      if(mysqli_error($this->con)) { 
       $error = mysqli_error_list($this->con); 
       return false; 
      } else { 
       if(count($data) > 0) { 
        return $data; 
       } else { 
        return true; 
       } 
      } 
     } else { 
      $this->dbError("empty query String"); 
      return false; 
     } 
    } 

    /** 
    * Performs q query against the database and returns JSON object 
    * 
    * @param $query 
    * @return bool 
    */ 
    public function queryArray($query) 
    { 
     $result = null; 
     if (!empty($query)) { 
      $result = mysqli_query($this->con, $query); 

      $data = array(); 
      if (!empty($result)) { 
       while ($row = $result->fetch_assoc()) { 
        $data[] = $row; 
       } 
       return ($data); 
      } else { 
       $this->dbError(mysqli_error($this->con)); 
       return false; 
      } 
     } else { 
      $this->dbError("empty query String"); 
      return false; 
     } 

    } 


    /** 
    * Throws error and custom error message if passed as parameter 
    * 
    * @param $message 
    */ 
    public function dbError($message) 
    { 
     Response::sendError($message); 
    } 


    /** 
    * Returns the mysqli_error message if error occurred 
    * 
    * @return string 
    */ 
    public function getErrorMessage() 
    { 
     return mysqli_error($this->con); 
    } 


    /** 
    * Checks if error message contains Duplicate Entry Error 
    * 
    * @return bool 
    */ 
    public function IsDuplicateEntry() 
    { 
     if (strpos($this->getErrorMessage(), "Duplicate") !== false) { 
      return true; 
     } else { 
      false; 
     } 
    } 

}