Java tutorial
/* * Copyright 2011-2012 the original author or authors. * * 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 org.youaretheone.website.client; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.springframework.http.MediaType; import org.springframework.http.converter.json.GsonHttpMessageConverter; import org.springframework.web.client.RestTemplate; import org.youaretheone.AbstractAsyncActivity; import org.youaretheone.R; import android.app.LocalActivityManager; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ImageView; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.TabHost; import android.widget.TabHost.TabContentFactory; import android.widget.TabHost.TabSpec; import android.widget.TextView; /** * @author Roy Clarkson */ public class UoneSearchGsonActivity extends AbstractAsyncActivity { protected static final String TAG = UoneSearchGsonActivity.class.getSimpleName(); private final static String WEBSITE = "http://www.androidworkz.com"; // This isn't necessary but it makes it nice to determine which tab I am on // in the switch statement below private static class TabItem { public final static int SEARCH = 0; public final static int SHARE = 1; public final static int WEBSITE = 2; public final static int SETTINGS = 3; public final static int QUIT = 4; } private TabHost mTabHost; private static RelativeLayout mMenuPanel; private TextView content; private ListView userListView; LocalActivityManager mLocalActivityManager; private List<UoneSearchResult> results = new ArrayList<UoneSearchResult>(); UoneSearchResultListAdapter userListAdapter; // *************************************** // Activity methods // *************************************** @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); setupViews(savedInstanceState); } @Override public void onStart() { super.onStart(); // when this activity starts, initiate an asynchronous HTTP GET request (new UoneSearchTask()).execute(); } // *************************************** // Private methods // *************************************** private void refreshResults(UoneSearchResponse response) { if (response == null) { return; } this.results = response.getResponseData().getResults(); Log.i(TAG, results.toString()); // setListAdapter(new UoneSearchResultListAdapter(this, this.results)); // ((ListView) findViewById(R.id.userlistview)).setAdapter(new // UoneSearchResultListAdapter(this, this.results)); List<UoneSearchResult> theRes = userListAdapter.getResults(); theRes.addAll(results); userListAdapter.setResults(theRes); userListAdapter.notifyDataSetChanged(); } // *************************************** // Private classes // *************************************** private class UoneSearchTask extends AsyncTask<Void, Void, UoneSearchResponse> { @Override protected void onPreExecute() { showLoadingProgressDialog(); } @Override protected UoneSearchResponse doInBackground(Void... params) { try { // The URL for making the GET request final String url = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q={query}"; // Create a new RestTemplate instance RestTemplate restTemplate = new RestTemplate(); // Set a custom GsonHttpMessageConverter that supports the // text/javascript media type GsonHttpMessageConverter messageConverter = new GsonHttpMessageConverter(); messageConverter .setSupportedMediaTypes(Collections.singletonList(new MediaType("text", "javascript"))); restTemplate.getMessageConverters().add(messageConverter); // Perform the HTTP GET request to the Google search API UoneSearchResponse response = restTemplate.getForObject(url, UoneSearchResponse.class, "Android"); Log.i(TAG, response.getResponseData().getResults().toString()); return response; } catch (Exception e) { Log.e(TAG, e.getMessage(), e); } Log.e(TAG, "null***************"); return null; } @Override protected void onPostExecute(UoneSearchResponse response) { dismissProgressDialog(); refreshResults(response); } } private void setupViews(Bundle savedInstanceState) { content = (TextView) findViewById(R.id.content); content.setText(getString(R.string.search)); userListView = ((ListView) findViewById(R.id.userlistview)); userListAdapter = new UoneSearchResultListAdapter(this, this.results); userListView.setAdapter(userListAdapter); userListView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, final int position, long id) { if (results == null) { return; } UoneSearchResult result = results.get(position); startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(result.getUrl()))); } }); mMenuPanel = ((RelativeLayout) findViewById(R.id.menuPopup)); mMenuPanel.setVisibility(View.GONE); mTabHost = (TabHost) findViewById(android.R.id.tabhost); mLocalActivityManager = new LocalActivityManager(this, false); mLocalActivityManager.dispatchCreate(savedInstanceState); mTabHost.setup(mLocalActivityManager); mTabHost.getTabWidget().setDividerDrawable(R.drawable.tab_divider); addMethodTab(new TextView(this), "Search", R.drawable.search); addMethodTab(new TextView(this), "Share", R.drawable.heart); addMethodTab(new TextView(this), "Website", R.drawable.globe); addActivityTab(new TextView(this), "Settings", R.drawable.tools, new Intent(this.getApplicationContext(), Settings.class)); addMethodTab(new TextView(this), "Quit", R.drawable.power); mTabHost.setOnClickListener(new TabHost.OnClickListener() { @Override public void onClick(View arg0) { Log.e(TAG, "mTabHost.onClick()-----------1"); checkTab(); } }); mTabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() { @Override public void onTabChanged(String arg0) { Log.e(TAG, "onTabChanged()-----------1"); checkTab(); } }); } private void checkTab() { if (mMenuPanel != null) { if (mMenuPanel.getVisibility() == View.VISIBLE) { toggleMenu(); } switch (mTabHost.getCurrentTab()) { case TabItem.SEARCH: content.setText(getString(R.string.search)); (new UoneSearchTask()).execute(); break; case TabItem.SHARE: content.setText(getString(R.string.share)); (new UoneSearchTask()).execute(); break; case TabItem.WEBSITE: content.setText(getString(R.string.website)); final Intent visit = new Intent(Intent.ACTION_VIEW); visit.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); visit.setData(android.net.Uri.parse(WEBSITE)); // Use a thread so that the menu is responsive when // clicked new Thread(new Runnable() { public void run() { startActivity(visit); } }).start(); break; case TabItem.SETTINGS: content.setText(getString(R.string.settings)); (new UoneSearchTask()).execute(); break; case TabItem.QUIT: content.setText(getString(R.string.quit)); new Thread(new Runnable() { public void run() { UoneSearchGsonActivity.this.finish(); // The following makes the Android Gods frown // upon me android.os.Process.killProcess(android.os.Process.myPid()); System.exit(0); } }).start(); break; default: break; } // Handle click on currently selected tab - hide menu bar // IMPORTANT: This listener has to appear AFTER the tabs are // added // Unfortunately, This doesn't work when the current tab // contains an activity (except for tab 0) // If you only have method tabs then it works perfect mTabHost.getTabWidget().getChildAt(mTabHost.getCurrentTab()) .setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { toggleMenu(); } }); // if you want to reset the current tab // mTabHost.setCurrentTab(0); } } // Use this method to add an activity or intent to the tab bar private void addActivityTab(final View view, final String tag, int iconResource, Intent intent) { View tabview = createTabView(mTabHost.getContext(), tag, iconResource); TabSpec setContent = mTabHost.newTabSpec(tag).setIndicator(tabview).setContent(intent); mTabHost.addTab(setContent); } // Use this method if you only want the tab to execute a method private void addMethodTab(final View view, final String tag, int iconResource) { View tabview = createTabView(mTabHost.getContext(), tag, iconResource); TabSpec setContent = mTabHost.newTabSpec(tag).setIndicator(tabview).setContent(new TabContentFactory() { public View createTabContent(String tag) { return view; } }); mTabHost.addTab(setContent); } private static View createTabView(final Context context, final String text, int iconResource) { View view = LayoutInflater.from(context).inflate(R.layout.tabs_layout, null); TextView tv = (TextView) view.findViewById(R.id.tabsText); tv.setText(text); ImageView icon = (ImageView) view.findViewById(R.id.tabsIcon); icon.setImageResource(iconResource); return view; } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_MENU) { toggleMenu(); return true; } else { return super.onKeyDown(keyCode, event); } } public static void toggleMenu() { if (mMenuPanel.getVisibility() == View.GONE) { mMenuPanel.setVisibility(View.VISIBLE); } else { mMenuPanel.setVisibility(View.GONE); } } @Override protected void onPause() { mLocalActivityManager.dispatchPause(isFinishing()); super.onPause(); } @Override protected void onResume() { mLocalActivityManager.dispatchResume(); super.onPause(); } }