-1

This 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"
      }
   ]
}

i am able to recieve all the data from database using php in android activity,but the problem is i want to send the recieved data to another activity using the intent, i used the for loop to send the recieved data to another activity,when the loop is executed it sends all the data are going to next activity, but when i tried to print them in toast it prints the last rows details, my question is how to set the loop in 2nd activity to recieve one by one of each row.and i didnt set any loop in second activity,because i dont know how to do it. can anyone help me to do it?

this is my android code of 1st activity

     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.util.Log;
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;
import java.util.Calendar;


public class MainActivity extends Activity {

    EditText name, password;
    String NAME=null, PASSWORD=null, EMAIL=null;
    String Name, Password;
    Context ctx=this;
   // String[] year ;
   // String[] month;
   // String[] day;
   // String[] StartTime;
   // String[] Endtime;
    //String[] Hours;




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        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;

            try {
                URL url = new URL("http://localhost/sample/FETCH/fetch.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;
            try
            {
                JSONObject root = new JSONObject(result);

                JSONArray user_data = root.getJSONArray("user_data");

                String[] year = new String[user_data.length()];
                String[] month = new String[user_data.length()];
                String[] day = new String[user_data.length()];
                String[] StartTime = new String[user_data.length()];
                String[] Endtime = new String[user_data.length()];
                String[] Hours = new String[user_data.length()];

                for (int i = 0; i < user_data.length(); i++)
                {

                    JSONObject jsonObject = user_data.getJSONObject(i);

                    year[i]= jsonObject.getString("year");
                    month[i]  = jsonObject.getString("month");
                    day[i]  = jsonObject.getString("day");
                    StartTime[i]  = jsonObject.getString("StartTime");
                    Endtime[i]  = jsonObject.getString("Endtime");
                    Hours[i]  = jsonObject.getString("Hours");


                    Intent k = new Intent(ctx, Calender.class);
                    k.putExtra("year", year[i]);
                    k.putExtra("month", month[i]);
                    k.putExtra("day", day[i]);
                    k.putExtra("StartTime", StartTime[i]);
                    k.putExtra("Endtime", Endtime[i]);
                    k.putExtra("Hours", Hours[i]);
                    k.putExtra("err", err);
                    startActivity(k);


                }


                    //Toast.makeText(MainActivity.this, "result has value" + year[1], Toast.LENGTH_LONG).show();


            }
            catch (JSONException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            if(result==null)
            {
               // Toast.makeText(MainActivity.this, year[0], Toast.LENGTH_LONG).show();
            }else
                {

                    //Toast.makeText(MainActivity.this, "result has value"+ year[0]  , Toast.LENGTH_LONG).show();
            }

        }
    }
}

and this is my second activity,which recieves the data,i didnt set any loop here.

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");



            Toast.makeText(context, "result has value" + year, Toast.LENGTH_LONG).show();




    }
}
selva surya
  • 103
  • 9
  • Possible duplicate of [How do I pass data between Activities in Android application?](https://stackoverflow.com/questions/2091465/how-do-i-pass-data-between-activities-in-android-application) – AskNilesh Jan 03 '18 at 04:13
  • i saw that , i need to send multiple data to next activity,for example year variable has 2 values in for loop ,i need to send these to values to next activity. – selva surya Jan 03 '18 at 04:20
  • than check below ans https://stackoverflow.com/a/48071105/7666442 – AskNilesh Jan 03 '18 at 04:21

3 Answers3

2

you are doing it in the wrong way, it will show only the last row since it's the last time you are launching the intent and previous data are simply getting replaced. So you can either convert your JSON in some string and then transfer to other activity using the putExtraString or you can make a list of some model and then transfer the list to the intent and receive it in another activity.

here is how you can do it.

method 1

protected void onPostExecute(String result) {
        String err=null;
        try
        {
            JSONObject root = new JSONObject(result);

                Intent k = new Intent(ctx, Calender.class);
                k.putExtra("rootJson",result);
                startActivity(k);

            }

        }
        catch (JSONException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

and receive on another side using

String jsonString = getIntent().getStringExtra("rootJson");

or you can convert your JSON into some model and then make it parcelable and then put into intent and receive on another side.

vikas kumar
  • 10,447
  • 2
  • 46
  • 52
  • whats the use of creating `root` json object ? cant he just pass the string result?? @vikas?? – Santanu Sur Jan 03 '18 at 04:21
  • yes bro @SantanuSur you are right i will make the change. – vikas kumar Jan 03 '18 at 04:22
  • ok bro, i can try that, but i have problem in send whole string,because i am recieving the data from php using the url,if send the root string to next activity,once again i have to create class BackGround extends AsyncTask in second activity!!! – selva surya Jan 03 '18 at 04:27
  • if you have problem then you can turn it into some model and then send it to another activity. – vikas kumar Jan 03 '18 at 04:29
  • i have posted my full code of 1st activityplease check them @vika,@santanu – selva surya Jan 03 '18 at 04:31
  • i'm not getting the need to create Async in another activity. you want to transer the data now you have it what other processing you want to do – vikas kumar Jan 03 '18 at 04:36
0

Just pass the whole String result through intent as in your case and parse the data in the second activity.

Hemant Parmar
  • 3,924
  • 7
  • 25
  • 49
Santanu Sur
  • 10,997
  • 7
  • 33
  • 52
0

Instead of having String arrays, I think you should create a POJO to hold the fields and parse the JSON response to an array of POJO using Gson. After than let your POJO class implement Parcelable so that you can pass to the second activity.

Xu Lei
  • 141
  • 1
  • 4