A. 如何使用JSON連接android和php Mysql資料庫
1. 什麼是WAMP Server WAMP是Windows,Apache,MySQL和PHP,Perl,Python的簡稱。WAMP是一個一鍵安裝的軟體,它為開發PHP,MySQL Web應用程序提供一個環境。安裝這款軟體你相當於安裝了Apache,MySQL和PHP。或者,你也可以使用XAMP。 2. 安裝和使用WAMP Server 你可以從下載WAMP,安裝完成之後,可以從開始->所有程序->WampServer->StartWampServer運行該程序。 在瀏覽器中輸入來測試你的伺服器是否安裝成功。同樣的,也可以打開來檢驗phpmyadmin是否安裝成功。 3. 創建和運行PHP項目 現在,你已經有一個能開發PHP和MYSQL項目的環境了。打開安裝WAMP Server的文件夾(在我的電腦中,是C:\wamp\),打開www文件夾,為你的項目創建一個新的文件夾。你必須把項目中所有的文件放到這個文件夾中。 新建一個名為android_connect的文件夾,並新建一個php文件,命名為test.php,嘗試輸入一些簡單的php代碼(如下所示)。輸入下面的代碼後,打開,你會在瀏覽器中看到「Welcome,I am connecting Android to PHP,MySQL」(如果沒有正確輸入,請檢查WAMP配置是否正確) test.php <?php echo"Welcome, I am connecting Android to PHP, MySQL"; ?>4. 創建MySQL資料庫和表 在本教程中,我創建了一個簡單的只有一張表的資料庫。我會用這個表來執行一些示例操作。現在,請在瀏覽器中輸入,並打開phpmyadmin。你可以用PhpMyAdmin工具創建資料庫和表。 創建資料庫和表:資料庫名:androidhive,表:proct CREATE DATABASE androidhive; CREATE TABLE procts( pid int(11) primary key auto_increment, name varchar(100) not null, price decimal(10,2) not null, description text, created_at timestamp defaultnow(), updated_at timestamp );5. 用PHP連接MySQL資料庫 現在,真正的伺服器端編程開始了。新建一個PHP類來連接MYSQL資料庫。這個類的主要功能是打開資料庫連接和在不需要時關閉資料庫連接。 新建兩個文件db_config.php,db_connect.php db_config.php--------存儲資料庫連接變數 db_connect.php-------連接資料庫的類文件 db_config.php 如果你是PHP和MySQL新手,我建議你可以先學習PHP和SQL基礎知識。 6. a)在MYSQL中新建一行(創建一行新的產品) 在你的PHP項目中新建一個php文件,命名為create_proct.php,並輸入以下代碼。該文件主要實現在procts表中插入一個新的產品。
B. android怎麼看json數據格式
JSON有兩種表示結構,對象和數組。
對象結構以」{」大括弧開始,以」}」大括弧結束。中間部分由0或多個以」,」分隔的」key(關鍵字)/value(值)」對構成,關鍵字和值之間以」:」分隔,語法結構如下
{
key1:value1,
key2:value2,
}其中關鍵字是字元串,而值可以是字元串,數值,true,false,null,對象或數組
數組結構以」[」開始,」]」結束。中間由0或多個以」,」分隔的值列表組成,語法結構如下
[
{
key1:value1,
key2:value2
},
{
key3:value3,
key4:value4
}
]
C. 如何使用JSON連接Android和PHP Mysql資料庫
Android客戶端直接連接遠程MySQL資料庫的方法如下: String result = ""; //首先使用NameValuePair封裝將要查詢的年數和關鍵字綁定 ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs/getAllPeopleBornAfter.php"); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); InputStream is = entity.getContent(); }catch(Exception e){ Log.e("log_tag", "Error in http connection "+e.toString()); } //將HttpEntity轉化為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()); } //將String通過JSONArray解析成最終結果 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")+ ", name: "+json_data.getString("name")+ ", sex: "+json_data.getInt("sex")+ ", birthyear: "+json_data.getInt("birthyear") ); } } }catch(JSONException e){ Log.e("log_tag", "Error parsing data "+e.toString()); } 雖然Android開發中可以直接連接資料庫,但是實際中卻不建議這么做,應該使用伺服器端中轉下完成。
D. android 用JSON 解析數據介面方法
介面獲取下來的數據為
{"status":200,"message":"查詢成功","data":{"id":32,"user_id":null,"user_code":null,"user_pass":null,"meeting_id":"1","meeting_pass":null,"config_param_ip":"11.1.1.70","port":"6501","web_config_param_ip":"11.1.1.70","web_port":"6501","unit_code":null,"create_time":null,"update_time":null,"status":0,"userCode":"video1","userPass":"video1","meetingId":"1","meetingPass":"","apiPort":"13000","username":"admin","password":"123456","updateTime":"2021-11-08 17:45:29"}}
使用方法
try {
JSONObject jsonObject = new JSONObject(outstring);
int resultCode = jsonObject.getInt("status");
if (resultCode == 200) {
JSONObject obj = jsonObject.getJSONObject("data");
IP = obj.getString("config_param_ip");
port = obj.getString("web_port");
username = obj.getString("userCode");
password = obj.getString("userPass");
roomID = Integer.parseInt(obj.getString("meetingId"));
roomPassword = obj.getString("password");
} else {
ToastUtils.showShort("查詢失敗");
}
goVideo();
} catch (Exception e) {
e.printStackTrace();
}
E. Android開發中為什麼很少使用JSON存儲數據
是可以用JSON存儲數據對象的,而且也是Google推薦的,可以取代以實現Serializable來存儲對象的方法。下面是使用JSON存儲數據的原因。
Android開發中,涉及到對象存儲,通常的做法是直接實現`Serializable`。有關這個介面,它保證了實現該介面的類的對象能夠被`ObjectOutput/InputStream`直接輸入輸出,即序列化。這很方便,但是也很不好。
提到『序列化』,大多數人都想到`Serializable`,而實際上『序列化』的只是指「將對象的狀態信息轉換為可以存儲或傳輸的形式的過程」,Java的`Serializabe`是位元組序列化的一種。
`Serialziable`的缺點之一是,實現了該介面的類將失去靈活性。這一點《Effective Java》第74條也指出了,實現了這個`Serializable`的類將會依賴這個類的內部演化,根源在於UID(Serial version UID)。如果你沒有指定UID,那麼每次這個類被序列化時都會根據這個類的當前狀態生成一個UID。想像這么一種場景:這個類已經被導出了,比如發給其他公司或部門使用了,然後你又修改了這個類,那麼當你再將這個類發布時,由於UID不同,其他公司或部門的程序員將可能得到一個「InvalidClassException」。
這種情況的根本原因是因為你不能控制序列化的實現,你控制不了UID的生成過程。這就需要一個自定義的序列化形式。在Android中,Google推薦JSON序列化。而且Android程序員也可以使用Gson等工具來進行序列化和反序列化。
和`Serializable`的位元組序列化不同,JSON序列化是字元序列化。
此外,`Serializable`只適合存儲對象。由於在傳輸時`Serializalbe`要做大量IO,Android提供了`Parcelable`。
最後,題主不應該把資料庫和JSON,XML比較,如果要比,也只能把資料庫和文件存儲比。資料庫適合存儲數量大,關系復雜的數據,這樣管理,查閱就很方便。與此相對文件存儲適合數量小,關系簡單的數據。
F. 適用於android的優秀的json解析庫有哪些
開始項目中使用的是fastjson,而且作者也說比gson快6倍,甚至嘲諷gson的g代表了「龜速」的意思,可是我自己的簡單測試是,比較簡陋的測試,一個10萬條數據的json文件,gson比fastjson快一些,快了大概80%的樣子。雖然測試可能不科學,但數據確實是我們項目中的實際數據,所以……
另外,也許是我使用真的有問題?使用的新版本的fastjson性能反而比舊的要低很多(1.2.7,1.1.44-android,1.1.33-android裡面,1.1.33反而是最快的)。
然而,最終我選擇了logan square,它的速度比fastjson快了2-3倍(自測),嗯,推薦Android開發者們使用Logan Square。
G. android怎麼得到php發來的json數據
使用守則
首先,我們要創建Web服務,從MySQL資料庫中讀取數據。
<?php
<pre>/* require the user as the parameter */
<pre>//http://localhost:8080/sample1/webservice1.php?user=1
if(isset($_GET['user']) && intval($_GET['user'])) {
/* soak in the passed variable or set our own */
$number_of_posts = isset($_GET['num']) ? intval($_GET['num']) : 10; //10 is the default
$format = strtolower($_GET['format']) == 'json' ? 'json' : 'xml'; //xml is the default
$user_id = intval($_GET['user']); //no default
/* connect to the db */
$link = mysql_connect('localhost','root','123456') or die('Cannot connect to the DB');
mysql_select_db('TEST',$link) or die('Cannot select the DB');
/* grab the posts from the db */
//$query = "SELECT post_title, guid FROM wp_posts WHERE post_author =
// $user_id AND post_status = 'publish' ORDER BY ID DESC LIMIT $number_of_posts";
$query = "SELECT * FROM `test`.`users`;";
$result = mysql_query($query,$link) or die('Errant query: '.$query);
/* create one master array of the records */
$posts = array();
if(mysql_num_rows($result)) {
while($post = mysql_fetch_assoc($result)) {
$posts[] = array('post'=>$post);
}
}
/* output in necessary format */
if($format == 'json') {
header('Content-type: application/json');
echo json_encode(array('posts'=>$posts));
}
else {
header('Content-type: text/xml');
echo '';
foreach($posts as $index => $post) {
if(is_array($post)) {
foreach($post as $key => $value) {
echo '<',$key,'>';
if(is_array($value)) {
foreach($value as $tag => $val) {
echo '<',$tag,'>',htmlentities($val),'</',$tag,'>';
}
}
echo '</',$key,'>';
}
}
}
echo '';
}
/* disconnect from the db */
@mysql_close($link);
}
?>
下面是代碼為Android活動讀取Web服務和解析JSON對象:
public void clickbutton(View v) {
try {
// http://androidarabia.net/quran4android/phpserver/connecttoserver.php
// Log.i(getClass().getSimpleName(), "send task - start");
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams,
TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
//
HttpParams p = new BasicHttpParams();
// p.setParameter("name", pvo.getName());
p.setParameter("user", "1");
// Instantiate an HttpClient
HttpClient httpclient = new DefaultHttpClient(p);
String url = "http://10.0.2.2:8080/sample1/" +
"webservice1.php?user=1&format=json";
HttpPost httppost = new HttpPost(url);
// Instantiate a GET HTTP method
try {
Log.i(getClass().getSimpleName(), "send task - start");
//
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
2);
nameValuePairs.add(new BasicNameValuePair("user", "1"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httppost,
responseHandler);
// Parse
JSONObject json = new JSONObject(responseBody);
JSONArray jArray = json.getJSONArray("posts");
ArrayList<HashMap<String, String>> mylist =
new ArrayList<HashMap<String, String>>();
for (int i = 0; i < jArray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = jArray.getJSONObject(i);
String s = e.getString("post");
JSONObject jObject = new JSONObject(s);
map.put("isers", jObject.getString("isers"));
map.put("UserName", jObject.getString("UserName"));
map.put("FullName", jObject.getString("FullName"));
mylist.add(map);
}
Toast.makeText(this, responseBody, Toast.LENGTH_LONG).show();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Log.i(getClass().getSimpleName(), "send task - end");
} catch (Throwable t) {
Toast.makeText(this, "Request failed: " + t.toString(),
Toast.LENGTH_LONG).show();
}
}
這里是PHP代碼,將數據發送到Web服務,並將其保存:
<?php
//$json=$_GET ['json'];
$json = file_get_contents('php://input');
$obj = json_decode($json);
//echo $json;
//Save
$con = mysql_connect('localhost','root','123456')
or die('Cannot connect to the DB');
mysql_select_db('TEST',$con);
/* grab the posts from the db */
//$query = "SELECT post_title, guid FROM wp_posts WHERE
// post_author = $user_id AND post_status = 'publish'
// ORDER BY ID DESC LIMIT $number_of_posts";
mysql_query("INSERT INTO `test`.`users` (UserName, FullName)
VALUES ('".$obj->{'UserName'}."', '".$obj->{'FullName'}."')");
mysql_close($con);
//
//$posts = array($json);
$posts = array(1);
header('Content-type: application/json');
echo json_encode(array('posts'=>$posts));
?>
Android的活動,將數據發送到Web服務作為一個JSON對象保存在MySQL資料庫中
public void clickbuttonRecieve(View v) {
try {
JSONObject json = new JSONObject();
json.put("UserName", "test2");
json.put("FullName", "1234567"); HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams,
TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
HttpClient client = new DefaultHttpClient(httpParams);
//
//String url = "http://10.0.2.2:8080/sample1/webservice2.php?" +
// "json={\"UserName\":1,\"FullName\":2}";
String url = "http://10.0.2.2:8080/sample1/webservice2.php";
HttpPost request = new HttpPost(url);
request.setEntity(new ByteArrayEntity(json.toString().getBytes(
"UTF8")));
request.setHeader("json", json.toString());
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
// If the response does not enclose an entity, there is no need
if (entity != null) {
InputStream instream = entity.getContent();
String result = RestClient.convertStreamToString(instream);
Log.i("Read from server", result);
Toast.makeText(this, result,
Toast.LENGTH_LONG).show();
}
} catch (Throwable t) {
Toast.makeText(this, "Request failed: " + t.toString(),
Toast.LENGTH_LONG).show();
}
}
知識點
要連接到你的模擬器,你可以使用此鏈接:http://10.0.2.2:8080/。
要讀取JSON對象在Web服務中,您可以使用下面這行代碼:
$json = file_get_contents('php://input');
$obj = json_decode($json);
H. android 怎樣將數據以json格式保存在手機文件中
json是一種輕量級數據交換格式,可以包含對象和數組,以下是一個json字元串的示例:
{"key":[{"key1":"value1","key2":value2",...}]}
json只是一種數據交換格式,並不是存儲格式,所以只要你正確地組織好json字元串後,跟其他文件是一樣存儲的;
同時建議你,如果你存儲的數據量比較多的話,建議存儲在android系統自帶的SQLite資料庫中,這樣操作起數據來更方便簡單;如果數據量非常少,只有三五個欄位存儲,那樣使用android的SharedPreferences可能會是更好的選擇,希望你根據應用需求適當選用。
I. 如何使用JSON連接Android和PHP Mysql資料庫
使用JSON連接Android和PHP Mysql資料庫方法:
1、打開安裝WAMP Server的文件夾,打開www文件夾,為你的項目創建一個新的文件夾。必須把項目中所有的文件放到這個文件夾中。
2、新建一個名為android_connect的文件夾,並新建一個php文件,命名為test.php,嘗試輸入一些簡單的php代碼(如下所示)。
test.php
<?php
echo"Welcome, I am connecting Android to PHP, MySQL";
?>
3、創建MySQL資料庫和表
創建了一個簡單的只有一張表的資料庫。用這個表來執行一些示例操作。現在,請在瀏覽器中輸入http://localhost/phpmyadmin/,並打開phpmyadmin。你可以用PhpMyAdmin工具創建資料庫和表。
創建資料庫和表:資料庫名:androidhive,表:proct
CREATE TABLE procts(
pid int(11) primary key auto_increment,