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.
Related
I have an activity that calls JSON data from a foreign database.
Below is my ideal case for my app:
The JSON data is parsed and inserted into an SQLite database on Android
Next activity is started and the newly inserted data is read from the SQLite database
What actually happens:
The JSON data is parsed and inserted into an SQLite database on Android
The next activity is started while data is still being inserted and returns zero when reading from the desired databse for my ListArray in that activity.
How do I force Android to wait until database insertion is completed before starting the next activity?
EDIT
My doInBackground looks as follows:
#Override
protected String doInBackground(String... params) {
StringRequest strReq = new StringRequest(Request.Method.GET,
str, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
// Check for error node in json
if (!error) {
JSONArray jObjInside = jObj.getJSONArray("service_prov_services");
for (int i = 0; i < jObjInside.length(); i++) {
// Now store the user in SQLite
try {
// JSONObject user = jObj.getJSONObject("user");
String service_prov_type = jObj.getString("service_prov_type");
String service_prov_name = jObj.getString("service_prov_name");
String addr_street = jObj.getString("addr_street");
String addr_num = jObj.getString("addr_number");
String addr_plz = jObj.getString("addr_plz");
String addr_city = jObj.getString("addr_city");
JSONObject elem = jObjInside.getJSONObject(i);
if(elem != null){
String service_id = elem.getString("service_id");
String service_type = elem.getString("service_type");
String service_measure = elem.getString("service_measure");
// Inserting row in userServiceProvServices table
db.addUserServiceProvServices(service_id, service_prov_type,
service_prov_name, addr_street, addr_num, addr_plz, addr_city, service_type, service_measure);
Log.d("post_url for service", addr_plz );
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getActivity().getApplicationContext(), "Json error: " +
e.getMessage(), Toast.LENGTH_LONG).show();
}
}
} else {
// Error in login. Get the error message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getActivity().getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getActivity().getApplicationContext(), "Json error: " +
e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Login Error: " + error.getMessage());
Toast.makeText(getActivity().getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
}
});
Log.d("test string to appcntr",strReq.toString());
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
return params[0];
}
onPostExecute looks as follows:
#Override
protected void onPostExecute(String Result) {
//super.onPostExecute(Result);
pdLoading.dismiss();
//this method will be running on UI thread
Log.d(TAG, "Stamp: " + Result);
Bundle args = new Bundle();
args.putString("stampID", Result);
ProviderServiceListFragment frag = new ProviderServiceListFragment();
frag.setArguments(args);
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_frame,
frag)
.commit();
}
With the way I am doing it now, my next Fragment is already called, although the data has not finished being entered into the database. This means the ListArray in the follwoing Fragment is empty because of the missing database data.
I worked on this for a month and finally figured it out for myself (stupid nube I am..) So here is a piece of code inserting a record to sqlite.
On the chosen event ("onClick actionbutton1") a new AsyncTask is created with doInBackground, onPreExecute and onPostExecute.
onPreExecute will setMessage() and show() the progressDialog which will start spinning
onPostExecute will handle the new/next Activity
READ BELOW FOR doInBackground!!
actionButton1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final ProgressDialog progressDialog = new ProgressDialog(AddUpdateEvf.this);
new AsyncTask<Void, Void, Boolean>() {
protected Boolean doInBackground(Void... params) {
doOneThing();
return null;
}
#Override
protected void onPreExecute() {
progressDialog.setMessage("Processing...");
progressDialog.show();
}
protected void onPostExecute(Boolean result) {
evaluationFormOps.close();
progressDialog.dismiss();
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(AddUpdateEvf.this);
alertDialogBuilder.setMessage("Added to Database...")
.setCancelable(false)
.setPositiveButton("Continue", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
i = new Intent(AddUpdateEvf.this, ViewProduct.class);
i.putExtra(EXTRA_ADD_UPDATE, "View");
i.putExtra(EXTRA_PRODUCT_ID, hiddenTextId.getText().toString());
i.putExtra(EXTRA_PRODUCT_NO, productNo_tv.toString());
startActivity(i);
dialog.dismiss();
finish();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
private void doOneThing() {
makeDbRequest();
do {
evfId = newEvf.getEvfId();
}
while (evfId<1);
}
}.execute();
}
});
Note this snippet in the above code called in doInBackground():
private void doOneThing() {
makeDbRequest();
do {
evfId = newEvf.getEvfId();
}
while (evfId<1);
}
Note: The makeDbRequest() handles the insert to sqlite by setting the values and then passing it to another class which handles the cursor and puts the values etc.
Heres a small snippet of relevant code in that class (which you should already have mastered...):
public Evf addEvf(Evf evf, String dBsuccess){
ContentValues values = new ContentValues();
values.put(TableHelper.PRODUCT_IDE,evf.getPRODUCTId());
values.put(TableHelper.CSCORE,evf.getcScore());
values.put(TableHelper.FSCORE,evf.getfScore());
values.put(TableHelper.TSCORE,evf.gettScore());
values.put(TableHelper.WEIGHT,evf.getWeight());
values.put(TableHelper.TEMP,evf.getTemp());
values.put(TableHelper.STATUS,evf.getStatus());
values.put(TableHelper.TIMESTAMP, String.valueOf(evf.getTimeStamp()));
values.put(TableHelper.LOADED, dBsuccess);
long insertid = database.insert(TableHelper.TABLE_EVFS,null,values);
evf.setEvfId((int) insertid);
return evf;
}
So above you can see the Id of, in my case evaluationform(Evf), being set to the insert id. This happens after the insert and you can set any value in your object class (the one with getters and setters...Evf())
Finally, use the do...while statement above to "listen" for the value being set in the object class
This can obviously only happen if the insert was finished and the onPosteExecute takes care of the rest
Hope it helps, crit is welcome, PEACHES!!
Use AsyncTask to process the Database insertion process & then use the onPostExecute method to move away from the current activity.
private class ProcessDatabase extends AsyncTask<String, String, String> {
String sampleData;
#Override
protected String doInBackground(String... params) {
//Call your Database Insert method here.
//In this example, I am inserting sampleData to the DB
return null;
}
#Override
protected void onPostExecute(String result) {
//This gets triggered when the process is complete
}
}
You can start the AsyncTask by adding the following code in your onCreate or where ever you want to start the DB Insertion process:
//in this case I am just passing a string, You can create your own
//custom class & send that as well
ProcessDatabase.execute(myData);
Refer this link for more information. Good luck!
The StringRequest is an Asynchronous request, so upon the executing the those lines onPostExecute will called immediately, so there is no guarantee that the sql update will complete before the next activity is launched.
Call the nextActivity at the end of the onResponse callback method of the StringRequest which way you can guarantee to insert the data to db first and then call the nextActivity.
private void makeJsonRequest(String str) {
StringRequest strReq = new StringRequest(Request.Method.GET,
str, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
// Check for error node in json
if (!error) {
JSONArray jObjInside = jObj.getJSONArray("service_prov_services");
for (int i = 0; i < jObjInside.length(); i++) {
// Now store the user in SQLite
try {
// JSONObject user = jObj.getJSONObject("user");
String service_prov_type = jObj.getString("service_prov_type");
String service_prov_name = jObj.getString("service_prov_name");
String addr_street = jObj.getString("addr_street");
String addr_num = jObj.getString("addr_number");
String addr_plz = jObj.getString("addr_plz");
String addr_city = jObj.getString("addr_city");
JSONObject elem = jObjInside.getJSONObject(i);
if (elem != null) {
String service_id = elem.getString("service_id");
String service_type = elem.getString("service_type");
String service_measure = elem.getString("service_measure");
// Inserting row in userServiceProvServices table
db.addUserServiceProvServices(service_id, service_prov_type,
service_prov_name, addr_street, addr_num, addr_plz, addr_city, service_type, service_measure);
Log.d("post_url for service", addr_plz);
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getActivity().getApplicationContext(), "Json error: " +
e.getMessage(), Toast.LENGTH_LONG).show();
}
}
goNextActivity();
} else {
// Error in login. Get the error message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getActivity().getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getActivity().getApplicationContext(), "Json error: " +
e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Login Error: " + error.getMessage());
Toast.makeText(getActivity().getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
}
});
Log.d("test string to appcntr", strReq.toString());
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void goNextActivity(){
//this method will be running on UI thread
ProviderServiceListFragment frag = new ProviderServiceListFragment();
frag.setArguments(args);
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_frame,
frag)
.commit();
}
I'm trying to get the value the user enters in the userNameVar and passwordVar variables, and then compare them to the values stored in my database. However, when I enter the details, which are the same as what I have stored in my database, I get the following message:
Error message
Here is my login class code
public class Login extends AppCompatActivity implements View.OnClickListener {
private EditText usernameField;
private EditText passwordField;
private static Button login_btn;
TextView register_link;
String userNameVar = "";
String passwordVar = "";
private ProgressDialog pDialog;
JSONParser jParser = new JSONParser();
User userObj;
DatabaseUserList databaseUserList = new DatabaseUserList();
private static final String TAG_SUCCESSFUL = "Successful";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_page);
login_btn = (Button) findViewById(R.id.login_button);
usernameField = (EditText) findViewById(R.id.etUsername);
passwordField = (EditText) findViewById(R.id.etPassword);
//starts to listen for clicks on this button
login_btn.setOnClickListener(this);
register_link = (TextView) findViewById(R.id.register_link);
register_link.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.login_button:
//null object reference problem here
Log.d("Username and password",
userNameVar = usernameField.getText().toString();
passwordVar = passwordField.getText().toString();
usernameField.getText().toString());
validateUser(userNameVar, passwordVar);
break;
}
}
private void validateUser (String username, String password)
{
new LogtheuserIn().execute();
}
private void resultsofloginAttmempt(User u)
{
if(u != null)
{
Log.d("User", userObj.toString() + "User must have logged in successfully");
}
}
private void userLoggedIn()
{
Intent intent = new Intent(this, FirstPage.class);
//User has to implement serializable
intent.putExtra("Userisin", userObj);
startActivity(intent);
}
public class LogtheuserIn extends AsyncTask<String,String,String>
{
#Override
protected void onPreExecute()
{
Log.d("onPrexecute", "on the preExecutePart");
pDialog = new ProgressDialog(Login.this);
pDialog.setMessage("Loading users");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... args)
{
List<NameValuePair> arguements = new ArrayList<NameValuePair>();
try{
Log.d("This is the username ", "and password taken from the input fields");
String loginDetails = ServerConnection.SERVER_ADDRESS + "login.php?userName=" + userNameVar + "?password" + passwordVar;
JSONObject jObject = jParser.makeHttpRequest(loginDetails, "GET", arguements);
Log.d("All users", jObject.toString());
int success = jObject.getInt(TAG_SUCCESSFUL);
} catch (Exception e) {
pDialog.dismiss();
runOnUiThread(new Runnable()
{
public void run()
{
Toast.makeText(getApplicationContext(), "Problem with the server",
Toast.LENGTH_SHORT).show();
}
});
}
return null;
}
protected void onPostExecute(String dismissable)
{
//Dismiss the dialogue after we have
//gotten the user(s)
pDialog.dismiss();
Login.this.runOnUiThread(
new Runnable() {
public void run()
{
resultsofloginAttmempt(userObj);
Log.d("Array details", databaseUserList.getListOfUsers().toString());
}
}
);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_login, 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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Recheck findViewById(R.id.whatisyourrealid); because it's returning null.
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.
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.
I have developed an android application by following this tutorial http://programmerguru.com/android-tutorial/how-to-sync-sqlite-on-android-to-mysql-db/
But its not working when iam running in the emulator Here is my code which i got stuck
When i run the application in the emulator its not working.
public class MainActivity extends Activity {
//DB Class to perform DB related operations
DBController controller = new DBController(this);
//Progress Dialog Object
ProgressDialog prgDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//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://localhost/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();
}
}
}
Here iam not understanding whether to keep localhost or my machines IP Address
client.post("http://localhost/sqlitemysqlsync/insertuser.php",params ,new AsyncHttpResponseHandler
Please Help me to solve this
localhost will not work , connect your mobile device to the same WAN using wifi as your pc, find the Ip of your machine and use the same in place of localhost.
Connect your phone and laptop to the same wifi connection.
Go to cmd type ip config.
Look for wireless wifi ipv4.
Note it type on local host space http://192.168.1.0/sqlitemysqlsync/insertuser.php
Then run