1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
public class TopActivity extends Activity {

	CafeDataSource dataSource;

	private Context context;
	private static String url = "http://ppcafe.phsaez.com/";
	private JSONArray places = null;
	private JSONArray pictures = null;

	private static final String TAG_CAFE_ID = "cafe_id";
	private static final String TAG_CAFE_TITLE = "cafe_title";
	private static final String TAG_CAFE_BEEN = "been";
	private static final String TAG_CAFE_WANT = "want";
	private static final String TAG_CAFE_ADDRESS = "cafe_address";
	private static final String TAG_CAFE_THUMB = "cafe_thumb";
	private static final String TAG_CAFE_DESCRIPTION = "cafe_description";
	private static final String TAG_CAFE_COFFEE_RATE = "cafe_coffee_rate";
	private static final String TAG_CAFE_WIFI_RATE = "cafe_wifi_rate";
	private static final String TAG_CAFE_LATITUDE = "cafe_latitude";
	private static final String TAG_CAFE_LONGITUDE = "cafe_longitude";
	private static final String TAG_PICTURE_URL = "picture_url";

	public ArrayList<HashMap<String, String>> placeList;
	public List<Model_Insert> model_Inserts;
	public ArrayList<HashMap<String, String>> arrCursor;

	private static final String TAG = "BITMAP";
	private boolean isImage = false;
	private String reviewImageLink;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_card);

		dataSource = new CafeDataSource(this);
		dataSource.open();

		List<Model_Insert> model_Inserts = dataSource.findTblCafe();
		List<Model_Insert> model_Inserts_save = dataSource.findTblCafeSave();
		List<Model_Insert> model_Inserts_picture = dataSource.findTblPicture();
		if ((model_Inserts.size() == 0) || (model_Inserts_save.size() == 0)	|| model_Inserts_picture.size() == 0) {
			new DownloadImageTask().execute();
			/* model_Inserts = dataSource.findTblCafe();
			model_Inserts_save = dataSource.findTblCafeSave();
			model_Inserts_picture = dataSource.findTblPicture(); */
		} else{
			
			ShowAllContent();
		}


	} // End onCreate

	public void ShowAllContent() {
		arrCursor = dataSource.getArrCursor();
		GridView gridView1 = (GridView) findViewById(R.id.grid_all);
		gridView1.setAdapter(new ImageAdapter(TopActivity.this, arrCursor));
	}

	public class DownloadImageTask extends AsyncTask<String, Void, Void> {

		@Override
		protected Void doInBackground(String... params) {

			placeList = new ArrayList<HashMap<String, String>>();
			JSONParser jParser = new JSONParser();
			JSONObject jsonO = jParser.getJSONUrl(url);

			try {
				places = jsonO.getJSONArray("place");

				for (int i = 0; i < places.length(); i++) {
					JSONObject jobj = places.getJSONObject(i);

					int cafe_id = jobj.getInt(TAG_CAFE_ID);
					String cafe_title = jobj.getString(TAG_CAFE_TITLE);
					int cafe_been = jobj.getInt(TAG_CAFE_BEEN);
					int cafe_want = jobj.getInt(TAG_CAFE_WANT);
					String cafe_address = jobj.getString(TAG_CAFE_ADDRESS);
					String cafe_thumb = jobj.getString(TAG_CAFE_THUMB);
					String cafe_description = jobj.getString(TAG_CAFE_DESCRIPTION);
					int cafe_wifi_rate = jobj.getInt(TAG_CAFE_WIFI_RATE);
					int cafe_coffee_rate = jobj.getInt(TAG_CAFE_COFFEE_RATE);
					double cafe_latitude = jobj.getDouble(TAG_CAFE_LATITUDE);
					double cafe_longitude = jobj.getDouble(TAG_CAFE_LONGITUDE);

					// Table Save
					Model_Insert model_Insert = new Model_Insert();
					model_Insert.setCafe_Id(cafe_id);
					model_Insert.setCafe_Been(cafe_been);
					model_Insert.setCafe_Want(cafe_want);
					model_Insert = dataSource.createTableCafeSave(model_Insert);
					Log.i("data", " ID " + model_Insert.getCafe_Id());

					// Table Cafe
					model_Insert = new Model_Insert();
					model_Insert.setCafe_Id(cafe_id);
					model_Insert.setCafe_Title(cafe_title);
					model_Insert.setCafe_Been(cafe_been);
					model_Insert.setCafe_Want(cafe_want);
					model_Insert.setCafe_Address(cafe_address);
					model_Insert.setCafe_Thumb(cafe_thumb);
					model_Insert.setCafe_Description(cafe_description);
					model_Insert.setCafe_WifiRate(cafe_wifi_rate);
					model_Insert.setCafe_CoffeeRate(cafe_coffee_rate);
					model_Insert.setCafe_Latitude(cafe_latitude);
					model_Insert.setCafe_Longitude(cafe_longitude);
					model_Insert = dataSource.createTableCafe(model_Insert);
					Log.i("data", " Picture " + model_Insert.getCafe_Id());
					
					HashMap<String, String> map = new HashMap<String, String>();
					map.put(TAG_CAFE_THUMB, cafe_thumb);
					placeList.add(map);
					
					reviewImageLink = "http://xxx.xxx.xxx/xxx/place_pictures/profiles/thumb/"+cafe_thumb;
					URL reviewImageURL;
					Log.i("url", reviewImageLink);
					String name = reviewImageLink.substring(reviewImageLink.lastIndexOf("/") + 1);
					Log.i("Url_name", "" +name);
					try {
						reviewImageURL = new URL(reviewImageLink);
						if (!hasExternalStoragePublicPicture(name)) {
							isImage = false;
							new DownloadFullImageTask().execute(reviewImageURL);
							Log.v("log_tag", "if");
							isImage = true;
							File sdImageMainDirectory = new File(Environment.getExternalStorageDirectory(),getResources()
											.getString(R.string.directory));
							sdImageMainDirectory.mkdirs();
							File file = new File(sdImageMainDirectory, name);
							Log.v("log_tag", "Directory created");
						}

					} catch (MalformedURLException e) {
						Log.v(TAG, e.toString());
					}

				}

				// for " piture " Object in json
				pictures = jsonO.getJSONArray("pictures");
				for (int i = 0; i < pictures.length(); i++) {
					JSONObject jObj = pictures.getJSONObject(i);
					int cafe_id = jObj.getInt(TAG_CAFE_ID);
					String picture_url = jObj.getString(TAG_PICTURE_URL);

					// Table Picture
					Model_Insert model_Insert = new Model_Insert();
					model_Insert.setCafe_Id(cafe_id);
					model_Insert.setPitureUrl(picture_url);
					model_Insert = dataSource.createTablePicture(model_Insert);
					Log.i("pic", " Picture " + model_Insert.getPitureurl());
//					HashMap<String, String> map = new HashMap<String, String>();
//					map.put(TAG_PICTURE_URL, picture_url);
//					placeList.add(map);
				}
				
				
					
				
			} catch (JSONException e) {
				// TODO: handle exception
			}
			return null;
		}

		protected void onPostExecute(Void unused) {
			 ShowAllContent(); // When Finish Show Content

		}

	}

	public class DownloadFullImageTask extends AsyncTask<URL, Integer, Bitmap> {

		// This class definition states that DownloadImageTask will take String
		// parameters, publish Integer progress updates, and return a Bitmap
		protected Bitmap doInBackground(URL... paths) {
			URL url;
			try {
				url = paths[0];
				HttpURLConnection connection = (HttpURLConnection) url.openConnection();
				int length = connection.getContentLength();
				InputStream is = (InputStream) url.getContent();
				byte[] imageData = new byte[length];
				int buffersize = (int) Math.ceil(length / (double) 100);
				int downloaded = 0;
				int read;
				while (downloaded < length) {
					if (length < buffersize) {
						read = is.read(imageData, downloaded, length);
					} else if ((length - downloaded) <= buffersize) {
						read = is.read(imageData, downloaded, length
								- downloaded);
					} else {
						read = is.read(imageData, downloaded, buffersize);
					}
					downloaded += read;
					publishProgress((downloaded * 100) / length);
				}
				Bitmap bitmap = BitmapFactory.decodeByteArray(imageData, 0,
						length);
				if (bitmap != null) {
					Log.i(TAG, "Bitmap created");
				} else {
					Log.i(TAG, "Bitmap not created");
				}
				is.close();
				return bitmap;
			} catch (MalformedURLException e) {
				Log.e(TAG, "Malformed exception: " + e.toString());
			} catch (IOException e) {
				Log.e(TAG, "IOException: " + e.toString());
			} catch (Exception e) {
				Log.e(TAG, "Exception: " + e.toString());
			}
			return null;

		}

		protected void onPostExecute(Bitmap result) {
			int position = placeList.size();
			reviewImageLink = "http://icomehere.com/data/place_pictures/profiles/thumb/"+placeList.get(position - 1).get(TAG_CAFE_THUMB);
			Log.i("url_thumb", reviewImageLink);
			URL reviewImageURL;
				String name = reviewImageLink.substring(reviewImageLink.lastIndexOf("/") + 1);
				Log.i("name", ""+name);
				if (result != null) {
					hasExternalStoragePublicPicture(name);
					saveToSDCard(result, name);
					isImage = true;

				} else {
					isImage = false;

				}
	
					}
	}

	public void saveToSDCard(Bitmap bitmap, String name) {
		boolean mExternalStorageAvailable = false;
		boolean mExternalStorageWriteable = false;
		String state = Environment.getExternalStorageState();
		if (Environment.MEDIA_MOUNTED.equals(state)) {
			mExternalStorageAvailable = mExternalStorageWriteable = true;
			Log.v("card", "SD Card is available for read and write"
					+ mExternalStorageAvailable + mExternalStorageWriteable);
			saveFile(bitmap, name);
		} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
			mExternalStorageAvailable = true;
			mExternalStorageWriteable = false;
			Log.v("card", "SD Card is available for read"
					+ mExternalStorageAvailable);
		} else {
			mExternalStorageAvailable = mExternalStorageWriteable = false;
			Log.v("card", " Please insert a SD Card to save your video"
					+ mExternalStorageAvailable + mExternalStorageWriteable);

		}
	}

	private void saveFile(Bitmap bitmap, String name) {
		String filename = name;
		ContentValues values = new ContentValues();
		File sdImageMainDirectory = new File(Environment.getExternalStorageDirectory(), getResources()
						.getString(R.string.directory));
		sdImageMainDirectory.mkdir();
		File outputFile = new File(sdImageMainDirectory, filename);
		values.put(MediaStore.MediaColumns.DATA, outputFile.toString());
		values.put(MediaStore.MediaColumns.TITLE, filename);
		values.put(MediaStore.MediaColumns.DATE_ADDED,System.currentTimeMillis());
		values.put(MediaStore.MediaColumns.MIME_TYPE, "image/png");
		Uri uri = this.getContentResolver().insert(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,values);
		try {
			OutputStream outStream = this.getContentResolver().openOutputStream(uri);
			bitmap.compress(Bitmap.CompressFormat.PNG, 95, outStream);
			outStream.flush();
			outStream.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private boolean hasExternalStoragePublicPicture(String name) {
		File sdImageMainDirectory = new File(Environment.getExternalStorageDirectory(), getResources()
						.getString(R.string.directory));
		File file = new File(sdImageMainDirectory, name);
		if (file != null) {
			file.delete();
		}
		return file.exists();
	}

	public Integer[] mThumb = { R.drawable.bar_navi, R.drawable.bg_base,
			R.drawable.btn_cafe_on, R.drawable.ic_launcher,
			R.drawable.bar_navi, R.drawable.bg_base, R.drawable.btn_cafe_on,
			R.drawable.ic_launcher, R.drawable.bar_navi, R.drawable.bg_base,
			R.drawable.btn_cafe_on, R.drawable.ic_launcher,
			R.drawable.bar_navi, R.drawable.bg_base, R.drawable.btn_cafe_on,
			R.drawable.ic_launcher, R.drawable.bar_navi, R.drawable.bg_base,
			R.drawable.btn_cafe_on, R.drawable.ic_launcher,
			R.drawable.bar_navi, R.drawable.bg_base, R.drawable.btn_cafe_on,
			R.drawable.ic_launcher, R.drawable.bar_navi, R.drawable.bg_base,
			R.drawable.btn_cafe_on, R.drawable.ic_launcher,
			R.drawable.bar_navi, R.drawable.bg_base, R.drawable.btn_cafe_on,
			R.drawable.ic_launcher, R.drawable.bar_navi, R.drawable.bg_base,
			R.drawable.btn_cafe_on, R.drawable.ic_launcher,
			R.drawable.bar_navi, R.drawable.bg_base, R.drawable.btn_cafe_on,
			R.drawable.ic_launcher, R.drawable.bar_navi, R.drawable.bg_base,
			R.drawable.btn_cafe_on, R.drawable.ic_launcher,
			R.drawable.bar_navi, R.drawable.bg_base, R.drawable.btn_cafe_on,
			R.drawable.ic_launcher, R.drawable.bar_navi, R.drawable.bg_base,
			R.drawable.btn_cafe_on, R.drawable.ic_launcher };

	private static class ViewHolder {
		public ImageView imageview;
		public TextView txtTitle;
	}

	public class ImageAdapter extends BaseAdapter {
		private ArrayList<HashMap<String, String>> MyArr = new ArrayList<HashMap<String, String>>();

		public ImageAdapter(Context c,ArrayList<HashMap<String, String>> myArrayList) {
			context = c;
			MyArr = myArrayList;
		}

		@Override
		public int getCount() {
			return MyArr.size();

		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View converView, ViewGroup parent) {
			ViewHolder viewHolder = new ViewHolder();
			LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			if (converView == null) {
				converView = inflater.inflate(R.layout.grid_item, null);
			}
			viewHolder.imageview = (ImageView) converView.findViewById(R.id.imv_card_cafe);
			viewHolder.txtTitle = (TextView) converView.findViewById(R.id.txt_title);

			/*
			 * String str = "frute : juse text"; Integer len; len =
			 * str.length(); if(len > 20){ String result = str.substring(0, 15);
			 * viewHolder.txtTitle.setText(result);
			 * 
			 * } else { viewHolder.txtTitle.setText(str); }
			 */
			viewHolder.txtTitle.setText(MyArr.get(position).get(CafeDbOpenHelper.CAFE_TITLE));

			String imagePath = Environment.getExternalStorageDirectory()+"/Download/".toString() + MyArr.get(position).get(CafeDbOpenHelper.CAFE_THUMB);
			Log.i("image", ""+imagePath);
			viewHolder.imageview.setImageDrawable(Drawable.createFromPath(imagePath));
			return converView;
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		dataSource.open();
	}

	@Override
	protected void onPause() {
		super.onPause();
		dataSource.close();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		// getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

}