dongzhuo3202 2017-12-20 06:36
浏览 52
已采纳

如何使用json从php文件发送整数值到android活动?

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);
    }
}
  • 写回答

1条回答 默认 最新

  • dsmvqp3124 2017-12-20 06:43
    关注

    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");
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效