Adding onClick to RecyclerView after parsing JSON data - javascript

I have a fragment in which reside a RecyclerView. I parsed JSON data from a webpage and showed it in this RecyclerView using tutorial: https://www.learn2crack.com/2016/02/recyclerview-json-parsing.html
Now I wish to add an onClick to the RecyclerView items. I know how to do so for static RecyclerView items but don't know to setOnClickListener in this case. For static recyclerview items, I'm using this class for onClick events.
package com.parassidhu.cdlumaths;
import android.support.v7.widget.RecyclerView;
import android.view.View;
public class ItemClickSupport {
private final RecyclerView mRecyclerView;
private OnItemClickListener mOnItemClickListener;
private OnItemLongClickListener mOnItemLongClickListener;
private View.OnClickListener mOnClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mOnItemClickListener != null) {
RecyclerView.ViewHolder holder = mRecyclerView.getChildViewHolder(v);
mOnItemClickListener.onItemClicked(mRecyclerView, holder.getAdapterPosition(), v);
}
}
};
private View.OnLongClickListener mOnLongClickListener = new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
if (mOnItemLongClickListener != null) {
RecyclerView.ViewHolder holder = mRecyclerView.getChildViewHolder(v);
return mOnItemLongClickListener.onItemLongClicked(mRecyclerView, holder.getAdapterPosition(), v);
}
return false;
}
};
private RecyclerView.OnChildAttachStateChangeListener mAttachListener
= new RecyclerView.OnChildAttachStateChangeListener() {
#Override
public void onChildViewAttachedToWindow(View view) {
if (mOnItemClickListener != null) {
view.setOnClickListener(mOnClickListener);
}
if (mOnItemLongClickListener != null) {
view.setOnLongClickListener(mOnLongClickListener);
}
}
#Override
public void onChildViewDetachedFromWindow(View view) {
}
};
private ItemClickSupport(RecyclerView recyclerView) {
mRecyclerView = recyclerView;
mRecyclerView.setTag(R.id.item_click_support, this);
mRecyclerView.addOnChildAttachStateChangeListener(mAttachListener);
}
public static ItemClickSupport addTo(RecyclerView view) {
ItemClickSupport support = (ItemClickSupport) view.getTag(R.id.item_click_support);
if (support == null) {
support = new ItemClickSupport(view);
}
return support;
}
public static ItemClickSupport removeFrom(RecyclerView view) {
ItemClickSupport support = (ItemClickSupport) view.getTag(R.id.item_click_support);
if (support != null) {
support.detach(view);
}
return support;
}
public ItemClickSupport setOnItemClickListener(OnItemClickListener listener) {
mOnItemClickListener = listener;
return this;
}
public ItemClickSupport setOnItemLongClickListener(OnItemLongClickListener listener) {
mOnItemLongClickListener = listener;
return this;
}
private void detach(RecyclerView view) {
view.removeOnChildAttachStateChangeListener(mAttachListener);
view.setTag(R.id.item_click_support, null);
}
public interface OnItemClickListener {
void onItemClicked(RecyclerView recyclerView, int position, View v);
}
public interface OnItemLongClickListener {
boolean onItemLongClicked(RecyclerView recyclerView, int position, View v);
}
}
My Adapter Class is:
package com.parassidhu.cdlumaths;
import android.content.ClipData;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.parassidhu.cdlumaths.R;
import com.parassidhu.cdlumaths.Android;
import java.util.ArrayList;
public class NoticesData extends RecyclerView.Adapter<NoticesData.ViewHolder> {
private ArrayList<Android> mAndroidList;
private RecyclerView recyclerView;
public NoticesData(ArrayList<Android> androidList, RecyclerView rcl) {
mAndroidList = androidList;
recyclerView=rcl;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.notices_row, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.mTvName.setText(mAndroidList.get(position).getName());
ItemClickSupport.addTo(recyclerView).setOnItemClickListener(new ItemClickSupport.OnItemClickListener() {
#Override
public void onItemClicked(RecyclerView recyclerView, int position, View v) {
//I can't call Toast or startIntent here
}
});
}
#Override
public int getItemCount() {
return mAndroidList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
private TextView mTvName;
public ViewHolder(View view) {
super(view);
mTvName = (TextView)view.findViewById(R.id.tv_name);
}
}
}

In your Activity or Fragment class create a method like below
public void showToast(int position) {
Toast.makeText(getActivity(), "Clicked position is " + position, Toast.LENGTH_SHORT).show();
}
(I think you're using Fragment so I used getActivity())
Now update your Adapter constructor like this
...
...
private YourFragment frag;
public NoticesData(ArrayList<Android> androidList, RecyclerView rcl, YourFragment fragment) {
mAndroidList = androidList;
recyclerView = rcl;
frag = fragment;
}
In your Fragment update Adapter initialization like this
NoticesData notice = NoticesData(androidList, rcl, YourFragment.this);
Now call the showToast() method like below in Adapter
ItemClickSupport.addTo(recyclerView).setOnItemClickListener(new ItemClickSupport.OnItemClickListener() {
#Override
public void onItemClicked(RecyclerView recyclerView, int position, View v) {
frag.showToast(position); // it's like callback method
}
});
Note: here YourFragment means the Fragment which hosts your RecyclerView.

you must set click listener for each of the items in your recycler view from the adapter for that recycler view. when you set the data for each if the items (views) in the recycler view you can add the onClickListener for that view too.

Related

i want to open my file when download completed

I extracted some urls by jsoup.
and made a download manager.
and it seems parcelfiledescriptor doesn't work.
i tryed regist broadcaster but did't work.
I don't know where should I insert "parcelfiledescriptor" and "regist broadcaster"
i have no idea to fix this...
ps. these urls goes like this
"http://www.dhu.ac.kr/korean/HOME/bbs/bbs_download.php?mv_data=aWR4PTI3MDU0MyZzdGFydFBhZ2U9MCZsaXN0Tm89MjY2JnRhYmxlPWV4X2Jic19kYXRhX2RodWxpZmUmbmF2X2NvZGU9ZGh1MTM0NDQwODk1NCZjb2RlPWZvb2Qmc2VhcmNoX2l0ZW09JnNlYXJjaF9vcmRlcj0mb3JkZXJfbGlzdD0mbGlzdF9zY2FsZT0mdmlld19sZXZlbD0mdmlld19jYXRlPSZ2aWV3X2NhdGUyPQ==||&type=0&download=h"
is there any methods to open this url without Excel viewer?
"http://docs.google.com/gview?embedded=true&url= url" does'nt work
package develop_hong.haanyeat;
import android.app.DownloadManager;
import android.content.Context;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import java.io.File;
import java.io.IOException;
public class menucrawl extends AppCompatActivity {
private String htmlPageUrl = "http://www.dhu.ac.kr/korean/HOME/dhulife/sub/sub.htm?nav_code=dhu1344408954"; //파싱할 홈페이지의 URL주소
private String text = "";
private String fixedtext = "";
private String fixplus = "";
private Button button1;
private Button button2;
private Button button3;
private Button button4;
private long downloadID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menucrawl);
Button button1 = findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(menucrawl.this, "1주차 메뉴를 다운로드 중입니다", Toast.LENGTH_SHORT).show();
new JsoupAsyncTask().execute();
}
});
Button button2 = findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(menucrawl.this, "2주차 메뉴를 다운로드 중입니다", Toast.LENGTH_SHORT).show();
new JsoupAsyncTask2().execute();
}
});
Button button3 = findViewById(R.id.button3);
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(menucrawl.this, "3주차 메뉴를 다운로드 중입니다", Toast.LENGTH_SHORT).show();
new JsoupAsyncTask3().execute();
}
});
Button button4 = findViewById(R.id.button4);
button4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(menucrawl.this, "4주차 메뉴를 다운로드 중입니다", Toast.LENGTH_SHORT).show();
new JsoupAsyncTask4().execute();
}
});
}
private class JsoupAsyncTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
try {
Document doc = Jsoup.connect(htmlPageUrl).timeout(5000).get();
Elements a = doc.select("tbody tr:has(a):eq(3) td:eq(2) a[href]");
text = a.attr("href");
String fixtext = text;
fixedtext = fixtext.substring(5);
fixplus = "http://www.dhu.ac.kr/korean/HOME" + fixedtext;
System.out.println(fixplus);
DownloadManager downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(fixplus));
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI |
DownloadManager.Request.NETWORK_MOBILE);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
//set the local destination for download file to a path within the application's external files directory
request.setDestinationInExternalPublicDir(Environment.getExternalStorageDirectory().getAbsolutePath(), "me1nu.xlsx");
request.setMimeType("application/vnd.ms-excel");
downloadManager.enqueue(request);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
}
}
private class JsoupAsyncTask2 extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
try {
Document doc = Jsoup.connect(htmlPageUrl).timeout(5000).get();
Elements a = doc.select("tbody tr:has(a):eq(2) td:eq(2) a[href]");
text = a.attr("href");
String fixtext = text;
fixedtext = fixtext.substring(5);
fixplus = "http://www.dhu.ac.kr/korean/HOME" + fixedtext;
System.out.println(fixplus);
DownloadManager downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(fixplus));
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI |
DownloadManager.Request.NETWORK_MOBILE);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
//set the local destination for download file to a path within the application's external files directory
request.setDestinationInExternalPublicDir(Environment.getExternalStorageDirectory().getAbsolutePath(), "me2nu.xlsx");
request.setMimeType("application/vnd.ms-excel");
downloadManager.enqueue(request);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
}
}
private class JsoupAsyncTask3 extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
try {
Document doc = Jsoup.connect(htmlPageUrl).timeout(5000).get();
Elements a = doc.select("tbody tr:has(a):eq(1) td:eq(2) a[href]");
text = a.attr("href");
String fixtext = text;
fixedtext = fixtext.substring(5);
fixplus = "http://www.dhu.ac.kr/korean/HOME" + fixedtext;
System.out.println(fixplus);
DownloadManager downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(fixplus));
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI |
DownloadManager.Request.NETWORK_MOBILE);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
//set the local destination for download file to a path within the application's external files directory
request.setDestinationInExternalPublicDir(Environment.getExternalStorageDirectory().getAbsolutePath(), "me3nu.xlsx");
request.setMimeType("application/vnd.ms-excel");
downloadManager.enqueue(request);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
}
}
private class JsoupAsyncTask4 extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
try {
Document doc = Jsoup.connect(htmlPageUrl).timeout(5000).get();
Elements a = doc.select("tbody tr:has(a):eq(0) td:eq(2) a[href]");
text = a.attr("href");
String fixtext = text;
fixedtext = fixtext.substring(5);
fixplus = "http://www.dhu.ac.kr/korean/HOME" + fixedtext;
System.out.println(fixplus);
DownloadManager downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(fixplus));
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI |
DownloadManager.Request.NETWORK_MOBILE);
// set title and description
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
//set the local destination for download file to a path within the application's external files directory
request.setDestinationInExternalPublicDir(Environment.getExternalStorageDirectory().getAbsolutePath(), "me4nu.xlsx");
request.setMimeType("application/vnd.ms-excel");
downloadManager.enqueue(request);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
}
}
}

After builing my app and Installing Google Maps API, My APP crashes anytime I tend to search for Location

I am new to this programming and I am finding it difficult to get past this stage. After building APP successfully, I added Google Map to get real time Location. After doing this, my app crashes each time I click the switch button.
Please if you can help me source out the issue, I would be very happy as this will help me a lot. Below is my Logcat
09-22 15:59:04.636 4803-4803/com.example.mac.uberclone E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.mac.uberclone, PID: 4803
java.lang.NullPointerException: Attempt to read from field 'int com.google.android.gms.location.LocationRequest.a' on a null object reference
at android.os.Parcel.createException(Parcel.java:1948)
at android.os.Parcel.readException(Parcel.java:1910)
at android.os.Parcel.readException(Parcel.java:1860)
at com.google.android.gms.internal.location.zza.transactAndReadExceptionReturnVoid(Unknown Source:10)
at com.google.android.gms.internal.location.zzap.zza(Unknown Source:9)
at com.google.android.gms.internal.location.zzas.zza(Unknown Source:44)
at com.google.android.gms.internal.location.zzaz.zza(Unknown Source:5)
at com.google.android.gms.internal.location.zzr.doExecute(Unknown Source:25)
at com.google.android.gms.common.api.internal.BaseImplementation$ApiMethodImpl.run(Unknown Source:10)
at com.google.android.gms.common.api.internal.zzag.execute(Unknown Source:71)
at com.google.android.gms.common.api.internal.zzbd.execute(Unknown Source:5)
at com.google.android.gms.common.api.internal.zzav.execute(Unknown Source:137)
at com.google.android.gms.internal.location.zzq.requestLocationUpdates(Unknown Source:14)
at com.example.mac.uberclone.Welcome.startLocationUpdate(Welcome.java:269)
at com.example.mac.uberclone.Welcome.onConnected(Welcome.java:283)
at com.google.android.gms.common.internal.GmsClientEventManager.onConnectionSuccess(Unknown Source:109)
at com.google.android.gms.common.api.internal.zzav.zzb(Unknown Source:22)
at com.google.android.gms.common.api.internal.zzaj.zzat(Unknown Source:92)
at com.google.android.gms.common.api.internal.zzaj.onConnected(Unknown Source:21)
at com.google.android.gms.common.api.internal.zzbd.onConnected(Unknown Source:7)
at com.google.android.gms.common.api.internal.zzp.onConnected(Unknown Source:5)
at com.google.android.gms.common.internal.zzf.onConnected(Unknown Source:2)
at com.google.android.gms.common.internal.BaseGmsClient$PostInitCallback.handleServiceSuccess(Unknown Source:130)
at com.google.android.gms.common.internal.BaseGmsClient$zza.deliverCallback(Unknown Source:62)
at com.google.android.gms.common.internal.BaseGmsClient$zza.deliverCallback(Unknown Source:2)
at com.google.android.gms.common.internal.BaseGmsClient$CallbackProxy.deliverCallback(Unknown Source:51)
at com.google.android.gms.common.internal.BaseGmsClient$zzb.handleMessage(Unknown Source:270)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Also in my Build Gradle App
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.github.glomadrian:MaterialAnimatedSwitch:1.1#aar'
implementation 'com.firebase:geofire-android:2.3.1'
implementation 'com.android.support:appcompat-v7:28.0.0-rc02'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'com.google.firebase:firebase-auth:16.0.3'
implementation 'com.google.android.gms:play-services-maps:15.0.1'
implementation 'com.google.android.gms:play-services-location:15.0.1'
implementation 'com.google.android.gms:play-services-analytics:16.0.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
//Add Library
implementation 'com.github.d-max:spots-dialog:0.7#aar'
implementation 'uk.co.chrisjenx:calligraphy:latest.integration'
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.rengwuxian.materialedittext:library:2.1.4'
implementation 'com.android.support:design:28.0.0'
implementation 'com.android.support:cardview-v7:28.0.0'
implementation 'com.google.firebase:firebase-core:16.0.3'
implementation 'com.google.firebase:firebase-database:16.0.2'
implementation 'com.firebaseui:firebase-ui-database:4.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
}
apply plugin: 'com.google.gms.google-services'
this is my Welcome activity
package com.example.mac.uberclone;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Handler;
import android.os.SystemClock;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.animation.Interpolator;
import android.view.animation.LinearInterpolator;
import android.widget.Toast;
import com.firebase.geofire.GeoFire;
import com.firebase.geofire.GeoLocation;
import com.github.glomadrian.materialanimatedswitch.MaterialAnimatedSwitch;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class Welcome extends FragmentActivity implements
OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener
{
private GoogleMap mMap;
//Play Service
private static final int MY_PERMISSION_REQUEST_CODE = 7000;
private static final int PLAY_SERVICE_RES_REQUEST = 7001;
private LocationRequest locationRequest;
private GoogleApiClient mGoogleApiClient;
private Location mLastLocation;
private static int UPDATE_INTERVAL = 5000;
private static int FASTEST_INTERVAL = 3000;
private static int DISPLACEMENT = 10;
DatabaseReference drivers;
GeoFire geoFire;
Marker mCurrent;
MaterialAnimatedSwitch location_switch;
SupportMapFragment mapFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
//Init View
location_switch = (MaterialAnimatedSwitch)findViewById(R.id.location_switch);
location_switch.setOnCheckedChangeListener(new MaterialAnimatedSwitch.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(boolean isOnline) {
if (isOnline)
{
startLocationUpdate();
displayLocation();
Snackbar.make(mapFragment.getView(),"You are online",Snackbar.LENGTH_SHORT)
.show();
}
else
{
stopLocationUpdate();
mCurrent.remove();
Snackbar.make(mapFragment.getView(),"You are offline",Snackbar.LENGTH_SHORT)
.show();
}
}
});
//Geo Fire
drivers = FirebaseDatabase.getInstance().getReference("Drivers");
geoFire = new GeoFire (drivers);
setUpLocation();
}
//Press Ctrl+O
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode)
{
case MY_PERMISSION_REQUEST_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
if (checkPlayServices())
{
buildGoogleApiClient();
createLocationRequest();
if (location_switch.isChecked())
displayLocation();
}
}
}
}
private void setUpLocation() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
//Request runtime permission
ActivityCompat.requestPermissions(this, new String[]{
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION
},MY_PERMISSION_REQUEST_CODE);
}
else
{
if (checkPlayServices())
{
buildGoogleApiClient();
createLocationRequest();
if (location_switch.isChecked())
displayLocation();
}
}
}
private void createLocationRequest() {
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setInterval(5000);
locationRequest.setFastestInterval(1000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
private void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS)
{
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode))
GooglePlayServicesUtil.getErrorDialog(resultCode,this,PLAY_SERVICE_RES_REQUEST).show();
else {
Toast.makeText(this, "This device is not supported", Toast.LENGTH_SHORT).show();
finish();
}
return false;
}
return true;
}
private void stopLocationUpdate() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
return;
}
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient,this);
}
private void displayLocation() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
return;
}
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastLocation != null)
{
if (location_switch.isChecked())
{
final double latitude = mLastLocation.getLatitude();
final double longitude = mLastLocation.getLongitude();
//Update to firebase
geoFire.setLocation(FirebaseAuth.getInstance().getCurrentUser().getUid(), new GeoLocation(latitude, longitude), new GeoFire.CompletionListener() {
#Override
public void onComplete(String key, DatabaseError error) {
//Add marker
if (mCurrent != null)
mCurrent.remove(); //Remove already marker
mCurrent = mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.car))
.position(new LatLng(latitude,longitude))
.title("You"));
// Move camera to this position
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude,longitude),15.0f));
//Draw animation rotate marker
rotateMarker(mCurrent,-360,mMap);
}
});
}
else
{
Log.d("Error", "Cannot get your location");
}
}
}
private void rotateMarker(final Marker mCurrent, final float i, GoogleMap mMap) {
final Handler handler = new Handler();
final long start = SystemClock.uptimeMillis();
final float startRotation = mCurrent.getRotation();
final long duration = 1500;
final Interpolator interpolator = new LinearInterpolator();
handler.post(new Runnable() {
#Override
public void run() {
long elapsed = SystemClock.uptimeMillis() - start;
float t = interpolator.getInterpolation((float)elapsed/duration);
float rot = t*i+(1-t)*startRotation;
mCurrent.setRotation(-rot > 180?rot/2:rot);
if (t<1.0)
{
handler.postDelayed(this,16);
}
}
});
}
private void startLocationUpdate() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,locationRequest,this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
}
#Override
public void onConnected(#Nullable Bundle bundle) {
displayLocation();
startLocationUpdate();
}
#Override
public void onConnectionSuspended(int i) {
mGoogleApiClient.connect();
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
displayLocation();
}
}
You try to ask for location updates using that line
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,locationRequest,this);
The problem is that you never initialize locationRequest variable. You have next function
private void createLocationRequest() {
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setInterval(5000);
locationRequest.setFastestInterval(1000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
To fix your problem add this line at the end of createLocationRequest()
this.locationRequest = locationRequest
private void createLocationRequest() {
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setInterval(5000);
locationRequest.setFastestInterval(1000);
locationRequest.setPriority (LocationRequest.PRIORITY_HIGH_ACCURACY);
this.locationRequest = locationRequest;
}
This was the solution to the problem.

Using Fused Location Provider for Wikitude

I previously used Android Location Manager to retrieve location. However, when I run wikitude apps, the POIs are loaded but are not displayed. I read a few posts saying that this may caused by basic Location Strategy. Therefore, I decided to use Fused Location Provider. The problem still occur. Please help me anyone
package xyz.arlayer.scratch;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.app.Activity;
import android.location.Location;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.wikitude.architect.ArchitectStartupConfiguration;
import com.wikitude.architect.ArchitectView;
import java.io.IOException;
public class Augmented extends Activity implements
LocationListener,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private static final int WIKITUDE_PERMISSIONS_REQUEST_CAMERA = 2;
private ArchitectView architectView;
private static final String TAG = "LocationActivity";
private static final long INTERVAL = 1000 * 10;
private static final long FASTEST_INTERVAL = 1000 * 5;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Location mCurrentLocation;
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_augmented);
this.architectView = this.findViewById(R.id.architectView);
final ArchitectStartupConfiguration config = new ArchitectStartupConfiguration();
config.setLicenseKey("AOfmybWCEL410fS81fIe29RwjF2eLJ00DCjmqSl+xZaUQc6E48KtXM9oxnbRayoGTjCzG2hSfq7oxzLDO0K8fVZfNyUs1DnLzm+p4jPSHEotpKJOrMmH8aOJoGLsiFfTcXzJY58Kj/EJt0dOHZvBXz/KBka4EPhvcvoDVq//6FFTYWx0ZWRfX9YCljHdYuEA0smGRDePFWZ3TTxz6sxXRJNfTU2P4aKDSsN1hXCicvw/Yf0cs8/v7xjI7UgOk+HZ+qkU2oDidWOPvPji7cbOhZ6pq3vA35s5aNJQU5t1o2LpaLuJyANaRgS/nGpmTYi/fRB6clGZcwEUgvyEl+OcNFL/7BFJUSJQTBdD6UBXy8Dfioh4mlupKMkIHn1d6nSYgTmu1tMn2MFVKTIL9O1qzopPe9O+J945Pq5NCvXbzaIL+6mn7BO6r+KxEY3XNKnpnmER0lnNxEobpY65Byy1v+oWFSCAi65mzEvGSzhGMMaqzlWHx7vJeaPRSoxqUcokvi8iLfiowRRptkiE+VQmNyb03gEViQd2LaQXl6aY+J2jKTIDXGuOLQ1C6hg0CY1AdKXjaslV4YETAkrpqIGbt+tSEeHPH+dL8gFh4UZe2g6JGQCyR4xRA0CtbAXY3CbSNCNypDox8cqOvwRnl0Jx5iwtuyQ4oOKfA6rV+94ZeLg=");
this.architectView.onCreate(config);
Log.d(TAG, "onCreate ...............................");
//show error dialog if GoolglePlayServices not available
if (!isGooglePlayServicesAvailable()) {
finish();
}
createLocationRequest();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]
{android.Manifest.permission.CAMERA}, WIKITUDE_PERMISSIONS_REQUEST_CAMERA);
}}
#Override
protected void onPostCreate (Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
architectView.onPostCreate();
try {
architectView.load("file:///android_asset/08_Browsing$Pois_5_Native$Detail$Screen/index.html"); } catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onStart() {
super.onStart();
Log.d(TAG, "onStart fired ..............");
mGoogleApiClient.connect();
}
#Override
public void onStop() {
super.onStop();
Log.d(TAG, "onStop fired ..............");
mGoogleApiClient.disconnect();
Log.d(TAG, "isConnected ...............: " + mGoogleApiClient.isConnected());
}
private boolean isGooglePlayServicesAvailable() {
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (ConnectionResult.SUCCESS == status) {
return true;
} else {
GooglePlayServicesUtil.getErrorDialog(status, this, 0).show();
return false;
}
}
#Override
public void onConnected(Bundle bundle) {
Log.d(TAG, "onConnected - isConnected ...............: " + mGoogleApiClient.isConnected());
startLocationUpdates();
}
protected void startLocationUpdates() {
PendingResult<Status> pendingResult = LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
Log.d(TAG, "Location update started ..............: ");
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.d(TAG, "Connection failed: " + connectionResult.toString());
}
#Override
public void onLocationChanged(Location location) {
Log.d(TAG, "Firing onLocationChanged..............................................");
mCurrentLocation = location;
if (location!=null && Augmented.this.architectView != null ) {
// check if location has altitude at certain accuracy level & call right architect method (the one with altitude information)
if ( location.hasAltitude() && location.hasAccuracy() && location.getAccuracy()<7) {
Augmented.this.architectView.setLocation( location.getLatitude(), location.getLongitude(), location.getAltitude(), location.getAccuracy() );
} else {
Augmented.this.architectView.setLocation( location.getLatitude(), location.getLongitude(), location.hasAccuracy() ? location.getAccuracy() : 1000 );
}
}
}
#Override
public void onResume() {
super.onResume();
architectView.onResume();
if (mGoogleApiClient.isConnected()) {
startLocationUpdates();
Log.d(TAG, "Location update resumed .....................");
}
}
#Override
protected void onPause() {
architectView.onPause();
super.onPause();
stopLocationUpdates();
}
protected void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient, this);
Log.d(TAG, "Location update stopped .......................");
}
#Override
protected void onDestroy(){
super.onDestroy();
architectView.onDestroy();
}
}

spring mvc ajax bad request error

Spring Controller Method :
#RequestMapping(value="/checklist/{id}",method=RequestMethod.PUT, consumes=MediaType.APPLICATION_JSON_VALUE , produces=MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
public Checklist update(#RequestBody Checklist checklist, #PathVariable("id") int id)
{
checklist.setId(id);
return service.update(checklist);
}
JavaScript AJAX code:
var checklist={name:$('#newName').val(), details:$('#newDetails').val()};
$.ajax({ //send updated item values to
method:'put',
url:'/tracker/checklist/'+$(editingItem).attr('id'),
contentType:'application/json',
dataType:'json',
data:checklist,
success:function(data)
{
console.log(data);
$('#myModal').modal('hide');
}
});
Checklist Model:
package com.tracker.web.models;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;
#Entity
#Table(name="checklists")
public class Checklist {
#Id #GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private int item_order;
private String name;
private String details;
private String phase;
private String completed;
private String skipped_note;
private Date completed_on;
private int completed_by;
#Temporal(TemporalType.TIMESTAMP)
#CreationTimestamp
private Date created_at;
#Temporal(TemporalType.TIMESTAMP)
#UpdateTimestamp
private Date updated_at;
#ManyToOne
private Event event;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getItem_order() {
return item_order;
}
public void setItem_order(int item_order) {
this.item_order = item_order;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDetails() {
return details;
}
public void setDetails(String details) {
this.details = details;
}
public String getPhase() {
return phase;
}
public void setPhase(String phase) {
this.phase = phase;
}
public String getCompleted() {
return completed;
}
public void setCompleted(String completed) {
this.completed = completed;
}
public String getSkipped_note() {
return skipped_note;
}
public void setSkipped_note(String skipped_note) {
this.skipped_note = skipped_note;
}
public Date getCompleted_on() {
return completed_on;
}
public void setCompleted_on(Date completed_on) {
this.completed_on = completed_on;
}
public int getCompleted_by() {
return completed_by;
}
public void setCompleted_by(int completed_by) {
this.completed_by = completed_by;
}
public Date getCreated_at() {
return created_at;
}
public void setCreated_at() {
this.created_at = new Date();
}
public Date getUpdated_at() {
return updated_at;
}
public void setUpdated_at() {
this.updated_at = new Date();
}
public Event getEvent() {
return event;
}
public void setEvent(Event event) {
this.event = event;
}
}
I am using Jquery 1.11. when i use with 'GET' instead of 'PUT' 'method' on client side and 'consumes' on server side, it works. even i tried with JSON.stringify while sending sending. i am using jackson on server side to convert data into json
Which version of jquery you are using?
If you are using jquery prior to 1.9.0 than try type: 'PUT' instead of method:'put' in your ajax call and it should work. Otherwise it should be of with method:'put' .
Check documentation for more reference http://api.jquery.com/jquery.ajax/

Webview Fragment : Back button and Download Listener?

I make simple webview app. using Webview fragment. App working properly. but problem is i click back button app close down. and second problem is i click on html page link. link not open in default browser. error says webpage not open. i want all tab open in same webview and back button and download link work properly. my code is
MyWebViewFragment.java
package com.example.com;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MyWebViewFragment extends Fragment {
ProgressDialog mProgress;
WebView webview;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.web_fragment, container,
false);
Bundle bundle = getArguments();
String url = bundle.getString("url");
webview = (WebView) rootView.findViewById(R.id.webview1);
WebSettings settings = webview.getSettings();
settings.setJavaScriptEnabled(true);
mProgress = ProgressDialog.show(getActivity(), "Loading",
"Please wait for a moment...");
webview.loadUrl(url);
webview.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if (mProgress.isShowing()) {
mProgress.dismiss();
}
}
});
return rootView;
}
}
MainActivity.java
package com.example.com;
import java.util.ArrayList;
import java.util.List;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
public class MainActivity extends Activity {
String[] menutitles;
TypedArray menuIcons;
String[] pageUrl;
// nav drawer title
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private List<RowItem> rowItems;
private CustomAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
menutitles = getResources().getStringArray(R.array.titles);
menuIcons = getResources().obtainTypedArray(R.array.icons);
pageUrl = getResources().getStringArray(R.array.pageurl);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.slider_list);
rowItems = new ArrayList<RowItem>();
for (int i = 0; i < menutitles.length; i++) {
RowItem items = new RowItem(menutitles[i], menuIcons.getResourceId(
i, -1), pageUrl[i]);
rowItems.add(items);
}
menuIcons.recycle();
adapter = new CustomAdapter(getApplicationContext(), rowItems);
mDrawerList.setAdapter(adapter);
mDrawerList.setOnItemClickListener(new SlideitemListener());
// enabling action bar app icon and behaving it as toggle button
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.app_name,
R.string.app_name) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
// on first time display view for first nav item
updateDisplay(0);
}
}
class SlideitemListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
updateDisplay(position);
}
}
private void updateDisplay(int position) {
String url = rowItems.get(position).getPageUrl();
Fragment fragment = new MyWebViewFragment();
Bundle bundle = new Bundle();
bundle.putString("url", url);
fragment.setArguments(bundle);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
setTitle(menutitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// toggle nav drawer on selecting action bar app icon/title
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action bar actions click
switch (item.getItemId()) {
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/***
* Called when invalidateOptionsMenu() is triggered
*/
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// if nav drawer is opened, hide the action items
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
#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);
// Pass any configuration change to the drawer toggles
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
To open urls in webview use the code
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.webView);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setPluginState(WebSettings.PluginState.OFF);
webSettings.setSupportMultipleWindows(true);
webSettings.setBuiltInZoomControls(true);
webSettings.setAppCacheMaxSize(1);
webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
webSettings.setAppCacheEnabled(false);
// webView.setVerticalScrollBarEnabled(false);
// webView.setHorizontalScrollBarEnabled(false);
webView.setWebChromeClient(new WebChromeClient());
webView.clearCache(true);
// webView.setInitialScale(100);
// webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webView.setBackgroundColor(0);
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
Log.e("", "shouldOverrideUrlLoading load url" + url);
return false;
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
isLoaded = false;
progressDialog.setMessage("Unknown Error!");
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
try {
progressDialog.dismiss();
} catch (Exception e) {
}
}
}, 1500);
}
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
displayProgress(getString(R.string.loading), getString(R.string.loading));
Log.e("onPageStarted",url);
}
public void onPageFinished(WebView view, String url) {
isLoaded = true;
super.onPageFinished(view, url);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
try {
progressDialog.dismiss();
} catch (Exception e) {
}
}
}, 1500);
}
});
web_link = "https://twitter.com";
webView.loadUrl(web_link);
}
public void displayProgress(String title,String mes){
if (progressDialog!=null)
progressDialog.dismiss();
progressDialog = new ProgressDialog(MainActivity.this);
// progressDialog.setTitle(title);
progressDialog.setMessage(mes);
progressDialog.setIndeterminate(false);
progressDialog.setCancelable(true);
try {
progressDialog.show();
} catch (Exception e) {
e.printStackTrace();
}
}
To go back on web view override this method to your activity
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (web_link!=null && !webView.getUrl().equals(web_link))
webView.goBack();
else{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.to_exit)
.setCancelable(false)
.setPositiveButton(getString(android.R.string.yes), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
MainActivity.this.finish();
}
})
.setNegativeButton(getString(android.R.string.no), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
return super.onKeyDown(keyCode, event);
}

Categories