net.noviden.android.shoutout.MainScreen.java Source code

Java tutorial

Introduction

Here is the source code for net.noviden.android.shoutout.MainScreen.java

Source

/**
 ShoutOut : an app for anonymous broadcasts
 Copyright (C) 2014 Tristan Kernan
    
 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.
    
 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
    
 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package net.noviden.android.shoutout;

import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;

import com.google.gson.Gson;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Array;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class MainScreen extends ListActivity {

    private String mJsonPostsArray;
    private String[] mStringPostsArray;
    private int mInterval = 10000;
    private Handler mHandler;

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

        mHandler = new Handler();
        mJsonPostsArray = null;
        mStringPostsArray = null;

        refreshPosts();

        startRepeatingTask();

    }

    Runnable mBackgroundRefresh = new Runnable() {
        @Override
        public void run() {
            refreshPosts();
            mHandler.postDelayed(mBackgroundRefresh, mInterval);
        }
    };

    void startRepeatingTask() {
        mBackgroundRefresh.run();
    }

    void stopRepeatingTask() {
        mHandler.removeCallbacks(mBackgroundRefresh);
    }

    @Override
    public void onResume() {
        super.onResume();

        refreshPosts();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main_screen, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        switch (item.getItemId()) {
        case R.id.action_new_post:
            openNewPost();
            return true;
        case R.id.action_refresh_posts:
            refreshPosts();
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }

    /**
     * refresh posts
     */

    private void refreshPosts() {

        getPosts();

        if (mStringPostsArray != null) {
            ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.rowlayout, R.id.label,
                    mStringPostsArray);

            setListAdapter(adapter);
        }
    }

    public void getPosts() {

        DownloadPostsAsyncTask mGetPosts = new DownloadPostsAsyncTask();

        mGetPosts.execute();

        Gson gson = new Gson();
        Post[] mPostsArray = null;
        mPostsArray = gson.fromJson(mJsonPostsArray, Post[].class);

        if (mPostsArray != null) {
            mStringPostsArray = new String[mPostsArray.length];
            for (int i = 0; i < mPostsArray.length; i++) {
                mStringPostsArray[mPostsArray.length - i - 1] = mPostsArray[i].toString();
            }
        }

    }

    /**
     * start new post activity
     */
    private void openNewPost() {
        Intent mNewPostIntent = new Intent(this, NewPostScreen.class);
        startActivity(mNewPostIntent);
    }

    private class DownloadPostsAsyncTask extends AsyncTask<Void, Void, Void> {
        @Override
        protected Void doInBackground(Void... params) {
            Log.d("interwebs", "debug point 1");
            try {
                HttpClient httpclient = new DefaultHttpClient();
                URI myURI = new URI("http", null, "INSERT IP ADDRESS", 3000, "/api/getPosts", null, null);
                Log.d("interwebs", myURI.toString());
                HttpResponse response = httpclient.execute(new HttpGet(myURI));
                StatusLine statusLine = response.getStatusLine();
                Log.d("interwebs", "debug point 2");
                if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
                    ByteArrayOutputStream out = new ByteArrayOutputStream();
                    response.getEntity().writeTo(out);
                    out.close();
                    String responseString = out.toString();
                    Log.d("interwebs", responseString);

                    mJsonPostsArray = responseString;

                    return null;

                } else {
                    //Closes the connection.
                    response.getEntity().getContent().close();
                    Log.d("interwebs", "debug point 3");
                    Log.d("interwebs", statusLine.getReasonPhrase());
                    throw new IOException(statusLine.getReasonPhrase());
                }
            } catch (ClientProtocolException e) {
                // do nothing, login failed
                //            Log.d("interwebs", e.getMessage());
                Log.d("interwebs", "client protocol exception");
            } catch (IOException e) {
                Log.d("interwebs", "io exception");
            } catch (URISyntaxException e) {
                Log.d("interwebs", "Malformed URI");
            }

            Log.d("interwebs", "Failed to connect");

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            return;
        }
    }
}