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,