Java tutorial
/* Copyright Vance Anderson 2015 @author Vance Anderson @version 04/2015 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package edu.asu.bsse.vtanders.finalproject; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.res.Configuration; import android.os.AsyncTask; import android.os.Handler; import android.os.Looper; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.text.method.ScrollingMovementMethod; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; import org.json.JSONArray; import org.json.JSONObject; import org.w3c.dom.Text; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.util.ArrayList; import java.util.List; import java.util.Timer; import java.util.TimerTask; public class MainActivity extends ActionBarActivity { ListView userList; ListView channelList; TextView chatHistory; EditText messageEditor; Timer timer; Socket socket; OutputStream out; InputStream in; ArrayList<String> users; ArrayAdapter<String> userListAdapter; final String HIST_CONSTANT = "14159"; public static final int FOUR_KB = 4096; //String host = "192.241.214.38"; //int port = 11001; byte input[]; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); messageEditor = (EditText) findViewById(R.id.message_editor); users = new ArrayList<String>(); // users.add("Gabe"); // users.add("Alex"); // users.add("Hillary"); // users.add("Vance"); userListAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, users); userList = (ListView) findViewById(R.id.user_list); userList.setAdapter(userListAdapter); ArrayList<String> channels = new ArrayList<String>(); channels.add("Android Project"); channels.add("Webapp Group"); channels.add("Help"); channels.add("Misc"); ArrayAdapter<String> channelListAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, channels); //corresponds to the commented out stuff in the layout // channelList = (ListView)findViewById(R.id.channel_list); // channelList.setAdapter(channelListAdapter); chatHistory = (TextView) findViewById(R.id.chat_history); // setup up connection info Button sendButton = (Button) findViewById(R.id.button_send); sendButton.setOnClickListener(new SendListener(messageEditor)); // StringBuilder sb = new StringBuilder(); // sb.append("08:40 Gabe: Isn't this chat service really cool?\n") // .append("08:41 Alex: It certainly is. Whoever developed this for us is pretty awesome.\n") // .append("08:41 Hillary: I agree. It's a pretty simplistic approach and it keeps our productivity high!\n") // .append("08:45 Vance: Thanks guys. I think it's pretty cool, too. Get back to work please\n") // .append("08:51 Alex: @Gabe, do you wanna do this PR real quick? I need to get this issue out of code review at some point today\n") // .append("08:53 Gabe: Sure, you wanna take the conversation to the webapp channel though?\n") // .append("08:53 Alex: That's probably best\n") // .append("09:18 Hillary: Anyone else on the cs17 server having connection issues?\n") // .append("09:20 Vance: Yeah I've been using it all day and it's been performing like garbage\n") // .append("11:48 SERVER: _Jeff has joined the channel.\n") // .append("11:48 _Jeff: Hey guys. Lunch is here\n") // .append("11:49 SERVER: _Jeff has left the channel.\n") // .append("11:50 Vance: NICE"); // chatHistory.setText(sb.toString()); chatHistory.setMovementMethod(new ScrollingMovementMethod()); } class RetrieveHistoryTask extends AsyncTask<Void, Void, String[]> { @Override protected String[] doInBackground(Void... params) { input = new byte[FOUR_KB]; int numRead = 0; String[] ret = new String[2]; try { out.write(HIST_CONSTANT.getBytes(), 0, HIST_CONSTANT.length()); numRead = in.read(input, 0, FOUR_KB); ret[0] = new String(input, 0, numRead); out.write("GOT_HIST".getBytes(), 0, "GOT_HIST".length()); numRead = in.read(input, 0, FOUR_KB); ret[1] = new String(input, 0, numRead); Log.d("history", ret[1]); } catch (Exception e) { e.printStackTrace(); } return ret; } @Override protected void onPostExecute(String[] result) { TextView history = (TextView) findViewById(R.id.chat_history); history.setText(result[0]); try { JSONObject jObject = new JSONObject(result[1]); JSONArray jArray = jObject.getJSONArray("users"); users.clear(); for (int i = 0; i < jArray.length(); i++) { String user = jArray.getString(i); Log.d("user", user); users.add(user); } userListAdapter.notifyDataSetChanged(); } catch (Exception e) { e.printStackTrace(); } } } private class SendListener implements View.OnClickListener { EditText editor; public SendListener(EditText editor) { this.editor = editor; } @Override public void onClick(View v) { new SendMessageTask().execute(editor.getText().toString()); editor.setText(""); } } private class SetupConnectionTask extends AsyncTask<String, Void, String> { String host; int port; String nick; SetupConnectionTask(String host, int port, String nick) { this.host = host; this.port = port; this.nick = nick; } @Override protected String doInBackground(String... hosts) { try { socket = new Socket(host, port); out = socket.getOutputStream(); in = socket.getInputStream(); out.write(nick.getBytes(), 0, nick.length()); } catch (Exception e) { e.printStackTrace(); } return null; } protected void onPostExecute(String result) { //new UpdateLoop(chatHistory, in).start(); final Handler handler = new Handler(); timer = new Timer(); TimerTask fetchHistoryTask = new TimerTask() { @Override public void run() { handler.post(new Runnable() { @Override public void run() { RetrieveHistoryTask performBackgroundTask = new RetrieveHistoryTask(); performBackgroundTask.execute(); } }); } }; timer.schedule(fetchHistoryTask, 0, 1000); } } private class SendMessageTask extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... messages) { input = new byte[FOUR_KB]; int numRead = 0; for (String message : messages) { try { Log.d("ASDASDA", message); out.write(message.getBytes(), 0, message.length()); numRead = in.read(input, 0, FOUR_KB); } catch (Exception e) { e.printStackTrace(); } } return new String(input, 0, numRead); } protected void onPostExecute(String result) { Log.d("ASDDA", result); TextView history = (TextView) findViewById(R.id.chat_history); history.setText(result); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, 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. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_config) { AlertDialog.Builder connInfoDialogBuilder = new AlertDialog.Builder(this); connInfoDialogBuilder.setTitle("Server Information"); final View view = getLayoutInflater().inflate(R.layout.server_config, null); connInfoDialogBuilder.setView(view); final AlertDialog connInfoDialog = connInfoDialogBuilder.create(); connInfoDialog.show(); Button apply = (Button) view.findViewById(R.id.apply_settings_button); apply.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { EditText hostET = (EditText) view.findViewById(R.id.host_content); String host = hostET.getText().toString(); EditText portET = (EditText) view.findViewById(R.id.port_content); int port = Integer.valueOf(portET.getText().toString()); EditText nickET = (EditText) view.findViewById(R.id.nickname_content); String nick = nickET.getText().toString(); Log.d("ASDF", host + " " + port + " " + nick); new SetupConnectionTask(host, port, nick).execute(); connInfoDialog.dismiss(); } }); return true; } return super.onOptionsItemSelected(item); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); } }