使用JSON在Android的ArrayList发送到PHP脚本 [英] Sending ArrayList from Android to PHP script using JSON
问题描述
什么是情景
我想从Android发送多个的ArrayList(usally 5)到服务器,并希望将其插入到MySQL数据库。
I want to send multiple ArrayList (usally 5) from android to the server and want to insert it into mysql database.
我已经成功地完成
我已经成功地使用JSON在Android发送单一值,多个值,以PHP脚本
I have Successfully send single value and Multiple Values from Android to PHP script using JSON
我收到单个或多个记录,从MySQL数据库使用JSON到Android
i have Received single and Multiple Records from mysql database to android using JSON
下面是code插入和正从服务器值
Here is the Code for inserting and getting value from server
class TeacherLogin1 extends AsyncTask<Void, Void, Void> {
String name,pass;
Context contextt;
int idofteach = 0;
int codee = 0;
TeacherLogin1(String pass1,String name1,Context context)
{
name = name1;
pass = pass1;
contextt = context;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... arg0) {
codee = Authenticate(name,pass);
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if(codee!=0)
{
Intent teachers = new Intent(context,TeachersView.class);
teachers.putExtra("TID", codee);
teachers.putExtra("TNAME", TeachName);
teachers.putExtra("sub1", subj1);
teachers.putExtra("sub2", subj2);
teachers.putExtra("sub3", subj3);
teachers.putExtra("sub4", subj4);
startActivity(teachers);
}
else
Toast.makeText(context, "Wrong Details", Toast.LENGTH_SHORT).show();
codee = 0;
}
}
public int Authenticate(String name,String Pass)
{
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
// put the values of id and name in that variable
nameValuePairs.add(new BasicNameValuePair("name",name));
nameValuePairs.add(new BasicNameValuePair("pass",Pass));
try
{
HttpClient httpclient = new DefaultHttpClient();
ScriptsFilePath a = new ScriptsFilePath();
HttpPost httppost = new HttpPost(a.TeacherAuthen);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("pass 1", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 1", e.toString());
}
try
{
BufferedReader reader = new BufferedReader
(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.e("pass 2", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 2", e.toString());
}
try {
JSONObject jsonResponse = new JSONObject(result);
if(jsonResponse != null)
{
JSONArray jsonMainNode = jsonResponse.optJSONArray("GetTeacher");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
code = jsonChildNode.optInt("ID");
TeachName= jsonChildNode.optString("Name");
subj1= jsonChildNode.optString("subject1");
subj2= jsonChildNode.optString("subject2");
subj3= jsonChildNode.optString("subject3");
subj4= jsonChildNode.optString("subject4");
}
}
} catch (JSONException e) {
// Toast.makeText(getApplicationContext(), "Error" + e.toString(),
// Toast.LENGTH_SHORT).show();
}
return code;
}
和TeacherAuthen.php脚本
and the TeacherAuthen.php script
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
$host="localhost";
$uname="root";
$pwd='';
$db="examsystem";
$con = mysql_connect($host,$uname,$pwd) or die("connection failed");
mysql_select_db($db,$con) or die("db selection failed");
if(isset($_REQUEST)){
$name=$_REQUEST['name'];
$pass=$_REQUEST['pass'];}
$flag['code']=0;
$name1['code1'] = "sdf";
$sql = "SELECT * FROM teachers WHERE Username ='$name' and Pass='$pass'";
$result = mysql_query($sql);
$json = array();
if(mysql_num_rows($result)){
while($row=mysql_fetch_assoc($result)){
$json['GetTeacher'][]=$row;
}
}
echo json_encode($json);
mysql_close($con);
?>
我在哪里卡住
我不无如何从Android发送到ArrayList的PHP脚本。
I dont no how to send ArrayList from android to PHP Script.
例如我想这些的ArrayList发送到PHP脚本=
For Example I want to send these arraylists to php script =
ArrayList<String> Questions= new ArrayList<String>();
ArrayList<String> A1= new ArrayList<String>();
ArrayList<String> A2= new ArrayList<String>();
ArrayList<String> A3= new ArrayList<String>();
ArrayList<String> A4= new ArrayList<String>();
然后在PHP脚本我想插入这样
and then in the PHP script i want to insert like this
"INSERT INTO `Question` (`ID` ,`Question` ,`A1` ,`A2` ,`A3` , `A4` ) VALUES (NULL, '$Question', '$A1', '$A2', '$A3' ,'$A4'); "
如果我能够派哪怕一个ArrayList的话,我想我可以做一个办法做到上述
if i am able to send even a single arrayList then i think i can make a way to do the above
和感谢您的时间
推荐答案
这是您的数组:你可以创建更多的在你需要的例子。
This is your Array: you can create more as required in your example.
ArrayList<String> contact = new ArrayList<String>();
然后,创建类型JSON的JSONcontacts变量数组存储在该对象
Then, create a JSONcontacts variable of type JSON to store this array in this object
JSONObject JSONcontacts = new JSONObject();
现在,通过接触数组中的所有元素循环,并将其存储在JSONcontacts
Now, loop through all elements in that contact array and store it in the JSONcontacts
//Loop through array of contacts and put them to a JSONcontact object
for (int i = 0; i < contact.size(); i++) {
try {
JSONcontacts.put("Count:" + String.valueOf(i + 1), contact.get(i));
} catch (JSONException e) {
e.printStackTrace();
}
}
比方说你创造了许多数组,你可能已经做了,现在你hvave把他们都变成1 JSON。因此,创建类型的JSONObject()
Lets say you created many Arrays, which you probably have done, now you hvave to put them all into 1 JSON. So create a EverythingJSON variable of type JSONObject()
JSONObject EverythingJSON = new JSONObject();
现在把你所有的触点阵列等阵列进去,对你遍历他们如上文所述:
and now put all your contact array and other arrays into it, right you loop through them as described above:
EverythingJSON.put("contact", JSONcontacts);
EverythingJSON.put("something", JSONsoemthing);
EverythingJSON.put("else", JSONelse);
现在这是你要AsynchTask它们发送到你的PHP服务器:
now this is your AsynchTask to send them to your PHP server:
new AsyncTask() {
//String responseBody = "";
@SuppressWarnings("unused")
protected void onPostExecute(String msg) {
//Not Needed
}
protected Object doInBackground(Object... params) {
//Create Array of Post Variabels
ArrayList<NameValuePair> postVars = new ArrayList<NameValuePair>();
//Add a 1st Post Value called JSON with String value of JSON inside
//This is first and last post value sent because server side will decode the JSON and get other vars from it.
postVars.add(new BasicNameValuePair("JSON", String.valueOf(JSON)));
//Declare and Initialize Http Clients and Http Posts
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Config.OnlineAPI);
//Format it to be sent
try {
httppost.setEntity(new UrlEncodedFormEntity(postVars));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
/* Send request and Get the Response Back */
try {
HttpResponse response = httpclient.execute(httppost);
String responseBody = EntityUtils.toString(response.getEntity());
} catch (ClientProtocolException e) {
e.printStackTrace();
Log.v("MAD", "Error sending... ");
} catch (IOException e) {
e.printStackTrace();
Log.v("MAD", "Error sending... ");
}
return null;
}
}.execute(null, null, null);
现在在PHP服务器端,你可以通过这个JSON作为这样的循环:
首先,从POST得到JSON并将其存储在一个VAR:
Now on the PHP server side, you can loop through this JSON as such: FIrst of all, get that JSON from POST and store it in a var:
//Receive JSON
$JSON_Received = $_POST["JSON"];
现在去code从JSON:
Now decode it from JSON:
//Decode Json
$obj = json_decode($JSON_Received, true);
这是循环从中穿过触头阵列,并得到他键和值:
And this is the loop to go through the array of contacts and get he Key and Value from it:
foreach ($obj['contact'] as $key => $value)
{
//echo "<br>------" . $key . " => " . $value;
}
您可以重复这个循环对于其他阵列您发送:)祝你好运!
you can repeat this loop for other Arrays you have sent :) Good Luck!
这篇关于使用JSON在Android的ArrayList发送到PHP脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!