Advertisement
Guest User

Untitled

a guest
Nov 26th, 2014
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 11.23 KB | None | 0 0
  1. public class MainActivity extends FragmentActivity implements OnClickListener {
  2. private MainFragment mainFragment;
  3. Button sendIPbutton; //Button for sending IP Address
  4. EditText mEdit; //Get info from what user enters in form
  5. //TextView mText;
  6. TextView coordinates;
  7. @Override
  8. protected void onCreate(Bundle savedInstanceState) {
  9. super.onCreate(savedInstanceState);
  10.  
  11.  
  12.  
  13. setContentView(R.layout.activity_main);
  14.  
  15. /*http://www.firstdroid.com/2010/04/29/android-development-using-gps-to-get-current-location-2/*/
  16. /* Use the LocationManager class to obtain GPS locations */
  17. LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
  18. LocationListener mlocListener = new MyLocationListener();
  19. mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
  20.  
  21.  
  22.  
  23.  
  24.  
  25. /**********************************************************************/
  26. /*get reference to views*/
  27. sendIPbutton = (Button) findViewById(R.id.sendIP);
  28. mEdit = (EditText) findViewById(R.id.enterIP);
  29. sendIPbutton.setOnClickListener(this);
  30.  
  31.  
  32.  
  33. // InputMethodManager imm = (InputMethodManager)getSystemService(
  34. // Context.INPUT_METHOD_SERVICE);
  35. // imm.hideSoftInputFromWindow(mEdit.getWindowToken(), 0);
  36. /*add click listener to Button "sendIPbutton"*/
  37. // sendIPbutton.setOnClickListener(new OnClickListener() {
  38. // @Override
  39. // public void onClick(View arg0) {
  40. // //Add JSON Logic here
  41. //
  42. String ip = "http://";
  43. ip = ip + ((mEdit).getText().toString()) + "/rpi/";
  44. System.out.println(ip);
  45. //String json = "{"lights": [{"lightId": 1, "red":242,"green":116,"blue":12, "intensity": 0.5}],"propagate": true}";
  46.  
  47. InputStream inputStream = null;
  48. String result = "";
  49. try {
  50. //1. CREATE HTTPCLIENT
  51. HttpClient httpClient = new DefaultHttpClient();
  52. System.out.println("no error");
  53. //2. MAKE POST REQUEST TO GIVEN ipAddress
  54. HttpPost httpPost = new HttpPost(ip);
  55. System.out.println("no error2");
  56.  
  57. //String json = "";
  58. //3. BUILD JSON OBJECT
  59. //JSONObject jsonObject = new JSONObject();
  60. //jsonObject.accumulate("")
  61. String json = "";//"{"lights": [{"lightId": 1, "red":242,"green":116,"blue":12, "intensity": 0.5}],"propagate": true}";
  62. JSONObject jsonObj = new JSONObject("{"phonetype":"N95","cat":"WP"}");
  63. json = jsonObj.toString();
  64. httpPost.setEntity(new StringEntity(json));
  65.  
  66. //5. SET JSON to STRING ENTITY
  67. // StringEntity se = new StringEntity(json);
  68. // System.out.println("no error3");
  69. //
  70. // //6. SET HTTP POST ENTITY
  71. // httpPost.setEntity(se);
  72. // System.out.println("no error4");
  73.  
  74. //7. SET SOME HEADERS TO INFORM SERVER ABOUT THE TYPE OF CONTENT
  75. // httpPost.setHeader("Accept", "application/json");
  76. // System.out.println("no error5");
  77. // httpPost.setHeader("Content-type", "application/json");
  78. // System.out.println("no error6");
  79. //HttpPost httpPost = new HttpPost(url);
  80. //httpPost.setEntity(new StringEntity(json));
  81. //CloseableHttpResponse response2 = httpclient.execute(httpPost);
  82. //ERROR HERE
  83. //8. EXECUTE POST REQUEST TO THE GIVEN IP ADDRESS
  84. HttpResponse httpResponse = httpClient.execute(httpPost);
  85.  
  86. System.out.println("no error7");
  87. // httpPost.completed();
  88. // response2.close();
  89.  
  90. //9. RECEIVE RESPONSE AS inputStream
  91. inputStream = httpResponse.getEntity().getContent();
  92. System.out.println("no error8");
  93. //10. CONVERT inputStream to string
  94. if(inputStream != null) {
  95. result = convertInputStreamToString(inputStream);
  96. System.out.println("no error9");
  97. }
  98. else
  99. result = "Did not work!";
  100.  
  101. } catch (Exception e) {
  102.  
  103. Log.d("InputStream", e.getLocalizedMessage());
  104. }
  105. if (savedInstanceState == null) {
  106. // Add the fragment on initial activity setup
  107. mainFragment = new MainFragment();
  108. getSupportFragmentManager()
  109. .beginTransaction()
  110. .add(android.R.id.content, mainFragment)
  111. .commit();
  112. } else {
  113. // Or set the fragment from restored state info
  114. mainFragment = (MainFragment) getSupportFragmentManager()
  115. .findFragmentById(android.R.id.content);
  116. }
  117. /*********************************************************************************/
  118. }
  119.  
  120.  
  121. /* Class My Location Listener */
  122. public class MyLocationListener implements LocationListener{
  123. @Override
  124. public void onLocationChanged(Location loc){
  125. loc.getLatitude();
  126. loc.getLongitude();
  127. String Text = "Latitude: " + loc.getLatitude() + "nLongitude: " + loc.getLongitude();
  128. // Toast.makeText( getApplicationContext(),Text, Toast.LENGTH_SHORT).show();
  129.  
  130. coordinates = (TextView)findViewById(R.id.coordinates);
  131.  
  132. coordinates.setText(Text);
  133. }
  134.  
  135.  
  136. @Override
  137. public void onProviderDisabled(String provider){
  138. Toast.makeText( getApplicationContext(),
  139. "Gps Disabled",
  140.  
  141. Toast.LENGTH_SHORT ).show();
  142.  
  143. }
  144.  
  145.  
  146. @Override
  147. public void onProviderEnabled(String provider){
  148. Toast.makeText( getApplicationContext(),"Gps Enabled",Toast.LENGTH_SHORT).show();
  149. }
  150.  
  151.  
  152. @Override
  153. public void onStatusChanged(String provider, int status, Bundle extras){
  154. }
  155.  
  156. }/* End of Class MyLocationListener */
  157.  
  158.  
  159.  
  160. @Override
  161. public boolean onTouchEvent(MotionEvent event) {
  162. InputMethodManager imm = (InputMethodManager)getSystemService(Context.
  163. INPUT_METHOD_SERVICE);
  164. imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
  165. return true;
  166. }
  167.  
  168. public void setObject(View view){
  169. Intent intent = new Intent(this, SetObjectActivity.class);
  170. startActivity(intent);
  171. }
  172.  
  173. public static String POST(String ip) {
  174. //Add JSON Logic here
  175. InputStream inputStream = null;
  176.  
  177. //((mEdit).getText().toString()) put on the line below if doesn't work
  178. ip = "http://" + ip + "/rpi/";
  179. System.out.println(ip);
  180. //String json = "{"lights": [{"lightId": 1, "red":242,"green":116,"blue":12, "intensity": 0.5}],"propagate": true}";
  181.  
  182.  
  183. String result = "";
  184. try {
  185. //1. CREATE HTTPCLIENT
  186. HttpClient httpclient = new DefaultHttpClient();
  187. System.out.println("no error");
  188. //2. MAKE POST REQUEST TO GIVEN ipAddress
  189. HttpPost httpPost = new HttpPost(ip);
  190. System.out.println("no error2");
  191.  
  192. //String json = "";
  193. //3. BUILD JSON OBJECT
  194. //JSONObject jsonObject = new JSONObject();
  195. //jsonObject.accumulate("")
  196. String json = "{"lights": [{"lightId": 1, "red":242,"green":116,"blue":12, "intensity": 0.5}],"propagate": true}";
  197.  
  198.  
  199. //5. SET JSON to STRING ENTITY
  200. StringEntity se = new StringEntity(json);
  201.  
  202. // 6. set httpPost Entity
  203. httpPost.setEntity(se);
  204.  
  205. // 7. Set some headers to inform server about the type of the content
  206. //httpPost.setHeader("Accept", "application/json");
  207. // httpPost.setHeader("Content-type", "application/json");
  208.  
  209. // 8. Execute POST request to the given URL
  210. HttpResponse httpResponse = httpclient.execute(httpPost);
  211.  
  212. // 9. receive response as inputStream
  213. inputStream = httpResponse.getEntity().getContent();
  214.  
  215. System.out.println("no error8");
  216. //10. CONVERT inputStream to string
  217. if (inputStream != null) {
  218. result = convertInputStreamToString(inputStream);
  219. System.out.println("no error9");
  220. } else
  221. result = "Did not work!";
  222.  
  223. } catch (Exception e) {
  224.  
  225. Log.d("InputStream", e.getLocalizedMessage());
  226. }
  227.  
  228. return result;
  229. }
  230.  
  231. public boolean isConnected(){
  232. ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Activity.CONNECTIVITY_SERVICE);
  233. NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
  234. if (networkInfo != null && networkInfo.isConnected())
  235. return true;
  236. else
  237. return false;
  238. }
  239. @Override
  240. public void onClick(View view) {
  241.  
  242. switch(view.getId()){
  243. case R.id.sendIP:
  244. if(!validate())
  245. Toast.makeText(getBaseContext(), "Enter some data!", Toast.LENGTH_LONG).show();
  246. // call AsynTask to perform network operation on separate thread
  247. new HttpAsyncTask().execute("http://hmkcode.appspot.com/jsonservlet");
  248. break;
  249. }
  250.  
  251. }
  252. private class HttpAsyncTask extends AsyncTask<String, Void, String> {
  253. @Override
  254. protected String doInBackground(String... urls) {
  255.  
  256.  
  257. return POST(((mEdit).getText().toString()));
  258. }
  259. // onPostExecute displays the results of the AsyncTask.
  260. @Override
  261. protected void onPostExecute(String result) {
  262. Toast.makeText(getBaseContext(), "Data Sent!", Toast.LENGTH_LONG).show();
  263. }
  264. }
  265. @Override
  266. protected void onResume() {
  267. super.onResume();
  268.  
  269. // Logs 'install' and 'app activate' App Events.
  270. AppEventsLogger.activateApp(this);
  271. }
  272. @Override
  273. protected void onPause() {
  274. super.onPause();
  275.  
  276. // Logs 'app deactivate' App Event.
  277. AppEventsLogger.deactivateApp(this);
  278. }
  279. private boolean validate(){
  280. if(mEdit.getText().toString().trim().equals(""))
  281. return false;
  282. else
  283. return true;
  284. }
  285. private static String convertInputStreamToString(InputStream inputStream) throws IOException{
  286. BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
  287. String line = "";
  288. String result = "";
  289. while((line = bufferedReader.readLine()) != null)
  290. result += line;
  291.  
  292. inputStream.close();
  293. return result;
  294.  
  295. }
  296.  
  297.  
  298.  
  299. @Override
  300. public boolean onCreateOptionsMenu(Menu menu) {
  301. // Inflate the menu; this adds items to the action bar if it is present.
  302. getMenuInflater().inflate(R.menu.menu_main, menu);
  303. return true;
  304. }
  305.  
  306. @Override
  307. public boolean onOptionsItemSelected(MenuItem item) {
  308. // Handle action bar item clicks here. The action bar will
  309. // automatically handle clicks on the Home/Up button, so long
  310. // as you specify a parent activity in AndroidManifest.xml.
  311. int id = item.getItemId();
  312.  
  313. //noinspection SimplifiableIfStatement
  314. if (id == R.id.action_settings) {
  315. return true;
  316. }
  317.  
  318. return super.onOptionsItemSelected(item);
  319. }
  320. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement