0

I need to parse and array from http Get.

I receive :

[
  {
    "category_id": "334",
    "category_name": "ENGLISH PREMIER LEAGUE VOD",
    "parent_id": 0
  },......

so I'm starting of with

public class Welcome extends Activity {

    Button btnLogout;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_home);



        Intent intent = getIntent();

        String Welcome=("Welcome ," +getIntent().getStringExtra("Username"));
        String Username= (getIntent().getStringExtra("Username"));
        String Password =(getIntent().getStringExtra("Password"));
        TextView textView = (TextView) findViewById(R.id.usertext);
        textView.setTextSize(45);
        textView.setText(Welcome);

          System.out.println("reseived  "+ Welcome);
          System.out.println("reseived Pass  "+ Password);



        btnLogout = (Button) findViewById(R.id.btnLogout);

        btnLogout.setOnClickListener(new View.OnClickListener() {

            public void onClick(View arg0) {
                Intent login = new Intent(getApplicationContext(), MainActivity.class);
                login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(login);
                finish();

                System.exit(0);

            }
        });
        new DownloadTask().execute("http://stb.spades-tv.xyz:25461/player_api.php?username=" + Username + "&password=" + Password+"&action=get_vod_categories");

    }

Andthen

private class DownloadTask extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... params) {

        try {
            return downloadContent(params[0]);
        } catch (IOException e) {
            return "Unable to retrieve data. URL may be invalid.";
        }
    }

    @Override
    protected void onPostExecute(String result) {

        Toast.makeText(Welcome.this, result, Toast.LENGTH_LONG).show();
    }
}
    public String convertInputStreamToString(InputStream stream, int length) throws IOException, UnsupportedEncodingException {

        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));

        String line = "";
        Reader reader = null;

        String result = "";
        reader = new InputStreamReader(stream, "UTF-8");
        char[] buffer = new char[length];
        reader.read(buffer);

        while ((line = bufferedReader.readLine()) != null)
            result += line;

        stream.close();
        if (result != null) {

//TODO someting here 
        }
        else { System.out.println(" 404 "); }

        getinfos(result);
        return result;


       // return new String(buffer);
    }
    private String downloadContent(String myurl) throws IOException {



        InputStream is = null;
        int length = 500;

        try {
            URL url = new URL(myurl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(10000 /* milliseconds */);
            conn.setConnectTimeout(15000 /* milliseconds */);
            conn.setRequestMethod("GET");
            conn.setDoInput(true);
            conn.connect();
            int response = conn.getResponseCode();
            Log.d(TAG, "The response is: " + response);

            is = conn.getInputStream();

            // Convert the InputStream into a string
            String contentAsString = convertInputStreamToString(is, length);

             System.out.println("Received from VOD list :" + contentAsString);

            return contentAsString;
        } finally {
            if (is != null) {
                is.close();
            }
        }
    }

In this part i want to convert to Array

[] array and {} object right?

   public void getinfos (String  result)
    {

        try {


            JSONArray jsonArr = new JSONArray(result);

            for (int i = 0; i < jsonArr.length(); i++)
            {
                JSONObject jsonObj = jsonArr.getJSONObject(i);

         System.out.println(" My VOD List :" +jsonObj);
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

So odd thing is this see the first atergory_id im missing part of it? and I get this error?:

W/System.err: org.json.JSONException: Value egory_id" of type java.lang.String cannot be converted to JSONArray
W/System.err:     at org.json.JSON.typeMismatch(JSON.java:111)
W/System.err:     at org.json.JSONArray.<init>(JSONArray.java:96)
W/System.err:     at org.json.JSONArray.<init>(JSONArray.java:108)
W/System.err:     at ca.iptvbooster.testhttp.Welcome.getinfos(Welcome.java:185)
W/System.err:     at ca.iptvbooster.testhttp.Welcome.convertInputStreamToString(Welcome.java:129)
W/System.err:     at ca.iptvbooster.testhttp.Welcome.downloadContent(Welcome.java:156)
W/System.err:     at ca.iptvbooster.testhttp.Welcome.access$100(Welcome.java:41)
W/System.err:     at ca.iptvbooster.testhttp.Welcome$DownloadTask.doInBackground(Welcome.java:95)
W/System.err:     at ca.iptvbooster.testhttp.Welcome$DownloadTask.doInBackground(Welcome.java:89)
W/System.err:     at android.os.AsyncTask$2.call(AsyncTask.java:333)
W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:266)
W/System.err:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
W/System.err:     at java.lang.Thread.run(Thread.java:764)
I/System.out: Received from VOD list :egory_id":"195","category_name":"LINE OF DUTY SEASON 2","parent_id":"77"},..
mplungjan
  • 169,008
  • 28
  • 173
  • 236
techker
  • 189
  • 1
  • 10
  • https://stackoverflow.com/questions/245062/whats-the-difference-between-javascript-and-java – mplungjan Mar 18 '18 at 17:32
  • Your convertInputStreamToString has issues. You have 2 readers chomping at the stream (1) reader : InputStreamReader (which may be a partial read of stream) and then (2) bufferReader which will read to end. So based on the stack trace (1) chewed up some of the stream and then (2) got the rest which is malformed. The debugger is useful. –  Mar 18 '18 at 18:07
  • ah that could be thx i will check it out – techker Mar 18 '18 at 21:33

1 Answers1

0

Demonstrates a cleaned up version of 'convertInputStreamToString'which is the source of your parsing issues - see comment. Test code included. The 'getinfos' worked as you coded it.

  import android.util.Log;
  import org.json.*;
  import java.io.*;
  import java.nio.charset.Charset;

  public class TestJsonParse {

      public void test() {
          StringBuffer sb = new StringBuffer();
          sb.append("[ { 'category_id': '334', 'category_name': 'ENGLISH PREMIER LEAGUE VOD', 'parent_id': 0 }, ");
          sb.append("{ 'category_id': '456', 'category_name': 'ENGLISH PREMIER LEAGUE ROCKS', 'parent_id': 2 }]");
          InputStream stream = new ByteArrayInputStream(sb.toString().getBytes(Charset.forName("UTF-8")));
          try {
              convertInputStreamToString(stream);
          } catch (Exception e) {
              Log.e("TestJsonParse", "Issue with stream: "+e);
          }
      }

      /** @return null if errors reading/parsing stream. */
      public String convertInputStreamToString(InputStream stream) throws IOException {

          BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
          StringBuffer sb = new StringBuffer();
          String result = null;
          String line;
          while ((line = bufferedReader.readLine()) != null) {
              sb.append(line);
          }
          //https://stackoverflow.com/questions/1388602/do-i-need-to-close-both-filereader-and-bufferedreader
          bufferedReader.close();

          if (sb.length() > 0) {
              result = sb.toString();
              getinfos(result);
          }
          else {
              Log.e("TestJsonParse"," 404 ");
          }

          return result;
      }


      // Existing 'getinfos' worked as is...
   }