app.hacked.ChatFragment.java Source code

Java tutorial

Introduction

Here is the source code for app.hacked.ChatFragment.java

Source

/*
 * Copyright (C) 2013 - Gareth Llewellyn
 *
 * This file is part of the Unofficial HackedIO Android App https://github.com/NetworksAreMadeOfString/HackedIO-Android-App
 *
 * This app is unofficial. The "Hacked.io" logo is copyright (and maybe even a trademark of) Telefnica UK Limited.
 * The author of this app is not affiliated with Telefnica UK Limited, The Lab ( https://thelab.o2.com/ ) or
 * Geeks of London ( http://geeksoflondon.com/ ) although the author <strong>is</strong> an attendee.
 *
 * 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 app.hacked;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.AlertDialog;
import android.content.*;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.List;

public class ChatFragment extends ListFragment {
    RequestQueue queue = null;
    EditText Message = null;
    Account[] accounts = null;
    List<ChatMessage> chatMessages;
    ChatAdapter adapter = null;
    public static String BROADCAST_ACTION = "io.hacked.android.broadcast.chatmsg";
    private View progressBar = null;
    SharedPreferences settings = null;
    private boolean canPost = false;

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.e("onRecieve",
                    "Got a broadcast " + intent.getStringExtra("name") + " " + intent.getStringExtra("msg"));
            if (null != adapter) {
                adapter.ChatMessages
                        .add(new ChatMessage(intent.getStringExtra("name"), intent.getStringExtra("msg")));
                adapter.notifyDataSetChanged();
            }
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        queue = Volley.newRequestQueue(getActivity());
        AccountManager am = AccountManager.get(getActivity());
        accounts = am.getAccountsByType("com.google");
        //chatMessages = new ArrayList<ChatMessage>();
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        adapter = new ChatAdapter(getActivity());
        setListAdapter(adapter);

        String url = "http://hackedioapp.networksaremadeofstring.co.uk/chats.php";

        JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.GET, url, null,
                new Response.Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            if (response.has("success") && response.getBoolean("success") && response.has("msgs")) {
                                Log.e("response", response.toString());

                                JSONArray msgs = response.getJSONArray("msgs");
                                int size = msgs.length();
                                for (int i = 0; i < size; i++) {
                                    JSONObject chatJSON = msgs.getJSONObject(i);

                                    adapter.ChatMessages.add(
                                            new ChatMessage(chatJSON.getString("UID"), chatJSON.getString("Msg")));
                                }

                                adapter.notifyDataSetChanged();
                            } else {
                                Toast.makeText(getActivity(), "An Error Was encountered", Toast.LENGTH_SHORT)
                                        .show();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            Toast.makeText(getActivity(), "An Error Was encountered", Toast.LENGTH_SHORT).show();
                        }

                    }
                }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        // TODO Auto-generated method stub
                        Toast.makeText(getActivity(), "An Error Was encountered", Toast.LENGTH_SHORT).show();
                    }
                });

        queue.add(jsObjRequest);

        SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getActivity());
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.chat_fragment, null);
        Message = (EditText) view.findViewById(R.id.chatText);

        ((ImageButton) view.findViewById(R.id.sendButton)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!canPost) {
                    //Toast.makeText(getActivity(), "You need to agree to the Hacked.io Terms of Attendance before posting", Toast.LENGTH_SHORT).show();
                    //return;
                    if (settings.getBoolean("agreetoChat", false)) {
                        canPost = true;
                    } else {
                        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                        // Add the buttons
                        builder.setPositiveButton("I agree", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                SharedPreferences.Editor editor = PreferenceManager
                                        .getDefaultSharedPreferences(getActivity()).edit();
                                editor.putBoolean("agreetoChat", true);
                                editor.commit();
                                dialog.dismiss();
                                canPost = true;
                            }
                        });
                        builder.setNegativeButton("Nope", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                SharedPreferences.Editor editor = PreferenceManager
                                        .getDefaultSharedPreferences(getActivity()).edit();
                                editor.putBoolean("agreetoChat", false);
                                editor.commit();
                                dialog.dismiss();
                                canPost = false;
                            }
                        });

                        builder.setMessage(getString(R.string.ChatTandC));

                        // Create the AlertDialog
                        AlertDialog dialog = builder.create();
                        dialog.setCancelable(false);
                        dialog.show();
                    }
                    return;
                }

                progressBar.setVisibility(View.VISIBLE);
                Message.setEnabled(false);

                final String msg = Message.getText().toString();
                JSONObject post = new JSONObject();
                try {
                    try {
                        post.put("name", accounts[0].name);
                    } catch (Exception e) {
                        e.printStackTrace();
                        post.put("name", "Anon");
                    }
                    post.put("msg", msg);
                    post.put("auth", API.md5(API.BETTER_THAN_NOTHING_STUFF_TO_PREVENT_INJECTION_ATTEMPTS + msg));
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(getActivity(),
                            "An Error Was encountered parsing the entered details: " + e.getMessage(),
                            Toast.LENGTH_SHORT).show();
                    return;
                }

                JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST,
                        "http://hackedioapp.networksaremadeofstring.co.uk/addchatmsg.php", post,
                        new Response.Listener<JSONObject>() {
                            @Override
                            public void onResponse(JSONObject response) {
                                Log.e("response", response.toString());
                                try {
                                    if (response.has("success") && response.getBoolean("success")) {
                                        //Toast.makeText(getActivity(), "Project added successfully!", Toast.LENGTH_SHORT).show();
                                        //adapter.ChatMessages.add(new ChatMessage(accounts[0].name,msg));
                                        //adapter.notifyDataSetChanged();
                                        Message.setText("");
                                        progressBar.setVisibility(View.INVISIBLE);
                                        Message.setEnabled(true);
                                    } else {
                                        Toast.makeText(getActivity(), "An Error Was encountered",
                                                Toast.LENGTH_SHORT).show();
                                        Message.setEnabled(true);
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }, new Response.ErrorListener() {

                            @Override
                            public void onErrorResponse(VolleyError error) {
                                // TODO Auto-generated method stub
                                Toast.makeText(getActivity(), "An Error Was encountered: " + error.getMessage(),
                                        Toast.LENGTH_SHORT).show();
                            }
                        });

                queue.add(jsObjRequest);
            }
        });

        progressBar = view.findViewById(R.id.progressBar);

        return view;
    }

    /*@Override
    public void onAttach(Activity activity)
    {
    super.onAttach(activity);
        
    //Register broadcast receiver
    }
        
    @Override
    public void onDetach()
    {
    super.onDetach();
        
    //Unregister broadcast reciever
    }*/

    @Override
    public void onResume() {
        super.onResume();
        Log.e("onResume", "Registering broadcast");
        IntentFilter filter = new IntentFilter();
        filter.addAction(BROADCAST_ACTION);
        getActivity().registerReceiver(receiver, filter);
    }

    @Override
    public void onPause() {
        super.onPause();
        Log.e("onResume", "UNregistering broadcast");
        getActivity().unregisterReceiver(receiver);
    }
}