This is my 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"}]}
The json object i received using fetch.php code
<?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));
?>
my question is how to receive multiple rows of json object in android activity, first i tried to receive one row it worked ,but when i tried to set a loop it is not working in android activity,and also i need send the multiple rows in intent to next activity.i tried diffrent ways but i cannot find it how to set loop .
1.how to receiving the multiple rows of json object data from php file 2.how to set a loop in intent to send the multiple rows one by one 3.how to receive them in next activity using loop please anyone help me to do it!!
this is my android code! 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();
// }
}
}
}
This is my second activity
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");
}
}
Try this
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();
}
Try this:
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");
}
}
from json screenshot your user_data
is not JSONObject
actually this is JSONArray
so check below code
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");
Try this code. This is just parsing only for sending data from one activity to another activity you need to store that data to on array an send it on Intent and receive that data to another activity.
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();
}
Try this, hope it will work
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"):
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.