0

I'm retriving the data from php to android using json when retriving myjson string has all values of php when i use

array= j.getJSONArray("result"); 

j has the 1st array element but my array is null. Plz anybody say me the exact reason behind this

    public void getData() {
        class GetDataJSON extends AsyncTask<String, Void, String> {

            @Override
            protected String doInBackground(String... params) {
                DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
                HttpPost httppost = new HttpPost("http://futuroitsolutions.in/php_android_api/data1.php");

                // Depends on your web service
                httppost.setHeader("Content-type", "application/json");

                InputStream inputStream = null;
                String result = null;
                try {
                    HttpResponse response = httpclient.execute(httppost);
                    HttpEntity entity = response.getEntity();

                    inputStream = entity.getContent();
                    // json is UTF-8 by default
                    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
                    StringBuilder sb = new StringBuilder();

                    String line = null;
                    while ((line = reader.readLine()) != null) {
                        sb.append(line + "\n");
                    }
                    result = sb.toString();
                } catch (Exception e) {
                    // Oops
                } finally {
                    try {
                        if (inputStream != null) inputStream.close();
                    } catch (Exception squish) {
                    }
                }
                return result;
            }

            @Override
            protected void onPostExecute(String result) {
                myJSON = result;
                ShowList( );
            }
        }
        GetDataJSON g = new GetDataJSON();
        g.execute();

    }
 public void ShowList() {
try {

    String vi=myJSON;
    vi=vi.replace('[',' ').replace(']',' ');
      JSONObject j = new JSONObject(vi);
      array= j.getJSONArray("result");
       try {


        for(int i=0;i<array.length();i++){
            JSONObject c = array.getJSONObject(i);
            id = c.getString(TAG_ID);
            name = c.getString(TAG_NAME);
            km = c.getString(TAG_KILOMETER);
            time = c.getString(TAG_TIMING);
            // get your data from jsonobject
        }
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

        //    String regno = c.getString(TAG_REG);
        //   String phone = c.getString(TAG_PHONE);
        //   String category = c.getString(TAG_CAT);

    }

        catch (JSONException e) {
            e.printStackTrace();
        }
     TableLayout tv = (TableLayout) findViewById(R.id.table);
      tv.removeAllViewsInLayout();
        int flag = 1;
     int c=array.length();
        for (int i = 0; i < c ; i++) {
        TableRow tr = new TableRow(MainActivity.this);
        tr.setLayoutParams(new LayoutParams(
                LayoutParams.FILL_PARENT,
                LayoutParams.WRAP_CONTENT));
        if (flag == 1) {
            TextView b6 = new TextView(MainActivity.this);
            b6.setText("Id");
            b6.setTextColor(Color.BLUE);
            b6.setTextSize(15);
            tr.addView(b6);
            TextView b19 = new TextView(MainActivity.this);
            b19.setPadding(10, 0, 0, 0);
            b19.setTextSize(15);
            b19.setText("Task name");
            b19.setTextColor(Color.BLUE);
            tr.addView(b19);
            TextView b29 = new TextView(MainActivity.this);
            b29.setPadding(10, 0, 0, 0);
            b29.setText("Timing");
            b29.setTextColor(Color.BLUE);
            b29.setTextSize(15);
            tr.addView(b29);
            tv.addView(tr);
            TextView b21 = new TextView(MainActivity.this);
            b29.setPadding(10, 0, 0, 0);
            b29.setText("Kilometers");
            b29.setTextColor(Color.BLUE);
            b29.setTextSize(15);
            tr.addView(b21);
            tv.addView(tr);

            final View vline = new View(MainActivity.this);
            vline.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, 2));
            vline.setBackgroundColor(Color.BLUE);
            tv.addView(vline);
            flag = 0;
        } else {
            //JSONObject json_data = jArray.getJSONObject(i);
           // Log.i("log_tag", "id: " + json_data.getInt("Id") + ", Username: " + json_data.getString("Task name") + ", No: " + json_data.getString("Kilometers"));
            TextView b = new TextView(MainActivity.this);
            String stime =id;
            b.setText(stime);
            b.setTextColor(Color.RED);
            b.setTextSize(15);
            tr.addView(b);
            TextView b1 = new TextView(MainActivity.this);
            b1.setPadding(10, 0, 0, 0);
            b1.setTextSize(15);
            String stime1 = name;
            b1.setText(stime1);
            b1.setTextColor(Color.BLACK);
            tr.addView(b1);
            TextView b2 = new TextView(MainActivity.this);
            b2.setPadding(10, 0, 0, 0);
            String stime2 = time;
            b2.setText(stime2);
            b2.setTextColor(Color.BLACK);
            b2.setTextSize(15);
            tr.addView(b2);
            tv.addView(tr);
            TextView b3 = new TextView(MainActivity.this);
            b2.setPadding(10, 0, 0, 0);
            String stime3 = km;
            b2.setText(stime3);
            b2.setTextColor(Color.BLACK);
            b2.setTextSize(15);
            tr.addView(b2);
            tv.addView(tr);
            final View vline1 = new View(MainActivity.this);
            vline1.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, 1));
            vline1.setBackgroundColor(Color.WHITE);
            tv.addView(vline1);
        }
    }
}

}

when i debug, I get

vi=
 {"id":"1","Taskname":"edapally to kakkanad","SourceLa":"10.0236761","SourceLo":"76.311623","Path1La":"10.0327153","Path1Lo":"76.331889","Path2La":"10.0231412","Path2Lo":"76.3409954","DestinationLa":"10.0158605","DestinationLo":"76.3418666","Timing":"10 a.m","Kilometer":"8"} 

j={"id":"1","Taskname":"edapally to kakkanad","SourceLa":"10.0236761","SourceLo":"76.311623","Path1La":"10.0327153","Path1Lo":"76.331889","Path2La":"10.0231412","Path2Lo":"76.3409954","DestinationLa":"10.0158605","DestinationLo":"76.3418666","Timing":"10 a.m","Kilometer":"8"}

array=null my json

[{"id":"1","Taskname":"edapally to kakkanad","SourceLa":"10.0236761","SourceLo":"76.311623","Path1La":"10.0327153","Path1Lo":"76.331889","Path2La":"10.0231412","Path2Lo":"76.3409954","DestinationLa":"10.0158605","DestinationLo":"76.3418666","Timing":"10 a.m","Kilometer":"8"}]

Data1.php

  <?php
  include('sql.php');

   mysql_query('SET CHARACTER SET utf8') ;

      $result = mysql_query('SELECT * FROM Location') or             die(mysql_error());

       while($row = mysql_fetch_assoc($result))
      {

      $rows[] = $row;

     }

       $final=array("result"=>$rows);

       echo json_encode($rows);
     ?>
3
  • You are getting JSONObject not JSONArray in vi as you said. Commented May 17, 2017 at 11:19
  • if you want a result , you should encode $final, not $rows in your php. Commented May 17, 2017 at 11:26
  • ya i encoded final only but it also gave array null so only i encoded $rows and also when i encode i get json like {"results"............[............]} Commented May 18, 2017 at 3:54

3 Answers 3

1

You can try the below code:

JSONArray jsonArray = new JSONArray(vi);
                    for(int k = 0; k < jsonArray.length(); k++)
                    {
                        JSONObject jsonObject = jsonArray.getJSONObject(k);

                        jsonObject.getString("id");
                        jsonObject.getString("Taskname");

                        .............
                        // parse all fields like above
                    }
Sign up to request clarification or add additional context in comments.

1 Comment

i'm getting array now but its legth seems to be null
0

You have not defined variable $rows outside of while loop. thats why scope of $rows is undefined.

<?php
include('sql.php');
mysql_query('SET CHARACTER SET utf8') ;
$rows=array();
$result = mysql_query('SELECT * FROM Location') or die(mysql_error());
while($row = mysql_fetch_assoc($result))
{
     $rows[] = $row;
}
$final=array("result"=>$rows);
echo json_encode($rows);

Comments

0

Try this instead.

String vi=myJSON;
JSONArray array = new JSONArray(vi);

2 Comments

give me your json object
are you still doing this ? vi=vi.replace('[',' ').replace(']',' '); if yes then please remove this line

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.