selva s
selva s

Reputation: 27

how to send integer value from php file to android activity using json?

I need to send the integer value from PHP file to android activity, but it is showing exception error.

That is,

Exception value [",null,null] at user_data of the type org.json.JSONARRAY cannot be converted to JSONObject.

Anyone help me please.

This is my output with error.

This is my output with error

My PHP code which will fetch the date from database and separate into separate day, month, year. Here the process is working fine, but not able to send that day, month, year, to android activity.

       <?php 
error_reporting(0);
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'];


    $ids=$row;
     $q = "SELECT `ScheduleDate` FROM user_info WHERE id ='" . $user_id . "'";


        $result = $con->query($q);
        $rows = $result->fetch_assoc();
          $date=$rows["ScheduleDate"];


 list($year,$month,$day) = split("-",$date);

 $response = array( $year , $month ,$day );

  //echo $year;
   //echo $month;
   //echo $day;


//$response = array("year"=>"$year","month"=>"$month","day"=>"$day");



}

//if(!$response==null)
 // {

    //  echo "Matches";

 // }
  //else
  //{
      // echo "No match";
  //}

 echo json_encode(array("user_data"=> $response));


?>

This my database structure.

This my database structure

Full Android code Main activity,home Activity

Main activity

      package com.example.text;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
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 MainActivity extends AppCompatActivity {

    EditText name, password;
    String Name, Password;
    Context ctx=this;

    String year,month,day;

    @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_register(View v){
        //startActivity(new Intent(this,Register.class));
    }

    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://www.powersys-india.com/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 s) {
            String err=null;
            try {

               /* if(s.equals("Matches")) {

                    Toast.makeText(MainActivity.this, "has a value", Toast.LENGTH_LONG).show();
                }

                if(s.equals("No match")) {

                    Toast.makeText(MainActivity.this, "no value", Toast.LENGTH_LONG).show();
                }*/


                JSONObject jsonObject = new JSONObject(s);
                JSONArray jsonArray = jsonObject.getJSONArray("user_data");  //Parse array from json object



                for(int i=0;i<jsonArray.length();i++)
                {
                    JSONObject curr = jsonArray.getJSONObject(i);

                      year = curr.getString("year");
                      month = curr.getString("year");
                      day = curr.getString("day");

                    //Do stuff with the month day String here
                }


            } catch (JSONException e) {
                e.printStackTrace();
                err = "Exception: "+e.getMessage();
            }

            Intent i = new Intent(ctx, Home.class);
            i.putExtra("year", year);
            i.putExtra("month", month);
            i.putExtra("day", day);
            i.putExtra("err", err);
            startActivity(i);

        }
    }

}

Home Avtivity

 package com.example.text;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;

public class Home extends AppCompatActivity {

    String day, month, year, Err;
    TextView nameTV, emailTV, passwordTV, err;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);

        nameTV = (TextView) findViewById(R.id.home_name);
        emailTV = (TextView) findViewById(R.id.home_email);
        passwordTV = (TextView) findViewById(R.id.home_password);
        err = (TextView) findViewById(R.id.err);

        year = getIntent().getStringExtra("year");
        month = getIntent().getStringExtra("month");
        day = getIntent().getStringExtra("day");
        Err = getIntent().getStringExtra("err");





        nameTV.setText("YEAR "+year);
        passwordTV.setText("MONTH "+month);
        emailTV.setText("DATE "+day);
        err.setText(Err);
    }
}

Upvotes: 1

Views: 842

Answers (1)

Ramesh sambu
Ramesh sambu

Reputation: 3539

In Php file, you're sending the response as JsonArray.So convert response string to JSONArray and Parse

Use

JSONObject jsonObject = new JSONObject(s);
JSONArray jsonArray = jsonObject.getJSONArray("user_data");  //Parse array from json object

for(int i=0;i<jsonArray.length();i++)
 {
 JSONObject curr = jsonArray.getJSONObject(i);

 String year = curr.getString("year")


 //Do stuff with the month day String here
 }

Instead

 JSONObject root = new JSONObject(s);
 JSONObject user_data = root.getJSONObject("user_data");

Upvotes: 0

Related Questions