Hey guys I am creating an app which gets the current co-ordinates of the user and then show them on the map which is implemented on the activity.
But my problem is that the map is not movable. I have tried getUiSettings().setScrollGesturesEnabled(true); but its not working.
The Code is given below:
public class Page1 extends AppCompatActivity implements OnMapReadyCallback {
private GoogleMap mMap;
String em,n;
private DrawerLayout mDrawer;
private Toolbar toolbar;
private NavigationView nvDrawer;
TextView tv1;
private static final int MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 2;
protected LocationManager locationManager;
Location location;
private ActionBarDrawerToggle drawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page1);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
nvDrawer = (NavigationView) findViewById(R.id.nvView);
setupDrawerContent(nvDrawer);
// Find our drawer view
mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerToggle = setupDrawerToggle();
// Tie DrawerLayout events to the ActionBarToggle
mDrawer.addDrawerListener(drawerToggle);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.my_menu_option, menu);
tv1= (TextView) nvDrawer.findViewById(R.id.textView5);
Intent i=getIntent();
em=i.getStringExtra("k");
tv1.setText(em);
return true;
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
Location nwLocation =getLocation(LocationManager.NETWORK_PROVIDER);
if (nwLocation != null) {
double latitude = nwLocation.getLatitude();
double longitude = nwLocation.getLongitude();
LatLng location = new LatLng(latitude,longitude);
mMap.addMarker(new MarkerOptions().position(location).title("I am here"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(location));
float zoomLevel = 16; //This goes up to 21
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(location, zoomLevel));
googleMap.getUiSettings().setScrollGesturesEnabled(true);
}
else {
showSettingsAlert("Network");
}
}
public Location getLocation(String provider) {
if (locationManager.isProviderEnabled(provider)) {
if(ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this,new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
}
else {
if (locationManager != null) {
location = locationManager.getLastKnownLocation(provider);
return location;
}
}
}
return null;
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 ) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Permission Granted", Toast.LENGTH_SHORT).show();
}
else if(grantResults[0]==PackageManager.PERMISSION_DENIED) {
Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(this, "Never Ask Again", Toast.LENGTH_SHORT).show();
}
}
return;
}
}
}
public void showSettingsAlert(String provider) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
Page1.this);
alertDialog.setTitle(provider + " Settings");
alertDialog.setMessage(provider + " is not enabled! Want to go to settings menu?");
alertDialog.setPositiveButton("Settings",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
Page1.this.startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
private ActionBarDrawerToggle setupDrawerToggle() {
return new ActionBarDrawerToggle(this, mDrawer, toolbar, R.string.drawer_open, R.string.drawer_close);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (drawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
case R.id.m1:
onMapReady(mMap);
return true;
case R.id.m2:
Intent i=new Intent(this,AboutUs.class);
startActivity(i);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void setupDrawerContent(final NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
selectDrawerItem(menuItem);
View headerLayout = navigationView.getHeaderView(0);
return true;
}
});
}
public void selectDrawerItem(MenuItem menuItem) {
// Create a new fragment and specify the fragment to show based on nav item clicked
switch(menuItem.getItemId()) {
case R.id.nav_first_fragment:
mFirst(menuItem);
mDrawer.closeDrawers();
break;
case R.id.nav_second_fragment:
/*Intent i = new Intent(Page1.this, ShowInfo.class);
i.putExtra("j", em);
startActivity(i);*/
Toast.makeText(this, "Location Updated", Toast.LENGTH_SHORT).show();
int a=0;
Intent i=getIntent();
a=i.getIntExtra("u",0);
Location nwLocation =getLocation(LocationManager.NETWORK_PROVIDER);
if (nwLocation != null) {
double latitude = nwLocation.getLatitude();
double longitude = nwLocation.getLongitude();
updateLocation(a,latitude,longitude);
}
else {
showSettingsAlert("Network");
}
break;
case R.id.sub1:
startActivity(new Intent(this, ShowInfo.class));
break;
case R.id.sub2:
startActivity(new Intent(this, LoginPage.class));
finish();
break;
default:
mFirst(menuItem);
mDrawer.closeDrawers();
}
menuItem.setChecked(true);
setTitle(menuItem.getTitle());
mDrawer.closeDrawers();
}
public void updateLocation(int userid,double xCoordinate,double yCoordinate){
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("userId", userid);
jsonObject.put("deviceName", "Mi4i");
jsonObject.put("xCoordinate",xCoordinate);
jsonObject.put("yCoordinate",yCoordinate);
jsonObject.toString();
} catch (JSONException e) {
e.printStackTrace();
}
final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
final OkHttpClient client = new OkHttpClient();
RequestBody body = RequestBody.create(JSON, String.valueOf(jsonObject));
final Request request = new Request.Builder()
.url("http://172.31.4.91:8090/rest/saveLocation")
.post(body)
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Request request, IOException e) {
e.printStackTrace();
}
#Override
public void onResponse(Response response) throws IOException {
if (!response.isSuccessful()) {
throw new IOException("Unexpected code " + response);
} /*else {
}*/
}
});
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
}
The UI for this activity is :-
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.pb.larcenytest.Page1" >
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- The main content view where fragments are loaded -->
<FrameLayout
android:id="#+id/flContent"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include
layout="#layout/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<android.support.design.widget.NavigationView
android:id="#+id/nvView"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/nav_header"
android:background="#android:color/white"
app:menu="#menu/drawer_view" />
</android.support.v4.widget.DrawerLayout>
</fragment>
you are getting location from Network provider , this takes time
what about add location.LocationListener
public class Page1 extends AppCompatActivity implements OnMapReadyCallback,location.LocationListener {
#Override
public void onLocationChanged(Location location)
{
CameraPosition position = new CameraPosition.Builder()
.target(new LatLng(Location.getLatitude, Location.getLongitude))
.zoom(17).build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(position));
}
}
Related
I'm trying to get the address line from longitude and latitude in a text view but it never shows in the text view and the map is blank.
this is my code including the toolbar and navigation bottom and the permission:
public class Map extends AppCompatActivity {
SupportMapFragment supportMapFragment;
FusedLocationProviderClient client;
private Toolbar toolbar;
View view;
TextView textLocation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
supportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
client = LocationServices.getFusedLocationProviderClient(this);
textLocation = findViewById(R.id.location);
if(ActivityCompat.checkSelfPermission(Map.this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
getLocation();
}else {
ActivityCompat.requestPermissions(Map.this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},44);
}
view = this.getWindow().getDecorView();
view.setBackgroundResource(R.color.lightGray);
toolbar=findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ImageView toolbar_icon = findViewById(R.id.toolbar_icon);
TextView toolbar_title = findViewById(R.id.toolbar_title);
BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_navigation);
bottomNavigationView.setSelectedItemId(R.id.map);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.map:
return true;
case R.id.camera:
startActivity(new Intent(getApplicationContext()
,Camera.class));
overridePendingTransition(0, 0);
return true;
case R.id.home:
startActivity(new Intent(getApplicationContext()
,MainActivity.class));
overridePendingTransition(0, 0);
return true;
case R.id.friends:
startActivity(new Intent(getApplicationContext()
,Friends.class));
overridePendingTransition(0, 0);
}
return false;
}
});
}
get the location from google map and here where I'm trying to get the line address in the textView:
private void getLocation() {
Task<Location> task = client.getLastLocation() ;
task.addOnSuccessListener((new OnSuccessListener<Location>() {
#Override
public void onSuccess(final Location location) {
if(location != null){
supportMapFragment.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions op = new MarkerOptions().position(latLng).title("IM HERE");
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15));
googleMap.addMarker(op);
try {
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
textLocation.setText(addresses.get(0).getAddressLine(0 ));
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
}));
}
request for permission:
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case 44: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
getLocation();
}
}
}
}
latitude and longitude for my current location are shown right but still, the map is blank and the address line is not shown in the TextView.
I am trying to add bookmark in my web browser and have added it but , it is only saving 1 link . for example if I am at https://www.wikipedia.org/ and save this bookmark
and i browse wikipedia more and landed on this link https://en.wikipedia.org/wiki/Portal:Featured_content
the bookmark will show remove in snack bar and is just saving 1 link and removing 1 link
I want to save both links.
public static final String PREFERENCES = "PREFERENCES_NAME";
public static final String WEB_LINKS = "links";
public static final String WEB_TITLE = "title";
String murl;
//
CoordinatorLayout coordinatorLayout;
private ProgressBar progressBar;
//
android.webkit.WebView webView;
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (webView.canGoBack()) {
webView.goBack();
} else {
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web_view);
webView = (android.webkit.WebView) findViewById(R.id.webview);
progressBar = findViewById(R.id.progressBar);
initWebview();
WebSettings settings = webView.getSettings();
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("");
toolbar.setNavigationIcon(R.drawable.ic_arrow_back);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
murl = getIntent().getExtras().getString("url");
coordinatorLayout = findViewById(R.id.main_content);
settings.setJavaScriptEnabled(true);
settings.setLoadWithOverviewMode(true);
settings.setUseWideViewPort(true);
settings.setSupportZoom(true);
// zoom
settings.setBuiltInZoomControls(true);
// zoom
settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
settings.setDomStorageEnabled(true);
webView.setScrollBarStyle(webView.SCROLLBARS_OUTSIDE_OVERLAY);
webView.setScrollbarFadingEnabled(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
} else {
webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
webView.setWebViewClient(new WebViewClient());
webView.loadUrl(murl);
webView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
webView.getSettings().setAppCacheEnabled(true);
// webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
settings.setDomStorageEnabled(true);
// settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
settings.setSaveFormData(true);
settings.setEnableSmoothTransition(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.saved, menu);
SharedPreferences sharedPreferences = getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE);
String links = sharedPreferences.getString(WEB_LINKS, null);
if (links != null) {
Gson gson = new Gson();
ArrayList<String> linkList = gson.fromJson(links, new TypeToken<ArrayList<String>>() {
}.getType());
if (linkList.contains(murl)) {
menu.getItem(0).setIcon(R.drawable.bookmark);
} else {
menu.getItem(0).setIcon(R.drawable.bookmark);
}
} else {
menu.getItem(0).setIcon(R.drawable.bookmark);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_bookmark) {
String message;
SharedPreferences sharedPreferences = getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE);
String jsonLink = sharedPreferences.getString(WEB_LINKS, null);
String jsonTitle = sharedPreferences.getString(WEB_TITLE, null);
if (jsonLink != null && jsonTitle != null) {
Gson gson = new Gson();
ArrayList<String> linkList = gson.fromJson(jsonLink, new TypeToken<ArrayList<String>>() {
}.getType());
ArrayList<String> titleList = gson.fromJson(jsonTitle, new TypeToken<ArrayList<String>>() {
}.getType());
if (linkList.contains(murl)) {
linkList.remove(murl);
titleList.remove(webView.getTitle().trim());
Editor editor = sharedPreferences.edit();
editor.putString(WEB_LINKS, new Gson().toJson(linkList));
editor.putString(WEB_TITLE, new Gson().toJson(titleList));
editor.apply();
message = "removed";
} else {
linkList.add(murl);
titleList.add(webView.getTitle().trim());
Editor editor = sharedPreferences.edit();
editor.putString(WEB_LINKS, new Gson().toJson(linkList));
editor.putString(WEB_TITLE, new Gson().toJson(titleList));
editor.apply();
message = "Saved";
}
} else {
ArrayList<String> linkList = new ArrayList<>();
ArrayList<String> titleList = new ArrayList<>();
linkList.add(murl);
titleList.add(webView.getTitle());
Editor editor = sharedPreferences.edit();
editor.putString(WEB_LINKS, new Gson().toJson(linkList));
editor.putString(WEB_TITLE, new Gson().toJson(titleList));
editor.apply();
message = "Saved";
}
Snackbar snackbar = Snackbar.make(coordinatorLayout, message, Snackbar.LENGTH_LONG);
snackbar.show();
invalidateOptionsMenu();
}
return super.onOptionsItemSelected(item);
}
private void initWebview() {
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageStarted(android.webkit.WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
progressBar.setVisibility(View.VISIBLE);
murl = url;
invalidateOptionsMenu();
}
#Override
public boolean shouldOverrideUrlLoading(android.webkit.WebView view, String url) {
webView.loadUrl(url);
return true;
}
#Override
public boolean shouldOverrideUrlLoading(android.webkit.WebView view, WebResourceRequest request) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
webView.loadUrl(request.getUrl().toString());
}
return true;
}
#Override
public void onPageFinished(android.webkit.WebView view, String url) {
super.onPageFinished(view, url);
progressBar.setVisibility(View.GONE);
invalidateOptionsMenu();
}
#Override
public void onReceivedError(android.webkit.WebView view, WebResourceRequest request, WebResourceError error) {
super.onReceivedError(view, request, error);
progressBar.setVisibility(View.GONE);
invalidateOptionsMenu();
}
});
}
}
xml file :
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/white"
android:fitsSystemWindows="true">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<WebView
android:id="#+id/webview"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<ProgressBar
android:id="#+id/progressBar"
style="#style/Widget.AppCompat.ProgressBar.Horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="-7dp"
android:indeterminate="true"
android:visibility="gone"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
I want to change a background color tab selected. I want change a color background my tab on green when is selected and changed a color background unselected tab to #a8a8a8
But when I swipe in logs I see this :
Process: pl.smok, PID: 28410
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.graphics.drawable.Drawable.setColorFilter(int, android.graphics.PorterDuff$Mode)' on a null object reference
at pl..smok.ui.activity.MainActivity$2.onTabUnselected(MainActivity.java:163)
at android.support.design.widget.TabLayout.dispatchTabUnselected(TabLayout.java:1163)
at android.support.design.widget.TabLayout.selectTab(TabLayout.java:1149)
at android.support.design.widget.TabLayout.selectTab(TabLayout.java:1124)
at android.support.design.widget.TabLayout$Tab.select(TabLayout.java:1419)
at android.support.design.widget.TabLayout$TabView.performClick(TabLayout.java:1524)
at android.view.View$PerformClick.run(View.java:22526)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7224)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
This is full code :
public class MainActivity extends AppCompatActivity {
#BindView(R.id.view_pager)
ViewPager viewPager;
#BindView(R.id.tab_layout)
TabLayout tabLayout;
ActionBar actionBar;
SharedPreferences sp;
SharedPreferences.Editor editor;
int choose;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sp = getSharedPreferences("pfref", Activity.MODE_PRIVATE);
editor = sp.edit();
choose = sp.getInt("screen", 1);
// String token = FirebaseInstanceId.getInstance().getToken();
// Log.e( "Token: ", token);
if(choose == 1 )
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
else
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
actionBar = getSupportActionBar();
hideActionBar();
String[] tabs = {"start", "status", "wiadomości", "nowa wiadomość"};
viewPager.setOffscreenPageLimit(4);
viewPager.setAdapter(new PageAdapter(getFragmentManager(), tabs));
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener(){
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
CommonUtil.hideKeyboard(MainActivity.this);
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
tabLayout.setupWithViewPager(viewPager);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = getWindow();
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(getResources().getColor(R.color.colorBrown));
}
getFragmentManager()
.beginTransaction()
.add(R.id.top_bar_container, new TopBarFragment(), TopBarFragment.class.getName())
.commit();
processIntent(getIntent());
createTabIcons();
setupTabIcons();
}
#Override
protected void onResume() {
super.onResume();
choose = sp.getInt("screen", 1);
if(choose == 1 )
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
else
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
private void setupTabIcons() {
// tabLayout.getTabAt(1).getIcon().setColorFilter(Color.parseColor("#a8a8a8"), PorterDuff.Mode.SRC_IN);
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
// tab.getIcon().mutate().setColorFilter(Color.GREEN, PorterDuff.Mode.SRC_IN);
Log.e("tab count " , tab.getPosition() + " " );
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
// tab.getIcon().setColorFilter(Color.parseColor("#a8a8a8"), PorterDuff.Mode.SRC_IN);
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
#Override
protected void onStart() {
super.onStart();
App.getBus().register(this);
runServices();
}
#Override
protected void onStop() {
super.onStop();
App.getBus().unregister(this);
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
processIntent(intent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
protected void processIntent(Intent intent) {
if (intent != null && intent.getIntExtra(Const.KEY_GOTO, 0) == 1 && viewPager != null) {
viewPager.setCurrentItem(2);
}
}
#Subscribe
public void onPermissionRequestedEvent(PermissionRequestedEvent event) {
PermissionUtil.getPermission(this, event.getPermission());
}
#Subscribe
public void onPermissionGrantedEvent(PermissionGrantedEvent event) {
if (event.getPermission().equals(Manifest.permission.ACCESS_FINE_LOCATION)) {
runLocationService();
}
}
#Subscribe
public void onPageNavigateEvent(PageNavigateEvent event) {
Intent intent;
switch (event.getPage()) {
case Const.APP_SETTINGS_LOCATION:
CommonUtil.hideKeyboard(this);
intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
break;
case Const.PAGE_START:
viewPager.setCurrentItem(0);
break;
case Const.PAGE_STATUSES:
viewPager.setCurrentItem(1);
break;
case Const.PAGE_MESSAGES:
viewPager.setCurrentItem(2);
break;
case Const.PAGE_SEND_MESSAGE:
viewPager.setCurrentItem(3);
break;
default: break;
}
}
#Subscribe(sticky = true)
public void onLoggedOutEvent(LoggedOutEvent event) {
String user = Hawk.get(HawkConst.LOGIN_USER);
String company = Hawk.get(HawkConst.LOGIN_COMPANY);
String password = Hawk.get(HawkConst.LOGIN_PASSWORD);
Hawk.clear();
Hawk.put(HawkConst.LOGIN_USER, user);
Hawk.put(HawkConst.LOGIN_COMPANY, company);
Hawk.put(HawkConst.LOGIN_PASSWORD, password);
stopLocationService();
stopTrackerService();
stopConfigService();
FileUtil.clearDirs();
Intent intent = new Intent(MainActivity.this, StartActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
App.getBus().removeStickyEvent(LoggedOutEvent.class);
}
#Subscribe
public void onPhotoRequestedEvent(PhotoRequestedEvent event) {
Intent intent;
switch (event.getRequestCode()) {
case Const.PHOTO_GALLERY:
intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(Intent.createChooser(intent, getResources().getString(R.string.choose_image_title)), event.getRequestCode());
break;
case Const.PHOTO_CAMERA:
intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, FileUtil.getOutputTempUri("images"));
startActivityForResult(intent, event.getRequestCode());
break;
default: break;
}
}
#Subscribe
public void onFileViewRequestEvent(FileViewRequestEvent event) {
File file = FileUtil.getFile(event.getEvent().getId());
if (file == null) {
Toast.makeText(this, getResources().getString(R.string.file_not_exists), Toast.LENGTH_LONG).show();
} else {
Uri uri = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
try {
String type = FileUtil.getMimeType(file.getPath());
intent.setDataAndType(uri, type);
startActivity(intent);
App.getBus().post(new FileViewedEvent(event.getEvent()));
} catch (Exception e) {
e.printStackTrace();
try {
intent.setDataAndType(uri, "*/*");
startActivity(intent);
App.getBus().post(new FileViewedEvent(event.getEvent()));
} catch (Exception ee) {
ee.printStackTrace();
Toast.makeText(this, getResources().getString(R.string.no_file_app), Toast.LENGTH_LONG).show();
}
}
}
}
#Subscribe
public void onHideKeyboardEvent() {
CommonUtil.hideKeyboard(this);
}
#Subscribe
public void onMoveAppBackgroundEvent(MoveAppBackgroundEvent event) {
moveTaskToBack(true);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
switch (requestCode) {
case Const.PHOTO_GALLERY:
App.getBus().postSticky(new PhotoSelectedEvent(data.getData())); break;
case Const.PHOTO_CAMERA:
Uri uri = FileUtil.renameFile(App.getConfigRepository().getPhotoMaxWidth());
App.getBus().postSticky(new PhotoSelectedEvent(uri)); break;
default: break;
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case Const.PERMISSIONS_REQUEST_LOCATION:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
App.getBus().post(new PermissionGrantedEvent(Manifest.permission.ACCESS_FINE_LOCATION));
}
break;
default:
break;
}
}
protected void runServices() {
if (LocationUtil.isLocationEnabled(getBaseContext())) {
if (checkPermission()) {
runLocationService();
}
} else {
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setMessage(getResources().getString(R.string.location_settings_disabled));
dialog.setPositiveButton(getString(R.string.go_to_location_settings), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
App.getBus().post(new PageNavigateEvent(Const.APP_SETTINGS_LOCATION));
}
});
dialog.setNegativeButton(getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
finish();
}
});
dialog.show();
}
runTrackerService();
runConfigService();
}
protected void runLocationService() {
startService(new Intent(this, LocationService.class));
}
protected void stopLocationService() {
stopService(new Intent(this, LocationService.class));
}
protected void runTrackerService() {
startService(new Intent(this, TrackerService.class));
}
protected void stopTrackerService() {
stopService(new Intent(this, TrackerService.class));
}
protected void runConfigService() {
startService(new Intent(this, ConfigService.class));
}
protected void stopConfigService() {
stopService(new Intent(this, ConfigService.class));
}
protected boolean checkPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
App.getBus().post(new PermissionRequestedEvent(Manifest.permission.ACCESS_FINE_LOCATION));
return false;
}
return true;
}
protected void hideActionBar() {
if (actionBar != null) {
actionBar.hide();
}
}
private void createTabIcons(){
}
}
And this is xml code for this activity . activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#fff"
tools:context="pl.eltegps.smokkomunikator.ui.activity.MainActivity">
<FrameLayout
android:id="#+id/top_bar_container"
android:layout_width="match_parent"
android:layout_height="70dp" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/top_bar_container">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingTop="?attr/actionBarSize">
<android.support.v4.view.ViewPager
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_vertical_margin"
android:paddingRight="#dimen/activity_vertical_margin"
android:paddingTop="#dimen/activity_vertical_margin" />
</LinearLayout>
<android.support.design.widget.TabLayout
android:id="#+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:layout_gravity="center_horizontal"
android:minHeight="?attr/actionBarSize"
android:paddingTop="#dimen/activity_vertical_margin"
app:tabGravity="center"
app:tabIndicatorColor="#fff"
app:tabMode="scrollable"
app:tabTextAppearance="#style/MyCustomTextAppearance" />
</RelativeLayout>
</RelativeLayout>
Hello you can set this color in xml only no need to write in code
<android.support.design.widget.TabLayout
android:id="#+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="35dp"
app:tabSelectedTextColor="#color/colorSplashBackground"
app:tabTextAppearance="#android:style/TextAppearance.Widget.TabWidget"
app:tabTextColor="#color/colorBottomLine">
</android.support.design.widget.TabLayout>
this will be the xml of tab layout and you have to pass your color in line
app:tabSelectedTextColor="#color/colorSplashBackground"
I would like to select few players ( highlighted in purple colors ie Player 1, Player 3 & Player 5) from 'MyPlayerActivity' and add these selected players into a mapbox Map as markers (MainActivity) during on click on 'Add Player' button.
Could someone please help me on how to achieve this ?
Following is my 'MyPlayerActivity' code
public class MyPlayerActivity extends ListActivity {
private static int lastClickId = -1;
// Array of strings storing country names
String[] players = new String[] {
"Player 1",
"Player 2",
"Player 3",
"Player 4",
"Player 5"
};
// Array of integers points to images stored in /res/drawable-ldpi/
int[] images = new int[]{
R.drawable.play_1,
R.drawable.play_2,
R.drawable.play_3,
R.drawable.play_4,
R.drawable.play_5
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_view);
final ListView listView = (ListView) findViewById(android.R.id.list);
View headerView = ((LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.header, null, false);
getListView().addHeaderView(headerView);
// Each row in the list stores country name, currency and flag
List<HashMap<String,String>> aList = new ArrayList<HashMap<String,String>>();
for(int i=0;i<6;i++){
HashMap<String, String> hm = new HashMap<String,String>();
hm.put("label", "" + players[i]);
hm.put("imgs", Integer.toString(images[i]) );
aList.add(hm);
}
// Keys used in Hashmap
String[] from = { "imgs","label"};
// Ids of views in listview_layout
int[] to = { R.id.imgs,R.id.label};
// Instantiating an adapter to store each items
// R.layout.listview_layout defines the layout of each item
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), aList, R.layout.list_view, from, to);
// Getting a reference to listview of main.xml layout file
// Setting the adapter to the listView
listView.setAdapter(adapter);
// Item Click Listener for the listview
AdapterView.OnItemClickListener itemClickListener = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View container, int position, long id) {
// Getting the Container Layout of the ListView
RelativeLayout relativeLayoutParent = (RelativeLayout) container;
//LinearLayout linearLayoutParent = (LinearLayout) container;
RelativeLayout relativeLayoutChild = (RelativeLayout) relativeLayoutParent.getChildAt(1);
// Getting the inner Linear Layout
// LinearLayout linearLayoutChild = (LinearLayout ) linearLayoutParent.getChildAt(1);
// Getting the Player TextView
TextView myPlayer = (TextView) relativeLayoutChild.getChildAt(0);
Toast.makeText(getBaseContext(), myPlayer.getText().toString(), Toast.LENGTH_SHORT).show();
}
};
// Setting the item click listener for the listview
listView.setOnItemClickListener(itemClickListener);
}
}
Following is the list_view.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<ImageView
android:id="#+id/imgs"
android:layout_width="75dp"
android:layout_height="75dp"
android:paddingTop="10dp"
android:paddingStart="10dp"
android:paddingEnd="10dp"
android:paddingRight="10dp"
android:paddingBottom="10dp" >
</ImageView>
<TextView
android:id="#+id/label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_centerVertical="true"
android:text="#+id/label"
android:textSize="17sp" >
</TextView>
<Button
android:id="#+id/button2"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginBottom="10dp"
android:text="#string/Add_Player"
android:background="#66ccff"
android:textColor="#ffffff">
</Button>
<ListView android:id="#id/android:list"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
Below is the 'MainActivity' code, where I have initialized my map and this is where I would need to add my Player markers and display in mapbox map.
'MainActivity' code where I have initialized my map:
public class MainActivity extends AppCompatActivity implements ActivityCompat.OnRequestPermissionsResultCallback {
private MapView mapView;
private MapboxMap map;
private Marker customMarker;
private ListView mDrawerList;
private DrawerLayout mDrawerLayout;
private ArrayAdapter<String> mAdapter;
private ActionBarDrawerToggle mDrawerToggle;
private String mActivityTitle;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MapboxAccountManager.start(this, "token");
final boolean permissionGranted = ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED;
setContentView(R.layout.activity_main);
mDrawerList = (ListView)findViewById(R.id.navList);
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
mActivityTitle = getTitle().toString();
onMapReady(map);
addDrawerItems();
setupDrawer();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mapView = (MapView) findViewById(R.id.mapview);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(MapboxMap mapboxMap) {
Log.i("MapAsync", " is called");
//you need to initialize 'map' with 'mapboxMap';
map = mapboxMap;
//map.setOnMapLongClickListener(new LatLng);
map.setOnMapLongClickListener(new MapboxMap.OnMapLongClickListener() {
#Override
public void onMapLongClick(#NonNull LatLng point) {
if (customMarker != null) {
// Remove previous added marker
map.removeAnnotation(customMarker);
customMarker = null;
}
customMarker = map.addMarker(new MarkerOptions()
.title("Custom Marker")
.snippet(new DecimalFormat("#.#####").format(point.getLatitude()) + ", "
+ new DecimalFormat("#.#####").format(point.getLongitude()))
.position(point));
}
}); // Long click Ends here
}
});
}
// Initialize the onMapReady
public void onMapReady(#NonNull MapboxMap mapboxMap) {
this.map = mapboxMap;
}
private void addDrawerItems() {
String[] osArray = { "Map", "Players", "Video", "TestPlayer", "My Profile"};
mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, osArray);
mDrawerList.setAdapter(mAdapter);
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// depending on the position in your drawer list change this
switch (position) {
case 0: {
Toast.makeText(MainActivity.this, "Access map", Toast.LENGTH_SHORT).show();
break;
}
case 1:{
Intent intent = new Intent(MainActivity.this, ListPlayerActivity.class);
startActivity(intent);
Toast.makeText(MainActivity.this, "See players arena", Toast.LENGTH_SHORT).show();
break;
}
case 2:{
Intent appIntent = new Intent(MainActivity.this, PlayYoutubeActivity.class);
startActivity(appIntent);
Toast.makeText(MainActivity.this, "See Video", Toast.LENGTH_SHORT).show();
break;
}
case 3:{
Intent appIntent = new Intent(MainActivity.this, MyPlayerActivity.class);
startActivity(appIntent);
Toast.makeText(MainActivity.this, "Test to see my players", Toast.LENGTH_SHORT).show();
break;
}
default:
break;
}
Toast.makeText(MainActivity.this, "More details to follow", Toast.LENGTH_SHORT).show();
}
});
}
private void setupDrawer() {
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) {
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getSupportActionBar().setTitle("Navigation!");
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getSupportActionBar().setTitle(mActivityTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerToggle.setDrawerIndicatorEnabled(true);
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#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_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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
// Activate the navigation drawer toggle
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
// Add the mapView lifecycle to the activity's lifecycle methods
#Override
public void onResume() {
super.onResume();
mapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mapView.onPause();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
public class TelemetryServiceNotConfiguredException extends RuntimeException {
public TelemetryServiceNotConfiguredException() {
super("\nTelemetryService is not configured in your applications AndroidManifest.xml. " +
"\nPlease add \"com.mapbox.mapboxsdk.telemetry.TelemetryService\" service in your applications AndroidManifest.xml" +
"\nFor an example visit For more information visit https://www.mapbox.com/android-sdk/.");
}
}
}
To add a marker to the map you can use this snippet:
mapboxMap.addMarker(new MarkerViewOptions()
.position(new LatLng(<position of player>)));
If the listview and map are in separate activities, you can pass the selected player information to the map activity using an intent. Is this what you were looking for?
I'm trying to add a progress spinner at the top of my app while data is being received from the volley. There may be an easier way to do this but this is what i've tried so far only I have a few errors. The first error being newsListView getting the error 'varied is accessed from within inner class, needs to be declared final'. and the string values cannot be resolved. Here is the class I made within the oncreate method:
public class MainActivity extends AppCompatActivity {
private List<NewsRecord> newsListData = new ArrayList<NewsRecord>();
private GridView newsListView;
private NewsListAdapter adapter;
LinearLayout layout;
private ProgressDialog pDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GridView newsListView = (GridView) findViewById(R.id.newsFeedList);
adapter = new NewsListAdapter(this, R.layout.adapter_news_list, newsListData, this);
layout = (LinearLayout) findViewById(R.id.progressbar_view);
newsListView.setAdapter(adapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading Articles...");
pDialog.show();
newsListView.setOnItemClickListener(itemClicked);
nextStart = 0;
updateListData(nextStart, 20);
}
public int nextStart = 0;
public void updateListData(int StartPoint, int count){
String url = "http://www.efstratiou.info/projects/newsfeed/getList.php?start=" + StartPoint + "&count=" + count;
EDANewsApp app = EDANewsApp.getInstance();
JsonArrayRequest jsonRequest = new JsonArrayRequest(url, listener, errorListener);
app.requestQueue.add(jsonRequest);
nextStart +=count;
}
#Override
public boolean onCreateOptionsMenu (Menu menu){
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()) {
case R.id.action_about:
Intent intent = new Intent(this, AboutActivity.class);
startActivity(intent);
return true;
case R.id.action_search:
return true;
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
AdapterView.OnItemClickListener itemClicked = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this, NewsItemActivity.class);
intent.putExtra("newsItemId", newsListData.get(position).recordId);
startActivity(intent);
}
};
private SearchView.OnQueryTextListener searchQueryListener = new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
Intent searchIntent = new Intent(MainActivity.this, SearchResultsActivity.class);
searchIntent.putExtra("query", query);
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
};
//Listeners
Response.Listener<JSONArray> listener = new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//we successfully received the JSONArray
//Here we will extract the data and use it in our app
hidePDialog();
//Clear the dataset before loading new data
// newsListData.clear();
//Go through all the JSON objects
for (int i = 0; i < response.length(); i++) {
try {
//Get one JSON object
JSONObject jsonObj = response.getJSONObject(i);
//Put JSON data in a Java object
NewsRecord record = new NewsRecord();
record.recordId = jsonObj.getInt("record_id");
record.title = jsonObj.getString("title");
record.date = jsonObj.getString("date");
record.shortInfo = jsonObj.getString("short_info");
record.imageUrl = jsonObj.getString("image_url");
newsListData.add(record);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
};
Response.ErrorListener errorListener = new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//There was an error in the communication
//We can notify the user about it
hidePDialog();
}
};
}
and the progress bar appears in the activity_main.xml like so:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/newsListItem"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:context=".MainActivity">
<LinearLayout
android:id="#+id/progressbar_view"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:orientation="vertical" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:orientation="horizontal" >
<ProgressBar
style="?android:attr/progressBarStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical|center_horizontal" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical|center_horizontal"
android:text="Loading data..." />
</LinearLayout>
<View
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="#C0C0C0" />
</LinearLayout>
<GridView
android:id="#+id/newsFeedList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:verticalSpacing="0dp"
android:horizontalSpacing="0dp"
android:stretchMode="columnWidth"
android:numColumns="2"/>
</FrameLayout>
Here is the way I often do in my projects, IMO you can take a look and apply to your project, hope it helps!
#Override
protected void onCreate(Bundle savedInstanceState) {
...
mRequestQueue = Volley.newRequestQueue(this);
mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
mProgressBar.setVisibility(View.VISIBLE);
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
mProgressBar.setVisibility(View.INVISIBLE);
// do something...
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
mProgressBar.setVisibility(View.INVISIBLE);
// do something...
}
});
mRequestQueue.add(jsonArrayRequest);
...
}
you declare your progressbar
private ProgressDialog pDialog;
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
you call you Volley request than when you get the response (either success or error event) you call the hidePDialog method
hidePDialog();
//method to hide progressbar
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
don't forget to call the method in onDestroy() also
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GridView newsListView = (GridView) findViewById(R.id.newsFeedList);
adapter = new NewsListAdapter(this, R.layout.adapter_news_list, newsListData, this);
layout = (LinearLayout) findViewById(R.id.progressbar_view);
newsListView.setAdapter(adapter);
newsListView.setOnItemClickListener(itemClicked);
EDANewsApp app = EDANewsApp.getInstance();
nextStart = 0;
updateListData(nextStart, 20);
}
private class Task extends AsyncTask<String, Integer, Boolean> {
private ProgressDialog dialog;
#Override
protected void onPreExecute() {
dialog.setMessage("Doing something, please wait.");
dialog.show();
layout.setVisibility(View.VISIBLE);
newsListView.setVisibility(View.GONE);
super.onPreExecute();
}
#Override
protected void onPostExecute(Boolean result) {
dialog.dismiss();
layout.setVisibility(View.GONE);
newsListView.setVisibility(View.VISIBLE);
adapter.notifyDataSetChanged();
super.onPostExecute(result);
}
#Override
protected Boolean doInBackground(String... params) {
stringValues.add("String 1");
stringValues.add("String 2");
stringValues.add("String 3");
stringValues.add("String 4");
stringValues.add("String 5");
try {
Thread.sleep(3000);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
Hope this will help you.