Where should i add my method for noInternetConnection? Android - android

It is all working and i have added my method to check if there is internet connection, and if there isn't change activity. But it is changing activity immediately before loading progress bar. Where should i add this method so first progress bar is loaded and if there is no internet connection, change activity.
Also if anyone have some suggestion about this checking internet connection, i would appricieate any answer.
This is my activity where i'm using that method:
public class ListaPreporuka extends AppCompatActivity {
// Log tag
private static final String TAG = ListaPreporuka.class.getSimpleName();
// Movies json url
private static final String url = "http://www.nadji-ekipu.org/wp-content/uploads/2015/07/movies.txt";
private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<Movie>();
private ListView listView;
private CustomListAdapter adapter;
private static String Title ="title";
private static String bitmap ="thumbnailUrl";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.lista_preporuka);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayUseLogoEnabled(true);
getSupportActionBar().setLogo(R.drawable.ic_horor_filmovi_ikonica);
Intent newActivity2=new Intent();
setResult(RESULT_OK, newActivity2);
listView = (ListView) findViewById(R.id.list);
adapter = new CustomListAdapter(this, movieList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Učitavanje...");
pDialog.show();
// Creating volley request obj
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Movie movie = new Movie();
movie.setTitle(obj.getString("title"));
movie.setThumbnailUrl(obj.getString("image"));
movie.setRating(((Number) obj.get("rating"))
.doubleValue());
movie.setYear(obj.getInt("releaseYear"));
// Genre is json array
final JSONArray genreArry = obj.getJSONArray("genre");
ArrayList<String> genre = new ArrayList<String>();
for (int j = 0; j < genreArry.length(); j++) {
genre.add((String) genreArry.get(j));
}
movie.setGenre(genre);
// adding movie to movies array
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
noInternet();
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String name = ((TextView) view.findViewById(R.id.title))
.getText().toString();
bitmap = ((Movie)movieList.get(position)).getThumbnailUrl();
Intent intent = new Intent(ListaPreporuka.this, MoviesSingleActivity.class);
intent.putExtra(Title, name);
intent.putExtra("images", bitmap);
intent.putExtra("Year", movieList.get(position).getYear());
startActivity(intent);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
}
});
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
//WHERE SHOULD I ADD THIS METHOD FOR MAKING MY ACTIVITY SHOW FIRST PROGRESS BAR AND IF THERE IS NO INTERNET CONNECTION, SHOW ANOTHER ACTIVITY
private void noInternet() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
if (info != null) {
if (!info.isConnected()) {
}
}
else {
Toast.makeText(this, "No Internet Connection", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(ListaPreporuka.this, NoConnection.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
if (item.getItemId() == android.R.id.home) {
finish();
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
return true;
}
return false;
}
#Override
public void onBackPressed() {
super.onBackPressed();
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
}

You are making some http request. So you want to chek if there is internet connection available right?
So first put a check if internet connection is available.
Wherever you are doing your other operations ..
if(internet connection is present){
//make http request;
}else{
// display appropriate message and switch to your new activity
}

You can call your method in the same place but with some delay, if you want simple answer. Something like this:
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
//Do something after 100ms
}
}, 100);
But, I think, you should better use this method to show dialog:
public static ProgressDialog show (Context context, CharSequence title, CharSequence message, boolean indeterminate, boolean cancelable, DialogInterface.OnCancelListener cancelListener)
Implement DialogInterface.OnCancelListener, call your intent with transition to the new activity in onCancel callback of OnCancelListener.
And use pDialog.cancel() in else statement of noInternet() method.

Related

Get specific json object from listview click

I have my class that is based on a tutorial online, i dont fully understand it yet ( working on it ), but its working.
It populates the listview, now i want to get the id and show the data related to that id on a more detailed activity.
I already obtain the id of the item i am clicking:
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position,
long id) {
Log.e("item clicks", "selected: " + position);
}
});
But now, i am not getting how i will do this, get the data of the position i clicked.
I have a inner class "GetObras" but i cant use the variables from it on my onCreate, i tried make them global, etc
public class MainActivity extends ActionBarActivity implements SearchView.OnQueryTextListener{
private String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
private ListView list;
private static String url = "http://ploran.gear.host/scriptobras6.php";
ArrayList<HashMap<String, String>> obrasList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
obrasList = new ArrayList<HashMap<String, String>>();
list = (ListView)findViewById(R.id.list1);
new GetObras().execute();
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position,
long id) {
Log.e("item clicks", "selected: " + position);
}
});
}
private class GetObras extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
//JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray obras = new JSONArray(jsonStr);
// Getting JSON Array node
//JSONArray obras = jsonObj.getJSONArray("obras");
// looping through All
for (int i = 0; i < obras.length(); i++) {
JSONObject c = obras.getJSONObject(i);
String id = c.getString("Id");
String nomeObra = c.getString("NomeObra");
String idCliente = c.getString("idCliente");
String DataLevantamento = c.getString("DataPLevantamento");
String DataRealizacao = c.getString("DataRLevantamento");
String Estado = c.getString("Estado");
String DataMateriais = c.getString("DataRMateriais");
String DataInicioObra = c.getString("DataInicioObra");
String DataConclusao = c.getString("DataConclusao");
String DataVestoria = c.getString("DataVestoria");
String Obs = c.getString("Obs");
String Prompor = c.getString("Prompor");
String Levantpor = c.getString("Levantpor");
String executpor = c.getString("executpor");
// tmp hash map for single contact
HashMap<String, String> obra = new HashMap<>();
// adding each child node to HashMap key => value
obra.put("Id", id);
obra.put("nomeObra", nomeObra);
obra.put("idCliente", idCliente);
obra.put("DataLevantamento", DataLevantamento);
obra.put("DataRealizacao", DataRealizacao);
obra.put("Estado", Estado);
obra.put("DataMateriais", DataMateriais);
obra.put("DataIncioObra", DataInicioObra);
obra.put("DataConclusao", DataConclusao);
obra.put("DataVestoria", DataVestoria);
obra.put("Obs", Obs);
obra.put("Prompor", Prompor);
obra.put("Levantpor", Levantpor);
obra.put("executpor", executpor);
// adding contact to contact list
obrasList.add(obra);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, obrasList,
R.layout.list_item, new String[]{"nomeObra", "idCliente",
"Estado"}, new int[]{R.id.name,
R.id.email, R.id.mobile});
list.setAdapter(adapter);
}
}
List<String> cities;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_search, menu);
MenuItem searchItem = menu.findItem(R.id.search);
return true;
}
#Override
public boolean onQueryTextSubmit(String query) {
// User pressed the search button
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
// User changed the text
return false;
}
}
If what i think is correct, i could just get the JsonArray from the doInBackground method in GetObras and do:
JSONObject c = obras.getJSONObject(position);
Thank you.
You can retrieve it using obrasList reference. As your are passing obrasList to your adapter.
Below is the sample code:
obrasList.get(position).get(yourkey);
Hope this will help you.. :))

How to make progress dialog in fragment tab in Android?

I have MainActivity which added two fragment tab namely "tab1 and "tab2.tab 1 sends some request to server during this process I Want to show a progress dialog but when I do this through a error message "android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application" and also have some implementation of Broadcast receiver in tab 1 fragment which also through error "unable to register receiver"
Progress dialog code:
public class DialogUtils {
public static ProgressDialog showProgressDialog(Context context, String message) {
ProgressDialog m_Dialog = new ProgressDialog(context);
m_Dialog.setMessage(message);
m_Dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
m_Dialog.setCancelable(false);
m_Dialog.show();
return m_Dialog;
}
}
Mainactivity code:
m_TabLayout = (TabLayout) findViewById(R.id.tab_layout);// finding Id of tablayout
m_ViewPager = (ViewPager) findViewById(R.id.pager);//finding Id of ViewPager
m_TabLayout.addTab(m_TabLayout.newTab().setText("Deals"));// add deal listin tab
m_TabLayout.addTab(m_TabLayout.newTab().setText("Stories"));
m_TabLayout.setTabGravity(TabLayout.GRAVITY_FILL);// setting Gravity of Tab
CDealMainListingPager m_oDealMainScreenPager = new CDealMainListingPager(getSupportFragmentManager(), m_TabLayout.getTabCount());
m_ViewPager.setAdapter(m_oDealMainScreenPager);// adiing adapter to ViewPager
m_ViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(m_TabLayout));// performing action of page changing
m_TabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
m_ViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
and tab1 fragment tab code:
public static final String TAG = CDealAppListing.class.getSimpleName();
public static final int m_TRANSACTION_SUCCESSFUL = 0;
public static String m_szMobileNumber;//declaring String mobile number variable
public static String m_szEncryptedPassword;//declaring string password variable
public static String sz_RecordCount;// //declaring String record count variable variable
public static String sz_LastCount;//declaring String lastcount variable
private static ListView m_ListView;// declaring Listview variable..
private static CDealAppListingAdapter m_oAdapter;// declaring DealListingAdapter..
public CDealAppDatastorage item;// declaring DealAppdataStorage
public View mFooter;
public AppCompatButton m_BtnRetry;
/*This Broadcast receiver will listen network state accordingly
which enable or disable create an account button*/
private final BroadcastReceiver m_oInternetChecker = new BroadcastReceiver() {// creating broadcast to receive otp sent by server from Inbox...
#Override
public void onReceive(Context context, Intent intent) {// on receive method to read OTP sent by server
changeButtonState();// check whether edit text is empty or not
}
};
RequestQueue requestQueue;
JsonObjectRequest jsonObjectRequest;
private ArrayList<CDealAppDatastorage> s_oDataset;// declaring Arraylist variable
private int[] m_n_FormImage;//declaring integer array varaible
private View m_Main;//declaring View variable
private int m_n_DefaultRecordCount = 5;// intiallly record count is 5.
private int m_n_DeafalutLastCount = 0;//initally lastcount is 0.
private SwipeRefreshLayout mSwipeRefresh;
private ProgressDialog m_Dialog;
private boolean bBottomOfView;
private LinearLayout m_NoInternetWarning;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
m_Main = inflater.inflate(R.layout.deal_listing, container, false);//intialize mainLayout
Log.i(TAG, "OnCreateView.........");
init();
return m_Main;
}
#Override
public void onResume() {
super.onResume();
Log.i(TAG, "onResume.........");
/*Registered Broadcast receiver*/
IntentFilter m_intentFilter = new IntentFilter();// creating object of Intentfilter class user for defining permission
m_intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");// action to check Internet connection
getActivity().registerReceiver(m_oInternetChecker, m_intentFilter);// register receiver....
getDetails();
}
public void changeButtonState() {
if (NetworkUtil.isConnected(getActivity())) {
m_BtnRetry.setEnabled(true);
m_BtnRetry.setBackgroundColor(Color.rgb(0, 80, 147));// set background color on eabled
} else {
m_BtnRetry.setEnabled(false);
m_BtnRetry.setBackgroundColor(Color.rgb(192, 192, 192));// color of login button
}
}
private void getDetails() {// get details of user from shared preference...
CLoginSessionManagement m_oSessionManagement = new CLoginSessionManagement(getActivity());// crating object of Login Session
HashMap<String, String> user = m_oSessionManagement.getLoginDetails();// get String from Login Session
m_szMobileNumber = user.get(CLoginSessionManagement.s_szKEY_MOBILE).trim();// getting password from saved preferences..........
m_szEncryptedPassword = user.get(CLoginSessionManagement.s_szKEY_PASSWORD).trim();// getting mobile num from shared preferences...
sz_RecordCount = String.valueOf(m_n_DefaultRecordCount);// increment of record count
m_n_DeafalutLastCount = 0;
sz_LastCount = String.valueOf(m_n_DeafalutLastCount);// increment of last count...
s_oDataset = new ArrayList<>();// making object of Arraylist
if (NetworkUtil.isConnected(getActivity())) {
m_NoInternetWarning.setVisibility(View.GONE);
postDealListingDatatoServer();// here sending request in onCreate
} else {
mSwipeRefresh.setVisibility(View.GONE);
m_NoInternetWarning.setVisibility(View.VISIBLE);
m_BtnRetry.setEnabled(false);
m_BtnRetry.setBackgroundColor(Color.rgb(192, 192, 192));// color of login button
}
}
#Override
public void onDestroy() {
super.onDestroy();
Log.i(TAG, "onDestroy...............");
getActivity().unregisterReceiver(m_oInternetChecker);// unregistaer broadcast receiver.
}
private void init() {// initialize controls
m_NoInternetWarning = (LinearLayout) m_Main.findViewById(R.id.no_internet_warning);
m_BtnRetry = (AppCompatButton) m_Main.findViewById(R.id.btn_retry);
m_BtnRetry.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
retryRequest(v);
}
});
m_ListView = (ListView) m_Main.findViewById(R.id.dealList);// findind Id of Listview
m_ListView.setFadingEdgeLength(0);
m_ListView.setOnScrollListener(this);
/*Swipe to refresh code*/
mSwipeRefresh = (SwipeRefreshLayout) m_Main.findViewById(R.id.swipe);
mSwipeRefresh.setColorSchemeResources(R.color.refresh_progress_1);
mSwipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
/*Here check net connection avialable or not */
if (NetworkUtil.isConnected(getActivity())) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
sz_RecordCount = String.valueOf(m_n_DefaultRecordCount);// increment of record count
m_n_DeafalutLastCount = 0;
sz_LastCount = String.valueOf(m_n_DeafalutLastCount);// increment of last count...
swipeData();
}
}, 3500);
} else {
m_NoInternetWarning.setVisibility(View.VISIBLE);
mSwipeRefresh.setVisibility(View.GONE);
if (mSwipeRefresh.isRefreshing()) {
mSwipeRefresh.setRefreshing(false);
}
}
}
});
m_n_FormImage = new int[]{// defining Images in Integer array
R.drawable.amazon,
R.drawable.whatsapp,
R.drawable.zorpia,
R.drawable.path,
R.drawable.app_me,
R.drawable.evernote,
R.drawable.app_me};
}
public void retryRequest(View v) {
if (NetworkUtil.isConnected(getActivity())) {
m_BtnRetry.setEnabled(true);
m_BtnRetry.setBackgroundColor(Color.rgb(0, 80, 147));// set background color on eabled
sz_RecordCount = String.valueOf(m_n_DefaultRecordCount);// increment of record count
m_n_DeafalutLastCount = 0;
sz_LastCount = String.valueOf(m_n_DeafalutLastCount);// increment of last count...
postDealListingDatatoServer();
} else {
m_BtnRetry.setEnabled(false);
m_BtnRetry.setBackgroundColor(Color.rgb(192, 192, 192));// color of login button
}
}
/*This is new changes in code ....using Volley instead of AsynkTask*/
/*This method send request to server for deallisting*/
// this method send request to server for deal list....
public void postDealListingDatatoServer() {
try {
String json;
// 3. build jsonObject
final JSONObject jsonObject = new JSONObject();// making object of Jsons.
jsonObject.put("agentCode", m_szMobileNumber);// put mobile number
jsonObject.put("pin", m_szEncryptedPassword);// put password
jsonObject.put("recordcount", sz_RecordCount);// put record count
jsonObject.put("lastcountvalue", sz_LastCount);// put last count
System.out.println("Record Count:-" + sz_RecordCount);
System.out.println("LastCount:-" + sz_LastCount);
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();// convert Json object to string
Log.i(TAG, "Server Request:-" + json);
m_Dialog = DialogUtils.showProgressDialog(getActivity().getApplicationContext(), "Loading...");
final String m_DealListingURL = "http://202.131.144.132:8080/json/metallica/getDealListInJSON";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, m_DealListingURL, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.i(TAG, "Server Response:-" + response);
m_Dialog.dismiss();
try {
int nResultCodeFromServer = Integer.parseInt(response.getString("resultcode"));
if (nResultCodeFromServer == m_TRANSACTION_SUCCESSFUL) {
JSONArray posts = response.optJSONArray("dealList");// get Deal list in array from response
s_oDataset.clear();
for (int i = 0; i < posts.length(); i++) {// loop for counting deals from server
JSONObject post = posts.getJSONObject(i);// counting deal based on index
item = new CDealAppDatastorage();// creating object of DealAppdata storage
item.setM_szHeaderText(post.getString("dealname"));// get deal name from response
item.setM_szsubHeaderText(post.getString("dealcode"));// get dealcode from response
item.setM_szDealValue(post.getString("dealvalue"));// get deal value from response
item.setM_n_Image(m_n_FormImage[i]);//set Image Index wise(Dummy)
s_oDataset.add(item);// add all items in ArrayList
}
if (!s_oDataset.isEmpty()) {// condition if data in arraylist is not empty
m_oAdapter = new CDealAppListingAdapter(getActivity(), s_oDataset);// create adapter object and add arraylist to adapter
m_ListView.setAdapter(m_oAdapter);//adding adapter to recyclerview
m_NoInternetWarning.setVisibility(View.GONE);
mSwipeRefresh.setVisibility(View.VISIBLE);
} else {
m_ListView.removeFooterView(mFooter);// else Load buttonvisibility set to Gone
}
}
if (response.getString("resultdescription").equalsIgnoreCase("Connection Not Available")) {//server based conditions
CSnackBar.getInstance().showSnackBarError(m_Main.findViewById(R.id.mainLayout), "Connection Lost !", getActivity());
} else if (response.getString("resultdescription").equalsIgnoreCase("Deal List Not Found")) {// serevr based conditions .....
CSnackBar.getInstance().showSnackBarError(m_Main.findViewById(R.id.mainLayout), "No more deals available", getActivity());
} else if (response.getString("resultdescription").equalsIgnoreCase("Technical Failure")) {
CSnackBar.getInstance().showSnackBarError(m_Main.findViewById(R.id.mainLayout), "Technical Failure", getActivity());
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Server error:-" + error);
m_Dialog.dismiss();
if (error instanceof TimeoutError) {
CSnackBar.getInstance().showSnackBarError(m_Main.findViewById(R.id.mainLayout), "Connection lost ! Please try again", getActivity());
} else if (error instanceof NetworkError) {
CSnackBar.getInstance().showSnackBarError(m_Main.findViewById(R.id.mainLayout), "No internet connection", getActivity());
mSwipeRefresh.setVisibility(View.GONE);
m_NoInternetWarning.setVisibility(View.VISIBLE);
}
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(jsonObjectRequest);
} catch (JSONException e) {
e.printStackTrace();
}
}
Step1: Change DialogUtils class:
public static ProgressDialog showProgressDialog(Activity activity, String message) {
ProgressDialog m_Dialog = new ProgressDialog(activity);
m_Dialog.setMessage(message);
m_Dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
m_Dialog.setCancelable(false);
m_Dialog.show();
return m_Dialog;
}
Step2: Change the postDealListingDatatoServer() method.
m_Dialog = DialogUtils.showProgressDialog(getActivity(), "Loading...");
Step3: About broadcast receiver. Please register at the onResume() method and unregister at the onPause() method.
public static ProgressDialog showProgressDialog(Context context, String message) {
ProgressDialog m_Dialog = new ProgressDialog(context);
m_Dialog.setMessage(message);
m_Dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
m_Dialog.setCancelable(false);
if (!((Activity) context).isFinishing()) {
m_Dialog.show();
}
return m_Dialog;
}
To dismiss dialog:
if ((m_Dialog!= null) && m_Dialog.isShowing())
m_Dialog.dismiss();
Check if fragment is visible or not.
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (this.isVisible()) {
// If we are becoming invisible, then...
if (!isVisibleToUser) {
}
} else {
}
}
}

Data refresh in listview after adding data to database

I have an application wherein, it retrieves data from DB and displays it in a list view but I want it to refresh after adding new data to database without using:
Intent i = new Intent (MyActivity.this,MyActivity.class);
startActivity (i);
Here is my code:
public class MainActivity extends ActionBarActivity {
//DB Class to perform DB related operations
DBController controller = new DBController(this);
//Progress Dialog Object
ProgressDialog prgDialog;
EditText userName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
userName = (EditText) findViewById(R.id.userName);
//Get User records from SQLite DB
ArrayList<HashMap<String, String>> userList = controller.getAllUsers();
//
if (userList.size() != 0) {
//Set the User Array list in ListView
ListAdapter adapter = new SimpleAdapter(MainActivity.this, userList, R.layout.view_user_entry, new String[]{"userId", "userName"}, new int[]{R.id.userId, R.id.userName});
ListView myList = (ListView) findViewById(android.R.id.list);
myList.setAdapter(adapter);
//Display Sync status of SQLite DB
Toast.makeText(getApplicationContext(), controller.getSyncStatus(), Toast.LENGTH_LONG).show();
}
//Initialize Progress Dialog properties
prgDialog = new ProgressDialog(this);
prgDialog.setMessage("Synching SQLite Data with Remote MySQL DB. Please wait...");
prgDialog.setCancelable(false);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//When Sync action button is clicked
if (id == R.id.refresh) {
//Sync SQLite DB data to remote MySQL DB
syncSQLiteMySQLDB();
return true;
}
return super.onOptionsItemSelected(item);
}
//Add User method getting called on clicking (+) button
public void addUser(View view) {
Intent objIntent = new Intent(getApplicationContext(), NewUser.class);
startActivity(objIntent);
}
public void syncSQLiteMySQLDB() {
//Create AsycHttpClient object
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
ArrayList<HashMap<String, String>> userList = controller.getAllUsers();
if (userList.size() != 0) {
if (controller.dbSyncCount() != 0) {
prgDialog.show();
params.put("usersJSON", controller.composeJSONfromSQLite());
client.post("http://192.168.2.4:9000/sqlitemysqlsync/insertuser.php", params, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
System.out.println(response);
prgDialog.hide();
try {
JSONArray arr = new JSONArray(response);
System.out.println(arr.length());
for (int i = 0; i < arr.length(); i++) {
JSONObject obj = (JSONObject) arr.get(i);
System.out.println(obj.get("id"));
System.out.println(obj.get("status"));
controller.updateSyncStatus(obj.get("id").toString(), obj.get("status").toString());
}
Toast.makeText(getApplicationContext(), "DB Sync completed!", Toast.LENGTH_LONG).show();
} catch (JSONException e) {
// TODO Auto-generated catch block
Toast.makeText(getApplicationContext(), "Error Occured [Server's JSON response might be invalid]!", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
#Override
public void onFailure(int statusCode, Throwable error,
String content) {
// TODO Auto-generated method stub
prgDialog.hide();
if (statusCode == 404) {
Toast.makeText(getApplicationContext(), "Requested resource not found", Toast.LENGTH_LONG).show();
} else if (statusCode == 500) {
Toast.makeText(getApplicationContext(), "Something went wrong at server end", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet]", Toast.LENGTH_LONG).show();
}
}
});
} else {
Toast.makeText(getApplicationContext(), "SQLite and Remote MySQL DBs are in Sync!", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(getApplicationContext(), "No data in SQLite DB, please do enter User name to perform Sync action", Toast.LENGTH_LONG).show();
}
}
/**
* Called when Save button is clicked
* #param view
*/
public void addNewUser(View view) {
HashMap<String, String> queryValues = new HashMap<String, String>();
queryValues.put("userName", userName.getText().toString());
if (userName.getText().toString() != null
&& userName.getText().toString().trim().length() != 0) {
controller.insertUser(queryValues);
} else {
Toast.makeText(getApplicationContext(), "Please enter User name",
Toast.LENGTH_LONG).show();
}
}
#Override
protected void onResume() {
super.onResume();
}
}
Call clear() on the adapter then notifyDatasetChanged(), this will get rid of old data in the list. At this time you can reload you database cursor.

When refreshing listView with SwipeRefreshLayout i'm getting one more ListView with data

I have successed to implement SwipeRefreshLayout in my Activity, but somewhere I have probably deployed adapter and this SwipeRefreshLayout.
Or do i need at all this ProgressDialog?
Maybe that is causing the problem, I'm beginner, so I would appreciate any help here.
Here is the code if anyone could help me finding the problem:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.lista_preporuka);
// Toolbabr settings
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayUseLogoEnabled(true);
getSupportActionBar().setLogo(R.drawable.ic_horor_filmovi_ikonica);
Intent newActivity2=new Intent();
setResult(RESULT_OK, newActivity2);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
noInternet();
}
}, 100);
listView = (ListView) findViewById(R.id.list);
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
adapter = new CustomListAdapter(this, movieList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Učitavanje...");
pDialog.setCancelable(false);
pDialog.show();
swipeRefreshLayout.setOnRefreshListener(this);
/**
* Showing Swipe Refresh animation on activity create
* As animation won't start on onCreate, post runnable is used
*/
swipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(true);
fetchMovies();
}
}
);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String name = ((TextView) view.findViewById(R.id.title))
.getText().toString();
String opisFilma = ((TextView) view.findViewById(R.id.opis))
.getText().toString();
String urlFilm = ((TextView) view.findViewById(R.id.url))
.getText().toString();
String ocena = String.valueOf(movieList.get(position).getRating());
String godina = String.valueOf(movieList.get(position).getYear());
bitmap = ((Movie)movieList.get(position)).getThumbnailUrl();
Intent intent = new Intent(ListaPreporuka.this, MoviesSingleActivity.class);
intent.putExtra(Title, name);
intent.putExtra(opis, opisFilma);
intent.putExtra("images", bitmap);
intent.putExtra(Rating, ocena);
intent.putExtra(Year, godina);
intent.putExtra(urlMovie, urlFilm);
startActivity(intent);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
}
});
}
#Override
public void onRefresh() {
fetchMovies();
}
private void fetchMovies(){
// showing refresh animation before making http call
swipeRefreshLayout.setRefreshing(true);
// Creating volley request obj
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Movie movie = new Movie();
movie.setTitle(obj.getString("title"));
movie.setOpis(obj.getString("opis"));
movie.setThumbnailUrl(obj.getString("image"));
movie.setRating(((Number) obj.get("rating"))
.doubleValue());
movie.setYear(obj.getInt("releaseYear"));
movie.setUrl(obj.getString("url"));
// Genre is json array
final JSONArray genreArry = obj.getJSONArray("genre");
ArrayList<String> genre = new ArrayList<String>();
for (int j = 0; j < genreArry.length(); j++) {
genre.add((String) genreArry.get(j));
}
movie.setGenre(genre);
// adding movie to movies array
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
// stopping swipe refresh
swipeRefreshLayout.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
// stopping swipe refresh
swipeRefreshLayout.setRefreshing(false);
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
if (item.getItemId() == android.R.id.home) {
finish();
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
return true;
}
return false;
}
#Override
public void onBackPressed() {
super.onBackPressed();
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
}
private void noInternet() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
if (info != null) {
if (!info.isConnected()) {
}
}
else {
Toast.makeText(this, "No Internet Connection", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(ListaPreporuka.this, NoConnection.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
}
}
}
First, you don't really need to use the ProgressDialog at all, but that's not the problem.
You simply have to clear your movieList before attaching new data to it.
Something like:
movieList.clear();
That will remove all the elements on your List before adding the new data.
A good place would be inside your onResponse() method. Before the for loop.
P.S.: You're calling swipeRefreshLayout.setRefreshing(true); twice.
More on ArrayList here.

How can implement offline caching of json in Android?

I am working on a articles application like techcrunch I am parsing data from json.
I am parsing title,author and image from json.
Articles are displayed in list-view.
I want to do offline caching means when there is no internet user can read the articles.
Here is my code-
public class OneFragment extends Fragment {
public OneFragment(){}
private static final String TAG = OneFragment.class.getSimpleName();
// Movies json url
private static String URL = "http://url";
private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<Movie>();
private ListView listView;
private CustomListAdapter adapter;
int current_page = 0;
int mPreLast;
SwipeRefreshLayout swipeView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.swip, container, false);
swipeView = (SwipeRefreshLayout) rootView.findViewById(R.id.swipe);
swipeView.setColorScheme(android.R.color.holo_blue_dark, android.R.color.holo_blue_light, android.R.color.holo_green_light, android.R.color.holo_green_dark);
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading...");
pDialog.show();
pDialog.setCancelable(false);
swipeView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
// TODO Auto-generated method stub
swipeView.setRefreshing(true);
Log.d("Swipe", "Refreshing Number");
( new Handler()).postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
swipeView.setRefreshing(false);
onStart();
}
}, 3000);
}
});
listView = (ListView) rootView.findViewById(R.id.list49);
listView.setOnScrollListener(new AbsListView.OnScrollListener()
{
#Override
public void onScrollStateChanged(AbsListView absListView, int i)
{
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount)
{
int lastItem = firstVisibleItem + visibleItemCount;
if(lastItem == totalItemCount){
if (mPreLast != lastItem)
{
mPreLast = lastItem;
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading more articles...");
pDialog.show();
//pDialog.setCancelable(false);
onStart();
}
}
}
});
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int Position,
long offset) {
// TODO Auto-generated method stub
Movie item = (Movie) adapter.getItem(Position);
Intent intent = new Intent(rootView.getContext(), SingleArticle.class);
single.title = item.getTitle();
single.author = item.getAuthor();
startActivity(intent);
}
});
//pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
return rootView;
}
#Override
public void onStart(){
super.onStart();
// calling adapter changes here, just
// to avoid getactivity()null
// increment current page
current_page += 1;
// Next page request
URL = "http://url" + current_page;
//adapter = new CustomListAdapter(this, movieList);
int currentPosition = listView.getFirstVisiblePosition();
adapter = new CustomListAdapter(getActivity(), movieList);
listView.setAdapter(adapter);
listView.setSelectionFromTop(currentPosition + 1, 0);
// changing action bar color
//getActivity().getActionBar().setBackground(
//new ColorDrawable(Color.parseColor("#1b1b1b")));
// Creating volley request obj
JsonArrayRequest movieReq = new JsonArrayRequest(URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Movie movie = new Movie();
movie.setTitle(obj.getString("title"));
movie.setAuthor(obj.getString("author"));
// adding movie to movies array
movieList.add(movie);
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
},new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
new AlertDialog.Builder(getActivity())
.setTitle("No Connectivity ")
.setMessage("Please check your internet connectivity!")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
}
})
//.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
//public void onClick(DialogInterface dialog, int which) {
// do nothing
//}
//})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
hidePDialog();
}
});
AppController.getInstance().addToRequestQueue(movieReq);
//listView.setAdapter(adapter);
}
private View getActionBar() {
// TODO Auto-generated method stub
return null;
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
}
This probably isn't the best way to do it, but it worked for me.
You might find this helpful: http://www.vogella.com/tutorials/JavaSerialization/article.html
I had to do the same in some project. This is what I did:
public final class cacheThis {
private cacheThis() {}
public static void writeObject(Context context, String fileName, Object object) throws IOException {
FileOutputStream fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(object);
oos.flush();
oos.close();
fos.close();
}
public static Object readObject(Context context, String fileName) throws IOException,
ClassNotFoundException {
FileInputStream fis = context.openFileInput(fileName);
ObjectInputStream ois = new ObjectInputStream(fis);
Object object = ois.readObject();
fis.close();
return object;
}
}
To write to file:
cacheThis.writeObject(YourActivity.this, fileName, movieList);
To read from file:
movieList.addAll((List<Movie>) cacheThis.readObject(
VideoActivity.this, fileName));
You have to have your Movie class implements Serializable
You must save the json offline. It can be Db or file system. I will prefer to go with Db part.
The approach is ,every time you get data from server save first in you db then from db you can show it to your UI.
Inserting in Db can be slow but you can use beginTransaction and other methods which will make it lighting fast.
Now How can you save data in Db. You have two ways
You can parse json first and create the table structure for name,url and other fields then run the query
Or store the whole json in Db without parsing .By using GSON or other json parsers this approch will be quite helpful.
I saw you are using Volley. Volley has built-in HTTP Cache mechanism.
So the easiest way is to support HTTP cache headers in your backend. It is very easy and it is transparent to the client side. Volley does the hard work. You can find information here
If you don't have access to the URL you use, you must use internal database to support your application. ContentProvider API is the best way to do that. And the following library is a great library to construct a database and write to it.
https://github.com/TimotheeJeannin/ProviGen
Basically you need to write every item that you pull from the internet to the database and the ListView should show the items from the database using ContentProvider you have just created. When the user opens the app, show the data from the database and then immediately try to pull the new data from your backend.

Categories

Resources