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.ArrayAdapter; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.ListView; import android.widget.Spinner; 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; import me.drakeet.materialdialog.MaterialDialog; public class DetailPlaceFragment 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; public String[] sp3_data; MaterialDialog mMaterialDialog; String totalURL; int firstPosition; int secondePosition; String result = " ?1?"; FrameLayout root; private ArrayList<Place> placeList = new ArrayList<Place>(); private CustomListAdapter adapter; private int pageCount = 1; private ListView listView; private Spinner sp1, sp2, sp3; private Context context; public DetailPlaceFragment() { } /** * 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 DetailPlaceFragment 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; DetailPlaceFragment fragment = new DetailPlaceFragment(); 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) { return inflater.inflate(R.layout.fragment_detail, container, false); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { 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); sp1 = (Spinner) parent.findViewById(R.id.spinner1); sp2 = (Spinner) parent.findViewById(R.id.spinner2); sp3 = (Spinner) parent.findViewById(R.id.spinner3); final String[] sp1_data = getResources().getStringArray(R.array.areaCode_1); ArrayAdapter<String> sp1_adapter = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_dropdown_item, sp1_data); sp1.setAdapter(sp1_adapter); //First Adapter firstPosition = 0; final String[] sp2_data = getResources().getStringArray(R.array.sigunguCode_1); ArrayAdapter<String> sp2_adapter = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_dropdown_item, sp2_data); sp2.setAdapter(sp2_adapter); sp2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { secondePosition = position; switch (position) { case 0: sp3_data = getResources().getStringArray(R.array.dongCode_1_1); break; case 1: sp3_data = getResources().getStringArray(R.array.dongCode_1_2); break; case 2: sp3_data = getResources().getStringArray(R.array.dongCode_1_3); break; case 3: sp3_data = getResources().getStringArray(R.array.dongCode_1_4); break; case 4: sp3_data = getResources().getStringArray(R.array.dongCode_1_5); break; case 5: sp3_data = getResources().getStringArray(R.array.dongCode_1_6); break; case 6: sp3_data = getResources().getStringArray(R.array.dongCode_1_7); break; case 7: sp3_data = getResources().getStringArray(R.array.dongCode_1_8); break; case 8: sp3_data = getResources().getStringArray(R.array.dongCode_1_9); break; case 9: sp3_data = getResources().getStringArray(R.array.dongCode_1_10); break; case 10: sp3_data = getResources().getStringArray(R.array.dongCode_1_11); break; case 11: sp3_data = getResources().getStringArray(R.array.dongCode_1_12); break; case 12: sp3_data = getResources().getStringArray(R.array.dongCode_1_13); break; case 13: sp3_data = getResources().getStringArray(R.array.dongCode_1_14); break; case 14: sp3_data = getResources().getStringArray(R.array.dongCode_1_15); break; case 15: sp3_data = getResources().getStringArray(R.array.dongCode_1_16); break; case 16: sp3_data = getResources().getStringArray(R.array.dongCode_1_17); break; case 17: sp3_data = getResources().getStringArray(R.array.dongCode_1_18); break; case 18: sp3_data = getResources().getStringArray(R.array.dongCode_1_19); break; case 19: sp3_data = getResources().getStringArray(R.array.dongCode_1_20); break; case 20: sp3_data = getResources().getStringArray(R.array.dongCode_1_21); break; case 21: sp3_data = getResources().getStringArray(R.array.dongCode_1_22); break; case 22: sp3_data = getResources().getStringArray(R.array.dongCode_1_23); break; case 23: sp3_data = getResources().getStringArray(R.array.dongCode_1_24); break; case 24: sp3_data = getResources().getStringArray(R.array.dongCode_1_25); break; default: break; } ArrayAdapter<String> sp3_adapter = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_dropdown_item, sp3_data); sp3.setAdapter(sp3_adapter); sp3.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { result = sp2_data[secondePosition] + " " + sp3_data[position]; Log.d("Theme", "Selected Location : " + result); totalURL = makeURL(1, result); placeList.clear(); pageCount = 1; adapter.isEndFalse(); adapter.resetServerListSize(0); adapter.notifyDataSetChanged(); new GetDataTask().execute(); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); 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(); } }); }//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 result) { String categoryData = ""; switch (intentPosition) { case 0: categoryData = "?"; break; case 1: categoryData = "??"; break; case 2: categoryData = "?"; break; case 3: categoryData = "?"; break; case 4: categoryData = "?"; break; case 5: categoryData = "?"; break; case 6: categoryData = ""; break; case 7: categoryData = " "; break; case 8: categoryData = ""; break; case 9: categoryData = ""; break; case 10: categoryData = ""; break; } String locationData = result + " " + categoryData; 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_content, 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++, result); } @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(); } } }