Advertisement
Guest User

Untitled

a guest
Dec 22nd, 2014
183
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.20 KB | None | 0 0
  1. package br.com.comidadibuteco.activities;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.List;
  5.  
  6. import org.apache.http.Header;
  7. import org.json.JSONArray;
  8. import org.json.JSONException;
  9. import org.json.JSONObject;
  10.  
  11. import com.loopj.android.http.JsonHttpResponseHandler;
  12. import com.loopj.android.http.RequestParams;
  13.  
  14. import de.greenrobot.dao.query.Query;
  15.  
  16. import br.com.comidadibuteco.R;
  17. import br.com.comidadibuteco.sqlite.City;
  18. import br.com.comidadibuteco.sqlite.CityDao;
  19. import br.com.comidadibuteco.sqlite.DaoMaster;
  20. import br.com.comidadibuteco.sqlite.DaoSession;
  21. import br.com.comidadibuteco.sqlite.DaoMaster.DevOpenHelper;
  22. import br.com.comidadibuteco.util.ApplicationVariables;
  23. import br.com.comidadibuteco.util.SingletonEnvironment;
  24. import android.annotation.SuppressLint;
  25. import android.app.Activity;
  26. import android.content.Context;
  27. import android.database.sqlite.SQLiteDatabase;
  28. import android.net.ConnectivityManager;
  29. import android.net.NetworkInfo;
  30. import android.os.AsyncTask;
  31. import android.os.Bundle;
  32. import android.view.Gravity;
  33. import android.view.LayoutInflater;
  34. import android.view.View;
  35. import android.view.ViewGroup;
  36. import android.widget.AbsListView;
  37. import android.widget.AbsListView.OnScrollListener;
  38. import android.widget.BaseAdapter;
  39. import android.widget.LinearLayout;
  40. import android.widget.ListView;
  41. import android.widget.ProgressBar;
  42. import android.widget.TextView;
  43.  
  44. public class CitiesActivity extends Activity {
  45.  
  46. // Adaptador
  47. private CityBaseAdapter mAdapter;
  48.  
  49. // Lista de cidades
  50. private ArrayList<City> mCities;
  51.  
  52. // Lista
  53. private ListView mListView;
  54.  
  55. //Layout carregando
  56. private LinearLayout mLoadingLayout;
  57.  
  58. // Singleton
  59. private SingletonEnvironment mSingleton;
  60.  
  61. // Elementos SQLite
  62. private DevOpenHelper mHelper;
  63. private SQLiteDatabase mDatabase;
  64. private DaoMaster mDaoMaster;
  65. private DaoSession mDaoSession;
  66. private CityDao mCityDao;
  67.  
  68. public void onCreate(Bundle savedInstanceState) {
  69. super.onCreate(savedInstanceState);
  70. setContentView(R.layout.cities);
  71.  
  72. initDB();
  73. initWidgets();
  74. }
  75.  
  76. // Inicializa os elementos da base de dados
  77. private void initDB() {
  78. mHelper = new DaoMaster.DevOpenHelper(this, "boteco.db", null);
  79. mDatabase = mHelper.getWritableDatabase();
  80. mDaoMaster = new DaoMaster(mDatabase);
  81. mDaoSession = mDaoMaster.newSession();
  82. mCityDao = mDaoSession.getCityDao();
  83. }
  84.  
  85. private void initWidgets() {
  86. mSingleton = SingletonEnvironment.getInstance();
  87. mCities = new ArrayList<City>();
  88. mAdapter = new CityBaseAdapter();
  89.  
  90. //verifica se há conectividade com a rede ou não
  91. ConnectivityManager cn = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
  92. NetworkInfo nf = cn.getActiveNetworkInfo();
  93. if(nf != null && nf.isConnected()==true )
  94. {
  95. // Tenta executar a busca por novos elementos online
  96. RequestParams mParams = new RequestParams();
  97. mParams.add("token", ApplicationVariables.TOKEN_SERVER);
  98.  
  99. mSingleton.getAsyncHttpClient().post(
  100. ApplicationVariables.SERVER_DOMAIN
  101. + ApplicationVariables.CITIES_SEARCH, mParams,
  102. new JsonHttpResponseHandler() {
  103.  
  104. @Override
  105. public void onStart() {
  106. super.onStart();
  107.  
  108. }
  109.  
  110. @Override
  111. public void onFailure(int statusCode, Header[] headers,
  112. Throwable throwable, JSONObject errorResponse) {
  113. super.onFailure(statusCode, headers, throwable,
  114. errorResponse);
  115.  
  116. }
  117.  
  118. @Override
  119. public void onSuccess(int statusCode, Header[] headers,
  120. JSONObject response) {
  121. super.onSuccess(statusCode, headers, response);
  122. new AsynCityDB(response).execute();
  123. }
  124. });
  125. }
  126. else
  127. {
  128. //se não houver, carrega diretamente os dados do BD
  129. new AsynCityDB(null).execute();
  130. }
  131.  
  132. // Inicializa a ListView
  133. SetLoadingLayout();
  134. mListView = (ListView) findViewById(R.id.citiesListView);
  135. mListView.addFooterView(mLoadingLayout);
  136. mListView.setAdapter(mAdapter);
  137. mListView.setOnScrollListener(new OnScrollListener() {
  138.  
  139. private int lastItem = 0;
  140. AsynCityDB task;
  141.  
  142. @Override
  143. public void onScrollStateChanged(AbsListView view, int scrollState) {
  144.  
  145. }
  146.  
  147. @Override
  148. public void onScroll(AbsListView view, int firstVisibleItem,
  149. int visibleItemCount, int totalItemCount) {
  150.  
  151. if (firstVisibleItem + visibleItemCount == totalItemCount
  152. && totalItemCount > lastItem) {
  153.  
  154. lastItem = totalItemCount;
  155.  
  156. if (task != null
  157. && task.getStatus() == AsyncTask.Status.RUNNING) {
  158. return;
  159. }
  160.  
  161. task = new AsynCityDB(null);
  162. task.execute();
  163. }
  164. }
  165. });
  166. }
  167.  
  168. void LoadItems() {
  169.  
  170. //insere as proximas 3 cidades do banco de dados
  171. Query<City> mQuery = mCityDao.queryBuilder().limit(3).offset(mCities.size()).build();
  172. List<City> mTempCities = mQuery.list();
  173.  
  174. //se houverem proximos itens, os insere na lista
  175. if(mTempCities.size() > 0){
  176. for (City c : mTempCities) {
  177. mCities.add(c);
  178. }
  179. }
  180. //se nao, remove o footer de carregando
  181. else{
  182. //TODO remover footer
  183. }
  184.  
  185. }
  186.  
  187. void SetLoadingLayout() {
  188.  
  189. LinearLayout layout = new LinearLayout(this);
  190. ProgressBar progressBar = new ProgressBar(this);
  191. progressBar.setPadding(0, 0, 10, 0);
  192. layout.addView(progressBar, new LinearLayout.LayoutParams(
  193. LinearLayout.LayoutParams.WRAP_CONTENT,
  194. LinearLayout.LayoutParams.WRAP_CONTENT));
  195.  
  196. TextView textView = new TextView(this);
  197. textView.setText("Carregando...");
  198. textView.setGravity(Gravity.CENTER_VERTICAL);
  199.  
  200. layout.addView(textView, new LinearLayout.LayoutParams(
  201. LinearLayout.LayoutParams.FILL_PARENT,
  202. LinearLayout.LayoutParams.FILL_PARENT));
  203.  
  204. mLoadingLayout = new LinearLayout(this);
  205. mLoadingLayout.addView(layout, new LinearLayout.LayoutParams(
  206. LinearLayout.LayoutParams.WRAP_CONTENT,
  207. LinearLayout.LayoutParams.WRAP_CONTENT));
  208. mLoadingLayout.setGravity(Gravity.CENTER);
  209. }
  210.  
  211. private class AsynCityDB extends AsyncTask<Void, Void, Void> {
  212.  
  213. private JSONObject response;
  214.  
  215. public AsynCityDB(JSONObject response) {
  216. this.response = response;
  217. }
  218.  
  219. @Override
  220. protected void onPreExecute() {
  221. super.onPreExecute();
  222. }
  223.  
  224. @Override
  225. protected Void doInBackground(Void... params) {
  226.  
  227. //se houver response, insere ou atualiza cidades do banco
  228. if (response != null) {
  229. try {
  230. JSONArray array = response.getJSONArray("cidades");
  231. for (int i = 0; i < array.length(); i++) {
  232. JSONObject object = array.getJSONObject(i);
  233. City mNextCity = new City(object.getString("id"),
  234. object.getString("uf"),
  235. object.getString("nome"));
  236. // Trabalha sobre o banco de dados
  237. mCityDao.insertOrReplace(mNextCity);
  238. }
  239. } catch (JSONException e) {
  240.  
  241. }
  242. }
  243.  
  244. //carrega os dados na listview
  245. LoadItems();
  246.  
  247. return null;
  248. }
  249.  
  250. @Override
  251. protected void onPostExecute(Void result) {
  252. super.onPostExecute(result);
  253. mAdapter.notifyDataSetChanged();
  254. }
  255.  
  256. }
  257.  
  258. public class CityBaseAdapter extends BaseAdapter {
  259.  
  260. private LayoutInflater mLayoutInflater;
  261.  
  262. public CityBaseAdapter() {
  263. this.mLayoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
  264. }
  265.  
  266. @SuppressLint("InflateParams") @Override
  267. public View getView(int position, View convertView, ViewGroup parent) {
  268. ViewHolder mHolder;
  269.  
  270. if (convertView == null) {
  271. convertView = mLayoutInflater.inflate(R.layout.city_item, null);
  272. mHolder = new ViewHolder();
  273. mHolder.mCityName = (TextView) convertView
  274. .findViewById(R.id.labelCityName);
  275. convertView.setTag(mHolder);
  276. } else {
  277. mHolder = (ViewHolder) convertView.getTag();
  278. }
  279.  
  280. City nextCity = mCities.get(position);
  281. if (nextCity != null) {
  282. mHolder.mCityName.setText(nextCity.getNome());
  283. }
  284.  
  285. return convertView;
  286. }
  287.  
  288. // Define a estrutura da cidade
  289. class ViewHolder {
  290. TextView mCityName;
  291. }
  292.  
  293. @Override
  294. public int getCount() {
  295. return mCities == null ? 0 : mCities.size();
  296. }
  297.  
  298. @Override
  299. public Object getItem(int position) {
  300. return mCities == null ? null : mCities.get(position);
  301. }
  302.  
  303. @Override
  304. public long getItemId(int position) {
  305. return position;
  306. }
  307.  
  308. }
  309.  
  310. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement