Explanation Needed In Android Code To Parse two different JSON Data from URL

  • Replies:0
  • OpenNot stickiedUnanswered
  • Forum posts: 1

Jun 13, 2017 5:34:18 PM via Website

Good day Android developers.

please i need inputs on how to display posts and comments on a new activity page i am presently working with json data from

jsonplaceholder-typicode,com/posts

sample json output for posts

{
"UserId": 1,
"Id": 1,
"Title": "to provide or to reject the blind are welcome option to find"
"Body": "And it takes \ nsuscipit follow accepted lightly with \ nreprehenderit discomfort may be the entire \ nnostrum of the things that happens is that they are extremely"
}

and

jsonplaceholder.typicode-com/comments

sample json output for comments

{
"postId": 1,
"id": 1,
"name": "id labore ex et quam laborum",
"email": "Eliseo@gardner.biz",
"body": "laudantium enim quasi est quidem magnam voluptate ipsam eos\ntempora quo necessitatibus\ndolor quam autem quasi\nreiciendis et nam sapiente accusantium"
}

This is my code below which displays post on a new list item. and when the list is clicked it takes the user to a new activity displaying just the title and the body.

I want to to be able to click a list item and it would display post title and comments in a new activity. any ideas please.

My Apologies for the long code i only want you all to see the big picture.

please find main activity code below

package com.example.crystaldave.jsontest;


import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
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.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;

public class MainActivity extends AppCompatActivity {

    JSONObject jsonPart;
    JSONArray jsonArray;
    ArrayList<String> titles = new ArrayList<String>();
    ArrayList<String> body = new ArrayList<String>();

    ArrayAdapter arrayAdapter;
    ProgressDialog dialog;


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

        ListView listView = (ListView) findViewById(R.id.listView);
        arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, titles);
        listView.setAdapter(arrayAdapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //Log.i("ArticleUrl", urls.get(position));

                // Intent i = new Intent(MainActivity.this, YourArticle.class);
                Intent i = new Intent(getApplicationContext(), YourArticle.class);
                // i.putExtra("data", jsonArray.toString());
                i.putExtra("data1", titles.get(position));
                i.putExtra("body1", body.get(position));

                i.putExtra("data", jsonPart.toString());
                // i.putExtra("articleTitle", body.get(position));
                //* i.putExtra("content", content.get(position));
                startActivity(i);
            }
        });

        dialog = new ProgressDialog(this);
        dialog.setMessage("Loading....");
        dialog.show();

        DownloadTask task = new DownloadTask();

        try {

            //bc this is updated listview is run twice. we put result in main task download
            String content = task.execute("https:-//jsonplaceholder.typicode.com/posts").get();

            Log.i("content", content);


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

    }


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

        @Override
        protected String doInBackground(String... urls) {
            String result = "";
            URL url;
            HttpURLConnection urlConnection = null;

            try {
                url = new URL(urls[0]);
                urlConnection = (HttpURLConnection) url.openConnection();
                InputStream in = urlConnection.getInputStream();
                InputStreamReader reader = new InputStreamReader(in);

                int data = reader.read();
                String articleInfo = "";

                while (data != -1) {
                    char current = (char) data;
                    articleInfo += current;
                    data = reader.read();
                }
                jsonArray = new JSONArray(articleInfo);
                Log.i("jsonObj", jsonArray.toString());
                for (int i = 0; i < jsonArray.length(); i++) {
                    jsonPart = jsonArray.getJSONObject(i);

                    String articleTitle = jsonPart.getString("title");
                    //String articleBody = jsonPart.getString("title");


                    //converted jsonPart.getString("title") to articleTitle
                    //Log.i("title", jsonPart.getString("title"));
                    Log.i("title", articleTitle);
                    // Log.i("body", jsonPart.getString("body"));

                    titles.add(jsonPart.getString("title"));
                    body.add(jsonPart.getString("body"));
                    dialog.dismiss();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            return result;
        }


    }
}

Activity Page

package com.example.crystaldave.jsontest;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.widget.TextView;

import org.json.JSONException;
import org.json.JSONObject;

public class YourArticle extends AppCompatActivity {
    TextView textView;
    TextView bodyView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_your_article);
        textView = (TextView) findViewById(R.id.textView);
        bodyView = (TextView) findViewById(R.id.bodyView);

        // String data = getIntent().getStringExtra("data");
        Intent i = getIntent();
        String data1 = i.getStringExtra("data1");
        String body1 = i.getStringExtra("body1");
        textView.setText(data1);
        bodyView.setText(body1);

        Log.i("data", data1);

        // try {
        // JSONObject jsonPart = new JSONObject(data);
        //String tView = jsonPart.getString("title");
        // textView.setText(tView);
        // Log.i("data", data1);

        // } catch (JSONException e) {
        //e.printStackTrace();
        //}
        //Intent i = getIntent();
        //i.getStringExtra("articleTitle");
        //i.getStringExtra("articleBody");
    }
        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            switch (item.getItemId()) {
                case android.R.id.home:
                    onBackPressed();
                    return true;
            }
            return super.onOptionsItemSelected(item);
    }
}

Thanks