user3669142
user3669142

Reputation: 11

Instagram feed search android

I need some help on Instagram api in android development, i need to search feeds or tags of Instagram in my app, is any one have suggestion about on it? or please provide links of tutorial

Advance thanks

Upvotes: 1

Views: 4653

Answers (2)

AMIT BHATNAGAR
AMIT BHATNAGAR

Reputation: 53

package com.pgd.Fragments;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.koushikdutta.async.future.FutureCallback;
import com.koushikdutta.ion.Ion;
import com.pgd.Adepters.InstagramTimelineAdapter;
import com.pgd.Beans.InstagramBeans;
import com.pgd.R;
import com.pgd.SocialLogin.Params;

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

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.zip.GZIPInputStream;

/**
 * Created by admin on 9/26/2017.
 */
public class InstagramTimelineFragment extends Fragment {

    public static final String API_AUTH_URL = "https://instagram.com/oauth/authorize/?";
    public static final String API_ACCESS_TOKEN_URL = "https://api.instagram.com/oauth/access_token";
    public static final String API_BASE_URL = "https://api.instagram.com/v1";

    public String CLIENT_ID = "8c1e17fd79e1402e915d94c1f05c5c3c";
    public String CLIENT_SECRET = "8885809e2b934647bedcec7068ea3e78";
    public String REDIRECT_URL = "https://stackoverflow.com/users/6286004/amit-bhatnagar";
    String username = "";
    String fullName = "";
    String profilePicture = "";
    String accessToken = "";
    String id = "";

    private WebView _webView;
    private LinearLayout _loadProgressLayout;
    private ProgressBar _loadProgressBar;
    InstagramBeans instagramBeansList;
    InstagramTimelineAdapter instagramTimelineAdapter;
    private RecyclerView recyclerView;
    public static final String InstagramTimelineFragment = "InstagramTimelineFragment";

    public static InstagramTimelineFragment newInstance(int page) {
        Bundle args = new Bundle();
        args.putInt(InstagramTimelineFragment, page);
        InstagramTimelineFragment fragment = new InstagramTimelineFragment();
        fragment.setArguments(args);

        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.instagram_timeline_list, container, false);

        recyclerView = (RecyclerView) view.findViewById(R.id.insta_recyclerView);
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(mLayoutManager);

        initWebView(view);
        return view;
    }


    private void initWebView(View view) {
        _loadProgressBar = (ProgressBar) view.findViewById(R.id.loadProgressBar);
        _loadProgressLayout = (LinearLayout) view.findViewById(R.id.loadProgressLayout);

        _webView = (WebView) view.findViewById(R.id.webView);
        _webView.getSettings().setJavaScriptEnabled(true);
        _webView.clearCache(true);
        _webView.setWebViewClient(new InstagramWebViewClient());
        _webView.setWebChromeClient(new InstagramWebChromeClient());

        CookieSyncManager.createInstance(getActivity());
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.removeAllCookie();
        _webView.loadUrl(getCodeRequest(CLIENT_ID, REDIRECT_URL));


    }

    public String authorize(String clientId, String clientSecret, String redirectUrl, String code) throws IOException, JSONException {
        Params params = new Params();
        params.put("client_id", clientId);
        params.put("client_secret", clientSecret);
        params.put("redirect_uri", redirectUrl);
        params.put("grant_type", "authorization_code");
        params.put("code", code);
        JSONObject rootJson = sendRequest(API_ACCESS_TOKEN_URL, params, Request.POST);
        JSONObject userJson = rootJson.getJSONObject("user");

        id = userJson.getString("id");
        username = userJson.optString("username");
        fullName = userJson.optString("full_name");
        profilePicture = userJson.optString("profile_picture");
        accessToken = rootJson.optString("access_token");

        Log.d("name", username);

        return accessToken;
    }

    public JSONObject sendRequest(String url, Params params, Request request) throws IOException, JSONException {
        String signedUrl = getSignedUrl(url, params, request);
        String body = "";
        if (request == Request.POST)
            body = params.getParamsStringUtf8();
        System.out.println("Tag" + " url : " + signedUrl);
        if (body.length() != 0)
            System.out.println("Tag" + " body : " + body);
        String response = "";
        for (int i = 1; i <= 3; ++i) {
            try {
                if (i != 1)
                    System.out.println("tag" + " try send = " + i);
                response = sendDummyRequest(signedUrl, body, request);
                break;
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
//        JSONObject rootJSON = new JSONObject(response);
        JSONObject rootJSON = (JSONObject) new JSONTokener(response).nextValue();
        return rootJSON;
    }

    public enum Request {
        GET,
        POST
    }

    private String sendDummyRequest(String url, String body, Request request) throws IOException {
        HttpURLConnection connection = null;
        try {
            connection = (HttpURLConnection) new URL(url).openConnection();
            connection.setConnectTimeout(10000);
            connection.setReadTimeout(10000);
            connection.setUseCaches(false);
            connection.setDoInput(true);
//            connection.setRequestProperty("Content-Type", "text/plain; charset=utf-8");
            if (request == Request.GET) {
                connection.setDoOutput(false);
                connection.setRequestMethod("GET");
            } else if (request == Request.POST) {
                connection.setDoOutput(true);
                connection.setRequestMethod("POST");
            }
            if (false)
                connection.setRequestProperty("Accept-Encoding", "gzip");
            if (request == Request.POST)
                connection.getOutputStream().write(body.getBytes("utf-8"));
            int code = connection.getResponseCode();
            System.out.println("TAG" + " responseCode = " + code);
            //It may happen due to keep-alive problem http://stackoverflow.com/questions/1440957/httpurlconnection-getresponsecode-returns-1-on-second-invocation
            if (code == -1)
                throw new IOException();
            //может стоит проверить на код 200
            //on error can also read error stream from connection.
            InputStream inputStream = new BufferedInputStream(connection.getInputStream(), 8192);
            String encoding = connection.getHeaderField("Content-Encoding");
            if (encoding != null && encoding.equalsIgnoreCase("gzip"))
                inputStream = new GZIPInputStream(inputStream);
            String response = convertStreamToString(inputStream);
            System.out.println("TAG" + " response = " + response);

            return response;
        } finally {
            if (connection != null)
                connection.disconnect();
        }
    }

    private String getSignedUrl(String url, Params params, Request request) {
        String signedUrl = url + params.getEndpoint();
        if (request == Request.GET) {
            String args = params.getParamsStringUtf8();
            return signedUrl + "?" + args;
        }
        return signedUrl;
    }

    public String convertStreamToString(InputStream is) throws IOException {
        InputStreamReader r = new InputStreamReader(is);
        StringWriter sw = new StringWriter();
        char[] buffer = new char[1024];
        try {
            for (int n; (n = r.read(buffer)) != -1; )
                sw.write(buffer, 0, n);
        } finally {
            try {
                is.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
        return sw.toString();
    }

    public class InstagramWebViewClient extends WebViewClient {
        @SuppressWarnings("deprecation")
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url.startsWith(REDIRECT_URL)) {
                final Intent intent = new Intent();
                if (url.contains("code")) {
                    String temp[] = url.split("=");
                    final String code = temp[1];
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                accessToken = authorize(CLIENT_ID, CLIENT_SECRET, REDIRECT_URL, code);
                                getActivity().runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        //   getFeed();
                                        // userNameTextView.setText(username);
                                        //userFullnameTextView.setText(fullName);
                                        //Picasso.with(getActivity()).load(profilePicture).into(userImageView);
                                        _webView.setVisibility(View.GONE);
                                        recyclerView.setVisibility(View.VISIBLE);
                                        getFeed();
                                    }
                                });
                            } catch (final Exception e) {
                                e.printStackTrace();
                                getActivity().runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        intent.putExtra("error", e.getMessage());
                                        // setResult(Activity.RESULT_OK, intent);
                                        // finish();
                                    }
                                });
                            }
                        }
                    }).start();
                } else if (url.contains("error")) {
                    String temp[] = url.split("=");
                    String error = temp[temp.length - 1];
                    intent.putExtra("error", error);
                    // setResult(Activity.RESULT_OK, intent);
                    // finish();
                }
                return true;
            }
            return false;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            _loadProgressLayout.setVisibility(View.VISIBLE);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            _loadProgressLayout.setVisibility(View.GONE);
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            _loadProgressLayout.setVisibility(View.GONE);
            Toast.makeText(getActivity(),
                    getString(R.string.page_load_error),
                    Toast.LENGTH_LONG).show();
            Intent intent = new Intent();
            intent.putExtra("error", description);
            // setResult(Activity.RESULT_OK, intent);
            //finish();
        }
    }

    public String getCodeRequest(String clientId, String redirectUrl) {
        return API_AUTH_URL + "client_id=" + clientId + "&redirect_uri=" + redirectUrl + "&response_type=code";
    }

    private class InstagramWebChromeClient extends WebChromeClient {

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
            _loadProgressBar.setProgress(newProgress);
        }
    }

    public void getFeed() {
        try {

            URL example = new URL("https://api.instagram.com/v1/users/self/media/recent?access_token="
                    + accessToken);

            Ion.with(getActivity())
                    .load(String.valueOf(example))
                    .asJsonObject()
                    .setCallback(new FutureCallback<JsonObject>() {
                        @Override
                        public void onCompleted(Exception e, JsonObject result) {
                            // do stuff with the result or error
                            String response = result.toString();
                            Log.d("res_feed", response);

                            Gson gson = new Gson();
                            instagramBeansList = gson.fromJson(response, InstagramBeans.class);


                            if (instagramBeansList.getData().size() > 0) {
                                instagramTimelineAdapter = new InstagramTimelineAdapter(getActivity(), instagramBeansList.getData());

                                recyclerView.setAdapter(instagramTimelineAdapter);

                            } else {
                                Toast.makeText(getActivity(), "Data in empty", Toast.LENGTH_SHORT).show();
                            }


                        }
                    });

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

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);

        if (isVisibleToUser) {

        } else {

        }
    }
}

Upvotes: 0

Chrisport
Chrisport

Reputation: 3146

You can find all you need on the instagram developer page: http://instagram.com/developer/endpoints/tags/

Instagram provides a RESTful API, so you will make simple HTTP-calls on URLs with your specified parameters (like a tag you want to search for). The response will be in JSON-format, from which you can extract the desired information such as image urls, user-name, etc.

With the bold parts above you have all you need reach your goal. Just google for these parts, here is a tutorial for implementing REST in Android. Also see this question on StackOverflow to reach a more advanced implementation: Android rest client sample. Also Vogella's tutorial is great and shows you both parts, the request call and the response parsing.

Here is a function that creates the URl to search for a certain hashtag:

 public static String getSearchUrl(String hashtag) {
    return "https://api.instagram.com/v1/tags/" + hashtag
            + "/media/recent?client_id=" + Constants.CLIENT_ID;
 }

Upvotes: 2

Related Questions