Post value to server when no internet connection android studio - sqlite

I'm trying to send a value to the server when the connection doesn't exist, when it connects to the internet it runs fine and is saved to the server and sqlite. but the problem arises when switching state from offline to online. I send one value to the server when the connection is offline but when the state moves to online the value I sent earlier becomes multiple on the server while in the sqlite database only one value is stored.
this is my network state checker class
public class NetworkStateCheckerNama extends BroadcastReceiver {
//context and database helper object
private Context context;
private Database db;
ApiRequestData apiRequestData;
#Override
public void onReceive(Context context, Intent intent) {
this.context = context;
apiRequestData = ServiceGenerator.createBaseService(this.context, ApiRequestData.class);
db = new Database(context);
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
//if there is a network
if (activeNetwork != null) {
//if connected to wifi or mobile data plan
if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI || activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
//getting all the unsynced user
Cursor cursor2 = db.getUnsyncedNama();
if (cursor2.moveToFirst()) {
do {
//calling the method to save the unsynced name to MySQL
Nama(
cursor2.getString(cursor2.getColumnIndexOrThrow(Database.KOLOM_NAMA_COBA)),
cursor2.getString(cursor2.getColumnIndexOrThrow(Database.KOLOM_NIP_COBA))
);
} while (cursor2.moveToNext());
}
}
}
}
private void Nama(final String nama,final String nip) {
//Call call = retrofit.create(APIInterface.class).saveName(name);
Call call = apiRequestData.nama_query(nama,nip);
call.enqueue(new Callback<Responses>() {
#Override
public void onResponse(Call<Responses> call, Response<Responses> response) {
if (response.code() == 200){
db.updateNamaStatus(nip, MainActivity.NAME_SYNCED_WITH_SERVER);
//sending the broadcast to refresh the list
context.sendBroadcast(new Intent(MainActivity.DATA_SAVED_BROADCAST_MAIN));
}
}
#Override
public void onFailure(Call<Responses> call, Throwable t) {
}
});
}
this is my MainActivity Class
public class MainActivity extends AppCompatActivity {
Session session;
Button buttonLogout,buttonKirim;
TextView textViewNamaMain, textViewNipMain;
EditText editTextNamaMain;
Database database;
private AdapterNama mAdapter;
private RecyclerView listviewNama;
ApiRequestData apiRequestData;
//1 means data is synced and 0 means data is not synced
public static final int NAME_SYNCED_WITH_SERVER = 1;
public static final int NAME_NOT_SYNCED_WITH_SERVER = 0;
//a broadcast to know weather the data is synced or not
public static final String DATA_SAVED_BROADCAST_MAIN = "com.example.myapplication.datasave2";
ArrayList<Nama> namaArray;
ArrayList<User> users;
BroadcastReceiver broadcastReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
session = new Session(this);
buttonLogout = findViewById(R.id.buttonLogout);
buttonKirim = findViewById(R.id.buttonKirim);
textViewNipMain = findViewById(R.id.textViewNipMain);
textViewNamaMain = findViewById(R.id.textViewNamaMain);
editTextNamaMain = findViewById(R.id.editTextTextNamaMain);
String nip = getIntent().getStringExtra("nip");
listviewNama = findViewById(R.id.lv_nama);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
listviewNama.setLayoutManager(layoutManager);
listviewNama.setItemAnimator(new DefaultItemAnimator());
database = new Database(this);
namaArray = new ArrayList<>();
users = new ArrayList<>();
apiRequestData = ServiceGenerator.createBaseService(this, ApiRequestData.class);
textViewNipMain.setText(nip);
registerReceiver(new NetworkStateCheckerNama(), new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
loadDaftarNama(nip);
broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//loading the names again
loadDaftarNama(nip);
}
};
registerReceiver(broadcastReceiver, new IntentFilter(DATA_SAVED_BROADCAST_MAIN));
if(!session.isUserLogin()){
logout();
}
buttonKirim.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SimpanKeServer();
}
});
buttonLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
logout();
}
});
users.clear();
Cursor cursor = database.getUsersWhereNip(nip);
if (cursor.moveToFirst()) {
do {
User user = new User(
cursor.getString(cursor.getColumnIndexOrThrow(Database.KOLOM_NIP)),
cursor.getString(cursor.getColumnIndexOrThrow(Database.KOLOM_NAMA)),
cursor.getString(cursor.getColumnIndexOrThrow(Database.KOLOM_PASSWORD)),
cursor.getInt(cursor.getColumnIndexOrThrow(Database.KOLOM_STATUS))
);
users.add(user);
textViewNamaMain.setText(user.getNama());
} while (cursor.moveToNext());
}
}
private void SimpanKeServer(){
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Saving Name...");
progressDialog.show();
String nama = editTextNamaMain.getText().toString();
String nip = textViewNipMain.getText().toString();
Call call = apiRequestData.nama_query(nama,nip);
call.enqueue(new Callback<Responses>() {
#Override
public void onResponse(Call<Responses> call, Response<Responses> response) {
progressDialog.dismiss();
if(response.code() == 200){
//if there is a success
//storing the name to sqlite with status synced
SaveNamaToLocal(nama,nip,NAME_SYNCED_WITH_SERVER);
Toast.makeText(MainActivity.this, "Berhasil", Toast.LENGTH_SHORT).show();
}else {
progressDialog.dismiss();
//if there is some error
//saving the name to sqlite with status unsynced
SaveNamaToLocal(nama,nip,NAME_NOT_SYNCED_WITH_SERVER);
Toast.makeText(MainActivity.this, "Gagal", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<Responses> call, Throwable t) {
progressDialog.dismiss();
SaveNamaToLocal(nama,nip,NAME_NOT_SYNCED_WITH_SERVER);
Toast.makeText(MainActivity.this, "Gagal", Toast.LENGTH_SHORT).show();
}
});
}
private void SaveNamaToLocal(String nama, String nip, int status){
database.Nama(nama,nip,status);
Nama namas = new Nama(nama,nip,status);
namaArray.add(namas);
refreshList();
}
private void loadDaftarNama(String nip) {
namaArray.clear();
Cursor cursor = database.getNama(nip);
if (cursor.moveToFirst()) {
do {
Nama nama = new Nama(
cursor.getString(cursor.getColumnIndexOrThrow(Database.KOLOM_NAMA_COBA)),
cursor.getString(cursor.getColumnIndexOrThrow(Database.KOLOM_NIP_COBA)),
cursor.getInt(cursor.getColumnIndexOrThrow(Database.KOLOM_STATUS_NAMA_COBA))
);
namaArray.add(nama);
} while (cursor.moveToNext());
}
mAdapter = new AdapterNama(this, namaArray);
listviewNama.setAdapter(mAdapter);
}
#SuppressLint("NotifyDataSetChanged")
private void refreshList() {
mAdapter.notifyDataSetChanged();
}
private void logout(){
session.updateUserLoginStatus(false);
finish();
startActivity(new Intent(MainActivity.this,LoginActivity.class));
}
}
this when online
enter image description here
enter image description here
this the problem when state internet switch from offline to online
enter image description here
enter image description here
Even in server send 3 same values
I'm sorry for my english and my question structure im new in programmer, and thank you for the answer

Related

FirebaseAuth.getInstance().getCurrentUser().getUid() always pointing to same ID

I'm trying to make a feature in my Android studio app which allows users to book appointment with a fixed list of doctors through Firebase realtime database. The problem is that FirebaseAuth.getInstance().getCurrentUser().getUid() is always pointing to same ID and so instead of new appointment details being added via children nodes in the parent node, the existing details in children nodes are being overwritten. Here's my code-
DoctorList.java-
public class DoctorList extends AppCompatActivity {
TextView doc1,doc2,doc3,doc4;
FirebaseAuth mAuth;
DatabaseReference patUser;
ProgressDialog loader;
FirebaseDatabase database= FirebaseDatabase.getInstance();
String Date;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_doctor_list);
Intent intent = getIntent();
// receive the value by getStringExtra() method
// and key must be same which is send by first
// activity
String email = intent.getStringExtra("message_key");//patient email
doc1=findViewById(R.id.doc1);
doc2=findViewById(R.id.doc2);
doc3=findViewById(R.id.doc3);
doc4=findViewById(R.id.doc4);
loader = new ProgressDialog(this);
mAuth = FirebaseAuth.getInstance();
FirebaseUser user= mAuth.getInstance().getCurrentUser();
patUser= database.getReference().child("Patient Appointments");
doc1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
loader.setMessage("Please wait....");
loader.setCanceledOnTouchOutside(false);
loader.show();
Intent intent= new Intent( DoctorList.this, Book.class);
intent.putExtra("message_key1", "elise#doc.com");
intent.putExtra("message_key2", email);
startActivity(intent);
// create the get Intent object
Intent intent1 = getIntent();
// receive the value by getStringExtra() method
// and key must be same which is send by first
// activity
Date = intent1.getStringExtra("message");
//Toast.makeText(PatientPage.this, str, Toast.LENGTH_SHORT).show();
String currentUserId = mAuth.getCurrentUser().getUid();
patUser= database.getReference().child("Patient Appointments").child(currentUserId);
//HashMap userInfo = new HashMap();
HashMap userInfo = new HashMap();
userInfo.put("Date",Date);
userInfo.put("Patient",email);
userInfo.put("Doctor","Dr.Elise Heather");
userInfo.put("Phone","5925866");
userInfo.put("Status","Pending");
patUser.updateChildren(userInfo).addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if (task.isSuccessful()){
Toast.makeText(DoctorList.this, "Little more to go....", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(DoctorList.this, task.getException().toString(), Toast.LENGTH_SHORT).show();
}
}
});
loader.dismiss();
//Intent intent2= new Intent( DoctorList.this, PatientPage.class);
//startActivity(intent2);
}
});
}
}
Book.java-
public class Book extends AppCompatActivity {
TextView selectedDate;
Button calenderButton,ok;
FirebaseAuth mAuth;
DatabaseReference docUser;
ProgressDialog loader;
FirebaseDatabase database= FirebaseDatabase.getInstance();
String Date;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_book);
Intent intent = getIntent();
// receive the value by getStringExtra() method
// and key must be same which is send by first
// activity
String docEmail = intent.getStringExtra("message_key1");
String patEmail = intent.getStringExtra("message_key2");
selectedDate=findViewById(R.id.text);
calenderButton=findViewById(R.id.calender);
ok=findViewById(R.id.ok);
loader = new ProgressDialog(this);
mAuth = FirebaseAuth.getInstance();
FirebaseUser user= mAuth.getInstance().getCurrentUser();
docUser= database.getReference().child("Doctor Schedule");
MaterialDatePicker materialDatePicker=MaterialDatePicker.Builder.datePicker().
setTitleText("Select date").setSelection(MaterialDatePicker.todayInUtcMilliseconds()).build();
calenderButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
materialDatePicker.show(getSupportFragmentManager(),"Tag_Picker");
materialDatePicker.addOnPositiveButtonClickListener(new MaterialPickerOnPositiveButtonClickListener() {
#Override
public void onPositiveButtonClick(Object selection) {
selectedDate.setText(materialDatePicker.getHeaderText());
Date=materialDatePicker.getHeaderText();
}
});
}
});
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (Date != null) {
String currentUserId = mAuth.getCurrentUser().getUid();
docUser = database.getReference().child("Doctor Schedule").child(currentUserId);
//HashMap userInfo = new HashMap();
HashMap userInfo = new HashMap();
userInfo.put("Date", Date);
userInfo.put("Patient", patEmail);
userInfo.put("Doctor", docEmail);
userInfo.put("Status", "Pending");
docUser.updateChildren(userInfo).addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if (task.isSuccessful()) {
Toast.makeText(Book.this, "Appointment booked", Toast.LENGTH_SHORT).show();
Intent intent= new Intent( Book.this, DoctorList.class);
intent.putExtra("message", Date);
startActivity(intent);
} else {
Toast.makeText(Book.this, task.getException().toString(), Toast.LENGTH_SHORT).show();
}
}
});
}
else {
Toast.makeText(Book.this, "Select date!", Toast.LENGTH_SHORT).show();
}
}
});
}
}
Suppose a user with email athy#gmail.com books appointment and in Firebase database there's already details of booking by another user nivi#gm.com . Then the details of the latter user in the parent node (ID) gets overwritten by user athy#gmail.com and it looks like this. I don't think I've written code for overwriting instead of updating since it works fine in other Android studio projects, so I'm guessing FirebaseAuth.getInstance().getCurrentUser().getUid() is the one always pointing to same ID which I've circled in the image.
How do I fix this?

Refresh recyclerView with new data Retrofit

I am using Retrofit 2.0 to retrieve data from my api and using a recyclerView to display it.
My main activity has a tab layout and one of those tabs has the recyclerView and the fragment class for that tab is being used to retrieve the data and update the layout.
In my main layout I have a fab which makes a post (all posts are being retrieved in fragment class) and this fab has it's function of making the post in main activity.
So how can I refresh the layout when the fab's function is over and the post is successfully saved in my database?
Basically
User clicks fab > Makes his post > Alert dialog closes > recyclerView should be refreshed with new data added.
My Fragment Class :
public class PostsRecentTab extends Fragment {
private static final String TAG = MainActivity.class.getSimpleName();
private RecyclerView feedView;
private ProgressDialog pDialog = MainActivity.pDialog;
LinearLayoutManager layoutManager;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.tab_recent_posts, container, false);
pDialog.setCancelable(false);
layoutManager = new LinearLayoutManager(this.getContext());
feedView = (RecyclerView) v.findViewById(R.id.feedView);
requestData();
return v;
}
public void requestData() {
SocialHubAPI apiService = ApiClient.getClient().create(SocialHubAPI.class);
pDialog.setMessage("Refreshing...");
showDialog();
Call<StatusResponse> call = apiService.getStatuses();
call.enqueue(new Callback<StatusResponse>() {
#Override
public void onResponse(Call<StatusResponse> call, Response<StatusResponse> response) {
int statusCode = response.code();
List<Status> statuses = response.body().getStatuses();
Log.d(TAG, "Status Code: " + statusCode);
hideDialog();
updateView(statuses);
}
#Override
public void onFailure(Call<StatusResponse> call, Throwable t) {
Log.e(TAG, t.toString());
}
});
}
private void updateView(List<Status> statuses) {
StatusesAdapter adapter = new StatusesAdapter(statuses, R.layout.feed_item, getContext());
feedView.setLayoutManager(layoutManager);
feedView.setAdapter(adapter);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
My Fab On Click :
FloatingActionButton postStatus = (FloatingActionButton) findViewById(R.id.postStatus);
postStatus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Post Status");
// Set up the input
final EditText input = new EditText(MainActivity.this);
// Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
input.setInputType(InputType.TYPE_CLASS_TEXT);
builder.setView(input);
// Set up the buttons
builder.setPositiveButton("Post", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
postText = input.getText().toString();
processPost(postText, sessionManager.getToken());
Snackbar.make(view, "Status posted!", Snackbar.LENGTH_LONG).show();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
});
Fab onClick calls this method :
protected void processPost(String postText, String token) {
SocialHubAPI apiService = ApiClient.getClient().create(SocialHubAPI.class);
pDialog.setMessage("Posting...");
showDialog();
final PostRequest postRequest = new PostRequest();
postRequest.setStatus(postText);
Call<PostResponse> call = apiService.postStatus(postRequest, token);
call.enqueue(new Callback<PostResponse>() {
#Override
public void onResponse(Call<PostResponse> call, Response<PostResponse> response) {
hideDialog();
Toast.makeText(getApplicationContext(), "Status Posted Successfully!", Toast.LENGTH_LONG).show();
}
#Override
public void onFailure(Call<PostResponse> call, Throwable t) {
Log.e(TAG, t.toString());
}
});
}
You should invalidate your list in updateView(List<Status> statuses) instead of setting the adapter again. Instantiate adapter only in onCreate().
This function should be like this:
adapter.addNewStatutes(statuses)
in Adapter class
public void addNewStatutes(List<Status> statuses)
{
this.statuses.addAll(statuses);
notifyDataSetChanged();
}
Also in onResponse use EventBus or Rx, because your view can be destroyed and this method can crash your app.
Added notifyDataSetChanged as per docs.

android fragment reloading (onCreate) each time when back Button pressed

I am new in android using fragments in my Project. first time my fragment is creating then api called and get data load in fragment. here when i clicked at any item i replaced fragment by another fragment there also another api called and load data to fragment.
now here problem situation generated for me.
from here i back Button pressed.
fragment reloading same as first time creating but it should be show data as i left before going to next fragment.
so please provide me solution how i can get same data as i left means savedInstanceState data.
im my first fragment getCategory method call Api and get Data first time when i choose any category i replace fragment with another fragment but when i m returning same getCategory method recall perform same process as it first time.
fragment should not call api method again on backpressed it should show same category on this i clicked before.
my first fragment where calling api......
public class LandingFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private GridLayoutManager gridLayoutManager;
private static RecyclerView category_Grid;
private Fragment myFragment = null;
ProgressBar mProgressView;
View mLoginFormView;
private Category category;
private CategoryAdapter categoryAdapter;
private List<CategoryObject> rowListItem;
private String productId;
private OnFragmentInteractionListener mListener;
public LandingFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment LandingFragment.
*/
// TODO: Rename and change types and number of parameters
public static LandingFragment newInstance(String param1, String param2) {
LandingFragment fragment = new LandingFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v= inflater.inflate(R.layout.fragment_landing, container, false);
return v;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
initViews(view);
RecyclerViewListeners();
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Activity context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
private void initViews(final View v) {
mLoginFormView = (View)v.findViewById(R.id.mainView);
mProgressView = (ProgressBar)v.findViewById(R.id.login_progress);
category_Grid = (RecyclerView)v.findViewById(R.id.cat_grid);
category_Grid.setHasFixedSize(true);
gridLayoutManager = new GridLayoutManager(getActivity(), 3);
category_Grid.setLayoutManager(gridLayoutManager);
}
private void RecyclerViewListeners(){
category_Grid.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), category_Grid, new ItemClickListener(){
#Override
public void onClick(View view, int position) {
String entityId = rowListItem.get(position).getCategoryId();
String catName = rowListItem.get(position).getName();
Integer ishave = rowListItem.get(position).getIshaveSubcategories();
if(ishave==1) {
myFragment = SubcategoryFragment.newInstance(""+catName, "" + entityId);
ActivityUtils.launchFragementWithAnimation(myFragment, getActivity());
}else{
myFragment = ProductListFragment.newInstance("", "" + entityId);
ActivityUtils.launchFragementWithAnimation(myFragment, getActivity());
}
}
#Override
public void onLongClick(View view, int position) {
}
}));
}
public void getCategory() {
showProgress(true);
String URL = getResources().getString(R.string.category_api);
StringRequest req = new StringRequest(Request.Method.POST,URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
VolleyLog.v("Response:%n %s", response);
Gson gson = new GsonBuilder().serializeNulls().create();
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.getString("status").equals(getResources().getString(R.string.response_success))){
category = gson.fromJson(response, Category.class);
rowListItem = category.getCategory();
if(navigationUpdated){
someEventListener.someEvent(rowListItem);
navigationUpdated = false;
}
Log.d("CATEGORYID::::::::",""+rowListItem.get(1).getCategoryId());
categoryAdapter = new CategoryAdapter(getActivity(),rowListItem);
category_Grid.setAdapter(categoryAdapter);
categoryAdapter.notifyDataSetChanged();
return;
}
else if (jsonObject.getString("status").equals(getResources().getString(R.string.login_Er_respose))){
Log.e("","ERRORRRRRR");
return;
}
} catch (JSONException e) {
showProgress(false);
Log.e("My App", "Could not parse malformed JSON: \"" + response + "\"");
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
showProgress(false);
VolleyLog.e("Error: ", error.getMessage());
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
params.put("Content-Type","application/x-www-form-urlencoded");
return params;
}
};
AppController.getInstance().addToRequestQueue(req);
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
private void showProgress(final boolean show) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
mLoginFormView.animate().setDuration(shortAnimTime).alpha(
show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
});
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mProgressView.animate().setDuration(shortAnimTime).alpha(
show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
}
});
} else {
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
}
You can check your rowListItem.size(), if it's size is 0 then call getCategory() service, otherwise load your data from your rowListItem. Here is sample code which I am using to load data from arraylist if it is not empty:
if (mArrayArticle.size() == 0) {
isDataLoading = true;
mRecyclerList.setVisibility(View.INVISIBLE);
getCategory();
} else {
mHomeItemAdapter = new HomeItemAdapter(getActivity(), mArrayArticle, this);
mRecyclerList.setAdapter(mHomeItemAdapter);
}
Here mArrayArticle is my ArrayList, Hope it will help you.
for more clarification i want to tell..
how i implement the #Bhvk_AndroidBee solution
fragment backpressed call onActivityCreated Method so first overridethis method in fragment
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//here you can check null condition for rowListItem
}
}
inside onActivityCreated method I checked the condition like that
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if(rowListItem!=null){
categoryAdapter = new CategoryAdapter(getActivity(),rowListItem);
category_Grid.setAdapter(categoryAdapter);
categoryAdapter.notifyDataSetChanged();
}else {
//call the method for first time creating your view
getCategory();
}
}
hope this would be helpfull for more strugglers like me...

show GPS location on google map

I want to show the GPS location of the user on google maps by retrieving the longitude and latitude from SQLite. Please tell me the procedure to show the information from SQLite on Google map. Here is the code I am using for saving the longitude and latitude. And I am also using the link
http://www.androidhive.info/2012/01/android-working-with-google-maps/
for maps but don't know how to retrieve the longitude and latitude from SQLite.
MAiN ACTIVITY:
public class MainActivity extends Activity {
ListView list;
mylocation loc = new mylocation();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LocationManager mylocman = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener myloclist = new mylocation();
mylocman.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,myloclist);
loc.updateDatabase(this);
GPSdatabase myDatabase=new GPSdatabase(this);
myDatabase.open();
Cursor cursor=myDatabase.getAllRows();
cursor.moveToFirst();
ArrayList listContents = new ArrayList();
for (int i = 0; i < cursor.getCount(); i++)
{
listContents.add("Lat=" +cursor.getString(1) +" "+"Log "+ cursor.getString(2));
cursor.moveToNext(); } myDatabase.close();
ListAdapter adapter=new ArrayAdapter(this,android.R.layout.simple_dropdown_item_1line, listContents);
list=(ListView)findViewById(R.id.list);
list.setAdapter(adapter);
}
/*public void updateDatabase(){
GPSDatabase myDatabase=new GPSDatabase(context);
myDatabase.open();
myDatabase.insertRow(lat.substring(0,4),log.substring(0,4));
myDatabase.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.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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}}
My Location class:
public class mylocation implements LocationListener {
String lat=null;
String log=null;
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
String text="my latitude="+location.getLatitude()+"longitude="+location.getLongitude();
lat=location.getLatitude()+"";
log=location.getLongitude()+"";
//updateDatabase();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void updateDatabase(Context context)
{
if(lat!=null || log!=null)
{
GPSdatabase myDatabase=new GPSdatabase(context);
myDatabase.open();
myDatabase.insertRows(lat.substring(0,4),log.substring(0,4));
myDatabase.close();
}
}
}
My DATABASE CLASS:
public class GPSdatabase {
private Context context;
private DbHelper dbHelper;
public final String DBNAME = "gps1";
public final int DBVERSION = 3;
public SQLiteDatabase db;
public final String COLUMN2 = "latitude";
public final String COLUMN3 = "longitude";
public final String COLUMN1 = "locationId";
public final String TABLENAME = "location";
public final String CREATERDB = "create table location(locationId integer primary key autoincrement, latitude text not null, longitude text not null);";
public GPSdatabase(Context context) {
this.context = context;
dbHelper = new DbHelper(context);
}
public class DbHelper extends SQLiteOpenHelper {
public DbHelper(Context context) {
super(context, DBNAME, null, DBVERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String CREATE_TABLE = "CREATE TABLE " + "location" + "(" +
"latitude" + " TEXT," +
"longitude" + " TEXT)";
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
public long insertRows(String column2, String column3) {
ContentValues value = new ContentValues();
value.put(COLUMN2, column2);
value.put(COLUMN3, column3);
return db.insert(TABLENAME, null, value);
}
public Cursor getAllRows() {
Cursor cursor = db.query(TABLENAME, new String[] {
COLUMN1,
COLUMN2,
COLUMN3
}, null, null, null, null, null);
return cursor;
}
public void open() throws SQLException {
db = dbHelper.getWritableDatabase();
//return true;
}
public void close() {
dbHelper.close();
//return true;
}
}
Why not showing directly the location of the user without saving and retrieving back and forth?
if you tell to the map to show user location, it is done automatically:
http://developer.android.com/reference/com/google/android/gms/maps/GoogleMap.html#setMyLocationEnabled(boolean)
map.setMyLocationEnabled(true);

how to get the data and update to UI when new record available in SqliteDB?

I am working on a sample application by communicate with .net web service.In my application I am getting records from web service into my activity class then i am displaying entire records in ListView by using ArrayAdapter and also i am running a service class at background process for get the latest record from web service when the new records are available from web service then i am saving those records in to SQLite data base.This process is happening at back ground.Here i would like to get the latest data from SQLite DB and append to my ListView.
I have implemented Activity class as follows:
public class GetMsgsScreen extends ListActivity
{
private LayoutInflater mInflater;
private Vector<RowData> data;
RowData rd;
static String[] userName = null;
static String[] usrMessages = null;
private Integer[] imgid = null;
ShoutRepeatService bg;
////////////////////////////////////////////////////
List<Message> resultShoutMessage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
resultMessage = new ParseXml().convertMessages(new Model().getMessages("0"));
usrMessages = new String[resultMessage.size()];
userName = new String[resultMessage.size()];
imgid = new Integer[resultMessage.size()];
getSharedPreferences("Values", 0).edit().putString("msgid",resultMessage.get(0).getMessageID()).commit();
for(int i=0;i<resultMessage.size();i++)
{
Log.v("GetMsgsScreen", "resultMessage*******>>>>"+resultMessage.get(i).getMessageText());
Log.v("GetMsgsScreen", "resultNames*******>>>>"+resultMessage.get(i).getUserFirstName());
usrMessages[i] = resultMessage.get(i).getMessageText();
userName[i] = resultMessage.get(i).getUserFirstName();
imgid[i] = R.drawable.person;
}
///////////////////////////////////////////////////////
mInflater = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
data = new Vector<RowData>();
for(int i=0;i<userName.length;i++){
try {
rd = new RowData(i,userName[i],usrMessages[i]);
} catch (ParseException e) {
e.printStackTrace();
}
data.add(rd);
}
CustomAdapter adapter = new CustomAdapter(this, R.layout.list, R.id.usrName, data);
setListAdapter(adapter);
bindService(new Intent(GetMsgsScreen.this, RepeatService.class), mConnection, Context.BIND_AUTO_CREATE);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
getListView().setTextFilterEnabled(true);
}
#Override
protected void onDestroy() {
unbindService(mConnection);
super.onDestroy();
}
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder binder) {
bg = ((RepeatService.MyBinder) binder).getService();
Toast.makeText(GetMsgsScreen.this, "Connected",
Toast.LENGTH_SHORT).show();
}
public void onServiceDisconnected(ComponentName className) {
bg = null;
}
};
public void onListItemClick(ListView parent, View v, int position, long id) {
Toast.makeText(getApplicationContext(), "You have selected "
+(position+1)+"th item", Toast.LENGTH_SHORT).show();
}
private class CustomAdapter extends ArrayAdapter<RowData> {
public CustomAdapter(Context context, int resource, int textViewResourceId, List<RowData> objects) {
super(context, resource, textViewResourceId, objects);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
TextView name = null;
TextView messages = null;
ImageView i11=null;
RowData rowData= getItem(position);
if(null == convertView){
convertView = mInflater.inflate(R.layout.list, null);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
}
holder = (ViewHolder) convertView.getTag();
name = holder.gettitle();
name.setText(rowData.mName);
messages = holder.getdetail();
messages.setText(rowData.mMessage);
i11=holder.getImage();
i11.setImageResource(imgid[rowData.mId]);
return convertView;
}
private class ViewHolder {
private View mRow;
private TextView names = null;
private TextView messageText = null;
private ImageView i11=null;
public ViewHolder(View row) {
mRow = row;
}
public TextView gettitle() {
if(null == names){
names = (TextView) mRow.findViewById(R.id.usrName);
}
return names;
}
public TextView getdetail() {
if(null == messageText){
messageText = (TextView) mRow.findViewById(R.id.msgText);
}
return messageText;
}
public ImageView getImage() {
if(null == i11){
i11 = (ImageView) mRow.findViewById(R.id.img);
}
return i11;
}
}
}
}
I have implemented background service class as follows:
public class RepeatService extends Service
{
List<Message> resultMessage;
String[] userNameLatest = null;
String[] usrMessagesLatest = null;
String[] usrMessageID = null;
String msgID = null;
private Timer timer = new Timer();
private static final long UPDATE_INTERVAL = 500;
SQLiteDB db;
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
pollForUpdates();
super.onCreate();
}
private void pollForUpdates() {
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
Log.v("!!!!!!!!!!!!!!!!", "service is calling");
msgID = getSharedPreferences("Values", 0).getString("msgid","");
resultMessage = new ParseXml().convertMessages(new Model().getMessages(msgID));
usrMessagesLatest = new String[resultMessage.size()];
userNameLatest = new String[resultMessage.size()];
usrMessageID = new String[resultMessage.size()];
db = new SQLiteDB();
for(int i=0;i<resultMessage.size();i++)
{
Log.v("RepeatService", "getMessageID------>"+resultMessage.get(i).getMessageID());
Log.v("RepeatService", "getMessageText------>"+resultMessage.get(i).getMessageText());
Log.v("RepeatService", "getUserFirstName------>"+resultMessage.get(i).getUserFirstName());
usrMessagesLatest[i] = resultMessage.get(i).getMessageText();
userNameLatest[i] = resultMessage.get(i).getUserFirstName();
usrMessageID[i] = resultMessage.get(i).getMessageID();
//Save the data into Sqlite db here
db.insertValues(usrMessageID[i], userNameLatest[i], usrMessagesLatest[i], RepeatService.this);
}
}
}, 0, UPDATE_INTERVAL);
Log.v(getClass().getSimpleName(), "Timer started.");
}
public class MyBinder extends Binder {
ShoutRepeatService getService()
{
return ShoutRepeatService.this;
}
}
}
The above class always run at back ground if any new record available from web service then store the record into Sqlite db.
From the above code i can save the data in to Sqlite data base then
How can i show the latest record to my ListView on My Activity class?
please any body help me with code explanation.........
I would probably use a BroadcastReceiver that is notified from the service when something new has been added. It could then update your list. Also look at LocalBroadcastManager since all the communication is in your app.

Resources