Sunday, 3 December 2017

JSON parsing and Displaying in ListView

1. manisfests.xml


<uses-permission android:name="android.permission.INTERNET"/>

2.mainActivity.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ProgressBar
        android:id="@+id/progressBar"
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:visibility="invisible" />

    <ListView
        android:id="@+id/listView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true" />

</RelativeLayout>

3.activity_detail

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".detail">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true" />
</RelativeLayout>

4.MainActivity.java

package com.arham.csdevbin.apidemo;

  import android.content.Intent;
  import android.os.AsyncTask;
  import android.os.Bundle;
  import android.support.v7.app.AppCompatActivity;
  import android.view.View;
  import android.widget.AdapterView;
  import android.widget.ArrayAdapter;
  import android.widget.ListView;
  import android.widget.ProgressBar;
  import java.util.ArrayList;
  import java.util.List;

  public class MainActivity extends AppCompatActivity {
 
    private ProgressBar pb;
    private ListView lv;
    private List<String> contactList;

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

        contactList = new ArrayList<>();
        pb = (ProgressBar) findViewById(R.id.progressBar);
        lv = (ListView) findViewById(R.id.listView);

        /*fetch data from the web*/
        Fetcher fetcher = new Fetcher();
        fetcher.execute("https://newsapi.org/v2/top-headlines?sources=techcrunch&apiKey=
b63009d5896f4fe19251a328a69c1835");

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String name = (String) lv.getItemAtPosition(position);
                Intent intent = new Intent(MainActivity.this, detail.class);
                intent.putExtra("name", name);
                startActivity(intent);
            }
        });
    }

    public void ContactAdapter(String json) {
        contactList = JsonParser.Parse(json);

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
              android.R.layout.simple_list_item_1, contactList); 
       lv.setAdapter(adapter);
    }

    //AsyncTask
    private class Fetcher extends AsyncTask<String, String, String> {
        @Override
        protected void onPreExecute() {
            pb.setVisibility(View.VISIBLE);
        }

        @Override 
       protected String doInBackground(String... params) {
            String data = HttpManger.getData(params[0]);
            return data;

        }
        @Override
        protected void onPostExecute(String s) {
            ContactAdapter(s);
            pb.setVisibility(View.INVISIBLE);
        }
    }
}

 5.JsonParser.java

package com.arham.csdevbin.apidemo;

  import android.util.Log;
  import org.json.JSONArray;
  import org.json.JSONException;
  import org.json.JSONObject;
  import java.util.ArrayList;
  import java.util.List;

  public class JsonParser {
    public static List<String> Parse(String json) {
        try {
            JSONObject response = new JSONObject(json);
            JSONArray articles = response.optJSONArray("articles");
            List<String> contactList = new ArrayList<>();
 
            for (int i = 0; i < articles.length(); i++) {
                JSONObject article = articles.optJSONObject(i);
                contactList.add(article.getString("title"));
            }
            return contactList;
        } catch (JSONException e) {
            e.printStackTrace();
            return null;
        }
    }
}

6.HttpManger.java

package com.arham.csdevbin.apidemo;
  import java.io.BufferedReader;
  import java.io.IOException;
  import java.io.InputStreamReader;
  import java.net.HttpURLConnection;
  import java.net.URL;

  public class HttpManger {

    public static String getData(String stringUrl) {
        BufferedReader reader = null;

        try {
            URL url = new URL(stringUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            StringBuilder sb = new StringBuilder();
            InputStreamReader is = new InputStreamReader(connection.getInputStream());

            reader = new BufferedReader(is);
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line).append("\n");
            }
            return sb.toString();

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

        } finally {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

7.detail.java

package com.arham.csdevbin.apidemo;
  import android.os.Bundle;
  import android.support.v7.app.AppCompatActivity;
  import android.widget.TextView;

  public class detail extends AppCompatActivity {

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

        //store the text in variable
        String name = getIntent().getExtras().getString("name");
        //display text
        tv.setText(name);
    }
}



No comments:

Post a Comment