这是我的json
{"user_data":[{"year":"2017","month":"12","day":"12","StartTime":"2:00 am","Endtime":"4:00 am","Hours":"02:00:00"},{"year":"2018","month":"12","day":"10","StartTime":"5:00 am","Endtime":"7:00 am","Hours":"02:00:00"}]}
我使用fetch.php代码
收到的json对象 <?php
require "init.php";
//$name = $_POST["name"];
// $password = $_POST["password"];
$name = "surya";
$password = "1995";
$Sql = "SELECT * FROM `user_info`
WHERE `name`='".$name."' AND
`password`='".$password."';";
$result = mysqli_query($con, $Sql);
$retrive = array();
while($row = mysqli_fetch_array($result))
{
$user_id = $row['id'];
$sql = "SELECT id, ScheduleDate, StartTime,Endtime, Hours,Employeeid
FROM empdet WHERE Employeeid ='".$user_id."' ";
$result = $con->query($sql);
if ($result->num_rows > 0)
{
// output data of each row
while($row = $result->fetch_assoc())
{
$id=$row["id"].
$date=$row["ScheduleDate"];
$start=$row["StartTime"];
$end=$row["Endtime"];
$hour=$row["Hours"];
$Employeeid=$row["Employeeid"];
list($year,$month,$day) = split("-",$date);
$data[] = array("year"=>$year,
"month"=>$month,
"day"=>$day,
"StartTime"=>$start,
"Endtime"=>$end,
"Hours"=>$hour );
}$response = $data;
} else
{
echo "0 results";
}
}
echo json_encode(array("user_data"=> $response));
?>
我的问题是如何在android活动中接收多行json对象, 首先,我试图接收它工作的一行,但是当我试图设置一个循环它不能在android活动中工作,而且我还需要将意图中的多行发送到下一个activity.i尝试了不同的方式,但我找不到它如何设置循环。
1.如何从php文件接收多行json对象数据 2.如何设置一个循环意图逐个发送多行 3.如何使用循环在下一个活动中接收它们 请有人帮我做!
这是我的android代码! MAinactivity
package com.example.myapplication;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class Login extends Activity
{
EditText name, password;
String NAME=null, PASSWORD=null, EMAIL=null;
String Name, Password;
Context ctx=this;
String year,month,day,StartTime,Endtime,Hours;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
name = (EditText) findViewById(R.id.main_name);
password = (EditText) findViewById(R.id.main_password);
}
public void main_login(View v)
{
Name = name.getText().toString();
Password = password.getText().toString();
BackGround b = new BackGround();
b.execute(Name, Password);
}
class BackGround extends AsyncTask<String, String, String>
{
@Override
protected String doInBackground(String... params)
{
String name = params[0];
String password = params[1];
String data="";
int tmp;
// creating the connection with localhost
try {
URL url = new URL("http://localhost/sample/loo/login.php");
String urlParams = "name="+name+"&password="+password;
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setDoOutput(true);
OutputStream os = httpURLConnection.getOutputStream();
os.write(urlParams.getBytes());
os.flush();
os.close();
InputStream is = httpURLConnection.getInputStream();
while((tmp=is.read())!=-1)
{
data+= (char)tmp;
}
is.close();
httpURLConnection.disconnect();
return data;
} catch (MalformedURLException e) {
e.printStackTrace();
return "Exception: "+e.getMessage();
} catch (IOException e) {
e.printStackTrace();
return "Exception: "+e.getMessage();
}
}
@Override
protected void onPostExecute(String result)
{
String err=null;
//fetching thte data from database using php/json
for (int j = 0; j < result.length(); j++) {
try
{
JSONObject root = new JSONObject(result);
boolean error = root.getBoolean("error");
if (!error) {
JSONObject user_data = root.getJSONObject("user_data");
year = user_data.getString("year");
month = user_data.getString("month");
day = user_data.getString("day");
StartTime = user_data.getString("StartTime");
Endtime = user_data.getString("Endtime");
Hours = user_data.getString("Hours");
}
} catch (JSONException e)
{
e.printStackTrace();
err = "Exception: "+e.getMessage();
} }
//passing the value to calender activity
Intent i = new Intent(ctx, Calender.class);
i.putExtra("year", year);
i.putExtra("month", month);
i.putExtra("day", day);
i.putExtra("StartTime", StartTime);
i.putExtra("Endtime", Endtime);
i.putExtra("Hours", Hours);
i.putExtra("err", err);
startActivity(i);
if(result==null)
{
Toast.makeText(Login.this, "result is null", Toast.LENGTH_LONG).show();
}
//else {
// Intent i = new Intent(ctx, Main2Activity.class);
// startActivity(i);
// Toast.makeText(MainActivity.this, "has a value", Toast.LENGTH_LONG).show();
// }
}
}
}
这是我的第二项活动
package com.example.myapplication;
import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.CalendarContract;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
public class Calender extends AppCompatActivity
{
String day, month, year,Hours,Endtime,StartTime, Err,Shours,Sminutes,Ssecond,Ehours,Eminutes,Esecond,Eampm,Sampm;
int s,mo;
public static final int MY_PERMISSIONS_REQUEST_WRITE_CALENDAR = 123;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calender);
context = Calender.this;
writeCalendarEvent();
}
private void writeCalendarEvent()
{
year = getIntent().getStringExtra("year");
month = getIntent().getStringExtra("month");
day = getIntent().getStringExtra("day");
StartTime = getIntent().getStringExtra("StartTime");
Endtime = getIntent().getStringExtra("Endtime");
Hours = getIntent().getStringExtra("Hours");
Err = getIntent().getStringExtra("err");
}
}
答案 0 :(得分:1)
试试这个
try
{
JSONObject root = new JSONObject(result);
JSONArray user_data = root.getJSONArray("user_data");
for (int i = 0; i < user_data.length(); i++) {
JSONObject jsonObject = user_data.getJSONObject(i);
year = jsonObject.getString("year");
month = jsonObject.getString("month");
day = jsonObject.getString("day");
StartTime = jsonObject.getString("StartTime");
Endtime = jsonObject.getString("Endtime");
Hours = jsonObject.getString("Hours");
}
}
catch (JSONException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
答案 1 :(得分:0)
试试这个:
JSONArray jArr = root.getJSONArray("user_data");
int arrLen = jArr.length();
if(arrLen != 0)
{
for (int i = 0; i < arrLen; i++)
{
JSONObject obj = (JSONObject) jArr.get(i);
year = obj.getString("year");
month = obj.getString("month");
day = obj.getString("day");
StartTime = obj.getString("StartTime");
Endtime = obj.getString("Endtime");
Hours = obj.getString("Hours");
}
}
答案 2 :(得分:0)
来自json截图,user_data
不是JSONObject
实际上这是JSONArray
所以请查看以下代码
JASONArray jsonArray = root.getJSONArray("user_data");
JSONObject user_data = jsonArray.getJSONObject(0);
year = user_data.getString("year");
month = user_data.getString("month");
day = user_data.getString("day");
StartTime = user_data.getString("StartTime");
Endtime = user_data.getString("Endtime");
Hours = user_data.getString("Hours");
答案 3 :(得分:0)
试试这段代码。这只是解析将数据从一个活动发送到另一个活动,您需要将该数据存储到数组上,然后将其发送到Intent并将该数据接收到另一个活动。
try
{
JSONObject jsonObject = new JSONObject(result);
JSONArray userData = jsonObject.getJSONArray("user_data");
if (userData != null)
{
for (int j = 0; j < userData.length(); j++) {
JSONObject user_data = userData.getJSONObject(j);
year = user_data.getString("year");
month = user_data.getString("month");
day = user_data.getString("day");
StartTime = user_data.getString("StartTime");
Endtime = user_data.getString("Endtime");
Hours = user_data.getString("Hours");
// here store this String value in one array and pass that array in Intent
}
}
//like your array name is UserData then you can do like this
// but make sure if you use List with Model then make it
//Serializable or Parcelable
if (UserData != null)
{
Intent i = new Intent(ctx, Main2Activity.class);
i.putExtra("userData", UserData);
startActivity(i);
}
else{
// data is null or something wrong
}
}
catch (Exception e) {
e.printStackTrace();
}
答案 4 :(得分:0)
试试这个,希望它能起作用
JSONObject jsonObject = new JSONObject(result);
String user = jsonObject.getString("user_data");
JSONArray jsonArray = new JSONArray(user);
for(int j =0 ; j<jsonArray.length() ; j++) {
JSONObject json = jsonArray.getJSONObject(j);
String year = json.getString("year");
String month = json.getString("month");
String day = json.getString("day"):
}