Java tutorial
/* * Copyright 2014 The Android Open Source Project * * 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 com.sunho.nating.fragments; import android.content.Context; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.Fragment; import android.transitions.everywhere.Scene; import android.transitions.everywhere.TransitionManager; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.sunho.nating.adapter.CustomListAdapter; import com.sunho.nating.adapter.EndlessScrollListener; import com.sunho.nating.listviewfeed.MainActivity; import com.sunho.nating.listviewfeed.R; import com.sunho.nating.listviewfeed.data.Place; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; public class DetailUnivFragment extends Fragment implements Animation.AnimationListener { private static final String TAG = "DetailFragment"; private static final String ARG_RESOURCE_ID = "resource_id"; private static final String ARG_TITLE = "title"; private static final String ARG_X = "x"; private static final String ARG_Y = "y"; private static final String ARG_WIDTH = "width"; private static final String ARG_HEIGHT = "height"; private static int intentPosition = 0; private static String myLocationLat; private static String myLocationLong; String totalURL; String result = " ?1?"; private ArrayList<Place> placeList = new ArrayList<Place>(); private CustomListAdapter adapter; private int pageCount = 1; private ListView listView; private Context context; public DetailUnivFragment() { } /** * Create a new instance of DetailFragment. * * @param resourceId The resource ID of the Drawable image to show * @param title The title of the image * @param x The horizontal position of the grid item in pixel * @param y The vertical position of the grid item in pixel * @param width The width of the grid item in pixel * @param height The height of the grid item in pixel * @return a new instance of DetailFragment */ public static DetailUnivFragment newInstance(int resourceId, String title, int x, int y, int width, int height, int position, String locationLat, String locationLong) { myLocationLat = locationLat; myLocationLong = locationLong; intentPosition = position; DetailUnivFragment fragment = new DetailUnivFragment(); Bundle args = new Bundle(); args.putInt(ARG_RESOURCE_ID, resourceId); args.putString(ARG_TITLE, title); args.putInt(ARG_X, x); args.putInt(ARG_Y, y); args.putInt(ARG_WIDTH, width); args.putInt(ARG_HEIGHT, height); fragment.setArguments(args); return fragment; } // getInputStreamFromUrl : URL ? (InputStream)? . public static InputStream getInputStreamFromUrl(String url) { InputStream contentStream = null; try { // HttpClient URL? ? . HttpClient httpclient = new DefaultHttpClient(); HttpResponse response = httpclient.execute(new HttpGet(url)); contentStream = response.getEntity().getContent(); } catch (Exception e) { e.printStackTrace(); } return contentStream; } // getInputStreamFromUrl @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { MainActivity.aBar.show(); return inflater.inflate(R.layout.fragment_detail, container, false); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { FrameLayout root = (FrameLayout) view; context = view.getContext(); assert context != null; // This is how the fragment looks at first. Since the transition is one-way, we don't need to make // this a Scene. View item = LayoutInflater.from(context).inflate(R.layout.item_gridview, root, false); assert item != null; bind(item); // We adjust the position of the initial image with LayoutParams using the values supplied // as the fragment arguments. Bundle args = getArguments(); FrameLayout.LayoutParams params = null; if (args != null) { params = new FrameLayout.LayoutParams(args.getInt(ARG_WIDTH), args.getInt(ARG_HEIGHT)); params.topMargin = args.getInt(ARG_Y); params.leftMargin = args.getInt(ARG_X); } root.addView(item, params); } @Override public void onResume() { super.onResume(); } /** * Bind the views inside of parent with the fragment arguments. * * @param parent The parent of views to bind. */ private void bind(View parent) { Bundle args = getArguments(); if (args == null) { return; } ImageView image = (ImageView) parent.findViewById(R.id.image); image.setImageResource(args.getInt(ARG_RESOURCE_ID)); TextView title = (TextView) parent.findViewById(R.id.title); title.setText(args.getString(ARG_TITLE)); } private void bindFragment(View parent) { Bundle args = getArguments(); if (args == null) { return; } ImageView image = (ImageView) parent.findViewById(R.id.image); image.setImageResource(args.getInt(ARG_RESOURCE_ID)); TextView title = (TextView) parent.findViewById(R.id.title); title.setText(args.getString(ARG_TITLE)); listView = (ListView) parent.findViewById(R.id.list); listView.setDividerHeight(0); adapter = new CustomListAdapter(MainActivity.mActivity, placeList) { @Override public View getDataRow(int position, View convertView, ViewGroup parent) { return convertView; } }; listView.setAdapter(adapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Toast.makeText(MainActivity.mContext, placeList.get(position).getOldAddress(), 0).show(); moveFragment(position); } }); listView.setOnScrollListener(new EndlessScrollListener() { @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { super.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount); //lastListitem = (totalItemCount - 1 > 0) && (firstVisibleItem + visibleItemCount >= totalItemCount - 1); } @Override public void onLoadMore(int page, int totalItemsCount) { // Triggered only when new data needs to be appended to the list // Add whatever code is needed to append new items to your AdapterView Log.d(TAG, "==ListView Information=="); Log.d(TAG, "PageNumber : " + page); Log.d(TAG, "TotalCount : " + totalItemsCount); Log.d(TAG, "adpaterCount : " + adapter.getCount()); Log.d(TAG, "========================"); new GetDataTask().execute(); } }); new GetDataTask().execute(); }//bindFragment public void moveFragment(int position) { getActivity().getSupportFragmentManager().beginTransaction() .replace(R.id.frame_container, new DetailInfoFragment(myLocationLat, myLocationLong, placeList, position)) .addToBackStack("detail").commit(); }//moveFragment private String makeURL(int num) { String[] sp1_data = getResources().getStringArray(R.array.seoul_UnivList); String locationData = sp1_data[intentPosition] + " "; Log.d("Search", "Search : " + locationData); String encodedLocationData = null; try { encodedLocationData = URLEncoder.encode(locationData, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } String DAUM_API_KEY = "cbc9fd26e82992216b5ba5247d9fad6f12cb6a79"; String myLocationStringData = myLocationLat + "," + myLocationLong; String newURL = "https://apis.daum.net/local/v1/search/keyword.json?query=" + encodedLocationData + "&sort=2" + "&location=" + myLocationStringData + "&radius=5000" + "&apikey=" + DAUM_API_KEY + "&page=" + num; Log.d(TAG, newURL); return newURL; } private void CheckDataJson() { JSONObject object, object2 = null; JSONArray feedArray = null; String line = null; try { line = getStringFromUrl(totalURL); object = new JSONObject(line); object2 = object.getJSONObject("channel"); feedArray = new JSONArray(object2.getString("item")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); Log.d(TAG, "4?"); } try { Log.d(TAG, "==FeedArray Information=="); Log.d(TAG, "Length : " + feedArray.length()); adapter.setServerListSize(feedArray.length()); Log.d(TAG, "========================="); for (int i = 0; i < feedArray.length(); i++) { try { String photoURL = null; JSONObject obj = feedArray.getJSONObject(i); Place place = new Place(); place.setId(obj.getString("id")); place.setName(obj.getString("title")); place.setOldAddress(obj.getString("address")); place.setNewAddress(obj.getString("newAddress")); // place.setIcon(obj.getString("icon")); place.setPlaceUrl(obj.getString("placeUrl")); place.setPhone(obj.getString("phone")); place.setCategory(obj.getString("category")); place.setDistance(String.valueOf(Integer.parseInt(obj.getString("distance")))); place.setLatitude((Double) obj.getDouble("latitude")); place.setLongitude((Double) obj.getDouble("longitude")); photoURL = obj.isNull("imageUrl") ? null : obj.getString("imageUrl"); place.setPhotolUrl(photoURL); // adding movie to movies array placeList.add(place); } catch (JSONException e) { e.printStackTrace(); } } } catch (NullPointerException e) { e.printStackTrace(); } } // getStringFromUrl : URL ? ? . public String getStringFromUrl(String url) throws UnsupportedEncodingException { // ? "UTF-8" ?? , ?? ?? ?? BufferedReader ?. BufferedReader br = new BufferedReader(new InputStreamReader(getInputStreamFromUrl(url), "UTF-8")); // ?? ?? StringBuffer ?. StringBuffer sb = new StringBuffer(); try { // ?? ?? ?? ? line String line = null; // ?? ?? ? StringBuffer ? . while ((line = br.readLine()) != null) { sb.append(line); } } catch (Exception e) { e.printStackTrace(); } return sb.toString(); } // getStringFromUrl @Override public Animation onCreateAnimation(int transit, boolean enter, int nextAnim) { Animation animation = AnimationUtils.loadAnimation(getActivity(), enter ? android.R.anim.fade_in : android.R.anim.fade_out); // We bind a listener for the fragment transaction. We only bind it when // this fragment is entering. if (animation != null && enter) { animation.setAnimationListener(this); } return animation; } @Override public void onAnimationStart(Animation animation) { // This method is called at the end of the animation for the fragment transaction. // There is nothing we need to do in this sample. } @Override public void onAnimationEnd(Animation animation) { // This method is called at the end of the animation for the fragment transaction, // which is perfect time to start our Transition. //Log.i(TAG, "Fragment animation ended. Starting a Transition."); final Scene scene = Scene.getSceneForLayout((ViewGroup) getView(), R.layout.fragment_detail_univ, getActivity()); TransitionManager.go(scene); // Note that we need to bind views with data after we call TransitionManager.go(). bindFragment(scene.getSceneRoot()); } @Override public void onAnimationRepeat(Animation animation) { // This method is never called in this sample because the animation doesn't repeat. } private class GetDataTask extends AsyncTask<Void, Void, Void> { protected void onPreExecute() { Log.d("Location", "GetDataTask, onPreExecute()"); totalURL = makeURL(pageCount++); } @Override protected Void doInBackground(Void... params) { Log.d("Location", "GetDataTask, doInBackground()"); CheckDataJson(); return (null); } @Override protected void onPostExecute(Void unused) { //sortShortestDistanceData(placeList); Log.d("Location", "GetDataTask, onPostExecute()"); adapter.notifyDataSetChanged(); } } }