Android Open Source - binghamton_svc Launchpad Section Fragment






From Project

Back to project page binghamton_svc.

License

The source code is released under:

MIT License

If you think the Android project binghamton_svc listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

package Fragments;
//w  w  w  . ja v a2s . c  o  m
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;

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

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v4.app.Fragment;
import android.text.util.Linkify;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.github.chrzhang.R;

/**
 * Contains inner classes and is responsible for interacting with both
 * the Tumblr and Twitter API to fetch JSON data to be parsed and displayed.
 * @author Christopher Zhang
 */
public class LaunchpadSectionFragment extends Fragment 
{
  View rootView;
  ImageView showMeTheMoney;
  ImageView showMeTheMoney2;
  ImageView showMeTheMoney3;
  ImageView showMeTheMoney4;
  ImageView showMeTheMoney5;
  ImageView showMeTheMoney6;
  
  Bitmap bmp1;
  Bitmap bmp2;
  Bitmap bmp3;
  Bitmap bmp4;
  Bitmap bmp5;
  Bitmap bmp6;
  
  String imgurl1;
  String imgurl2; 
  String imgurl3; 
  String imgurl4; 
  String imgurl5; 
  String imgurl6; 
  
  final String URL = "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=binghamtonsvc&include_rts=1";
  final String APIKEY = "";
  final String APISECRET = "";
  
  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
  {
    rootView = inflater.inflate(R.layout.fragment_section_launchpad, container, false);
    
    showMeTheMoney = (ImageView) rootView.findViewById(R.id.iv1);
    showMeTheMoney2 = (ImageView) rootView.findViewById(R.id.iv2);
    showMeTheMoney3 = (ImageView) rootView.findViewById(R.id.iv3);
    showMeTheMoney4 = (ImageView) rootView.findViewById(R.id.iv4);
    showMeTheMoney5 = (ImageView) rootView.findViewById(R.id.iv5);
    showMeTheMoney6 = (ImageView) rootView.findViewById(R.id.iv6);
    
    Button btn_bearer_token = (Button) rootView.findViewById(R.id.bGetBearerToken);
    btn_bearer_token.setOnClickListener(new OnClickListener() 
    {
      @Override
      public void onClick(View v) 
      {
        new GetBearerTokenTask().execute();
      }
    });
    
    Button btn_facebook = (Button) rootView.findViewById(R.id.bFacebook);
    btn_facebook.setOnClickListener(new OnClickListener()
    {
      @Override
      public void onClick(View v)
      {
        Intent LaunchIntent = getActivity().getPackageManager().getLaunchIntentForPackage("com.facebook.katana");
        startActivity(LaunchIntent);
      }
    });    
    
    
    new Snag().execute();
    btn_bearer_token.performClick();
    return rootView;
  }
  
  public class Snag extends AsyncTask<Void, Void, Void>
  {
    @Override
    protected void onPostExecute(Void result)
    {
      new DownloadImageTask().execute();
    }

    @Override
    protected Void doInBackground(Void... params)
    {
      JSONObject jsonthing;
      try
      {
        jsonthing = readJsonFromUrl("");
        JSONArray posts = jsonthing.getJSONObject("response").getJSONArray("posts");
        ArrayList<String> urls = new ArrayList<String>();
        for(int i = 0; i < posts.length(); i++)
        {
            JSONArray photos = posts.getJSONObject(i).getJSONArray("photos");
            for(int j = 0; j < photos.length(); j++)
            {
                JSONObject photo = photos.getJSONObject(j);
                String url = photo.getJSONArray("alt_sizes").getJSONObject(1).getString("url");
                urls.add(url);
            }
        }
        imgurl1 = urls.get(0);
        imgurl2 = urls.get(1);
        imgurl3 = urls.get(2);
        imgurl4 = urls.get(3);
        imgurl5 = urls.get(4);
        imgurl6 = urls.get(5);
      }
      catch (Exception e)
      {
        e.printStackTrace();
      }
      return null;
    }
    
    private String readAll(Reader rd) throws IOException 
    {
      StringBuilder sb = new StringBuilder();
      int cp;
      while ((cp = rd.read()) != -1) 
      {
        sb.append((char) cp);
      }
      return sb.toString();
    }

    public JSONObject readJsonFromUrl(String url) throws IOException, JSONException 
    {
      InputStream is = new URL(url).openStream();
      try {
        BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
        String jsonText = readAll(rd);
        JSONObject json = new JSONObject(jsonText);
        return json;
      } 
      finally 
      {
        is.close();
      }
    }
  }
  
  // Inner class
  public class DownloadImageTask extends AsyncTask<Void, Void, Void>
  {
    
    protected Void doInBackground(Void... params)
    {
      loadImageFromNetwork();
      return null;
    }
    
    protected void onPostExecute(Void result)
    {
      showMeTheMoney.setImageBitmap(bmp1);
      showMeTheMoney2.setImageBitmap(bmp2);
      showMeTheMoney3.setImageBitmap(bmp3);
      showMeTheMoney4.setImageBitmap(bmp4);
      showMeTheMoney5.setImageBitmap(bmp5);
      showMeTheMoney6.setImageBitmap(bmp6);
      
       new CountDownTimer(3000, 1) 
       { 
           
          public void onTick(long millisUntilFinished) 
          { 
              HorizontalScrollView hv = (HorizontalScrollView) rootView.findViewById(R.id.hsv);
              hv.scrollTo((int) (2000 - millisUntilFinished), 0); 
          } 

          public void onFinish()
          { 
          } 
       }.start();
    }

    private void loadImageFromNetwork() 
    {
      try
      {
        bmp1 = BitmapFactory.decodeStream((InputStream)new URL(imgurl1).getContent());
        bmp2 = BitmapFactory.decodeStream((InputStream)new URL(imgurl2).getContent());
        bmp3 = BitmapFactory.decodeStream((InputStream)new URL(imgurl3).getContent());
        bmp4 = BitmapFactory.decodeStream((InputStream)new URL(imgurl4).getContent());
        bmp5 = BitmapFactory.decodeStream((InputStream)new URL(imgurl5).getContent());
        bmp6 = BitmapFactory.decodeStream((InputStream)new URL(imgurl6).getContent());
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }
  
  // Inner Class
  protected class GetBearerTokenTask extends AsyncTask<Void, Void, String> 
  {
      @Override
      protected String doInBackground(Void... params) 
      {
        try
        {
          DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
          HttpPost httppost = new HttpPost("https://api.twitter.com/oauth2/token");
          
          String apiString = APIKEY + ":" + APISECRET;
          String authorization = "Basic " + Base64.encodeToString(apiString.getBytes(), Base64.NO_WRAP);
      
          httppost.setHeader("Authorization", authorization);
          httppost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
          httppost.setEntity(new StringEntity("grant_type=client_credentials"));
      
          InputStream inputStream = null;
          HttpResponse response = httpclient.execute(httppost);
          HttpEntity entity = response.getEntity();
      
          inputStream = entity.getContent();
          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");
          }
          return sb.toString();
        }
        catch (Exception e)
        {
          Log.e("GetBearerTokenTask", "Error:" + e.getMessage());
          return null;
        }
      }
  
    @Override
    protected void onPostExecute(String jsonText)
    {
      try 
      {
        JSONObject root = new JSONObject(jsonText);
        String bearer_token = root.getString("access_token");  
        new GetFeedTask().execute(bearer_token, URL);
      }
      catch (Exception e)
      {
        Log.e("GetBearerTokenTask", "Error:" + e.getMessage());
      }
    }
  }

  // Inner class
  protected class GetFeedTask extends AsyncTask<String, Void, String> 
  {
    @Override
    protected String doInBackground(String... params) 
    {
      try 
      {
        DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
        HttpGet httpget = new HttpGet(params[1]);
        httpget.setHeader("Authorization", "Bearer " + params[0]);
        httpget.setHeader("Content-type", "application/json");
    
        InputStream inputStream = null;
        HttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();
    
        inputStream = entity.getContent();
        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");
        }
        return sb.toString();
      }
      catch (Exception e)
      {
        Log.e("GetFeedTask", "Error:" + e.getMessage());
        return null;
      }
    }
  
    @Override
    protected void onPostExecute(String jsonText)
    {
      try 
      {
        LinearLayout ll = (LinearLayout) rootView.findViewById(R.id.linearloftweets);
        if(((LinearLayout) ll).getChildCount() > 0) 
          ((LinearLayout) ll).removeAllViews(); 
        ArrayList<String> tweetList = new ArrayList<String>();
        JSONArray yourjsonarray = new JSONArray(jsonText);
        for(int i =0;i<yourjsonarray.length();i++)
        {
        String tweet =yourjsonarray.getJSONObject(i).getString("text");
        
        tweetList.add(tweet);
        }
        for (int i = 0; i < tweetList.size(); i++)
        {
            TextView temp = new TextView(getActivity());
            temp.setTextSize(18);
            temp.setAutoLinkMask(Linkify.ALL);
            temp.setText(tweetList.get(i));
            temp.setTypeface(Typeface.SERIF);
            if (i % 2 == 0)
              temp.setBackgroundColor(Color.parseColor("#78AB46"));
            else
              temp.setBackgroundColor(Color.WHITE);
            temp.setPadding(10, 10, 10, 10);
            ll.addView(temp);
        }
      }
      catch (Exception e)
      {
        Log.e("GetFeedTask", "Error:" + e.getMessage());
      }
    }
  }  
}




Java Source Code List

Fragments.AboutSectionFragment.java
Fragments.ContactSectionFragment.java
Fragments.EventsSectionFragment.java
Fragments.IsOnlineDialogFragment.java
Fragments.LaunchpadSectionFragment.java
Fragments.SignupSectionFragment.java
Parsers.GetEBoard.java
Parsers.GetMembershipInfo.java
Parsers.GetMissionStatement.java
Parsers.GetVolunteerHours.java
com.github.chrzhang.AboutAdapter.java
com.github.chrzhang.MainActivity.java
com.github.chrzhang.SplashScreen.java