I am trying to create this Volley project as my second activity which fetches a JSON feed from Yahoo Pipe and display in a ListView from here. The code works perfectly fine. However, I have encountered these problems:
When I have not turned the Internet on, the activity displays the loading ProgressDialog. However, pressing the Back button on my emulator or actual device does not dismiss the ProgressDialog. The activity did not respond to the Back action.
I tried this code, but it does not work or maybe I'm not doing it right:
#Override
public void onDestroy() {
super.onDestroy();
dismissPd();
}
private void dismissPd() {
if (pd != null) {
pd.dismiss();
pd = null;
}
}
In case of an Internet connection error, how do I display the error message in this activity as a toast?
The following is my code:
public class Trending extends ActionBarActivity {
private String TAG = this.getClass().getSimpleName();
private ListView lstView;
private RequestQueue mRequestQueue;
private ArrayList<NewsModel> arrNews ;
private LayoutInflater lf;
private VolleyAdapter va;
private ProgressDialog pd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.trending);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Intent newActivity3=new Intent();
setResult(RESULT_OK, newActivity3);
lf = LayoutInflater.from(this);
arrNews = new ArrayList<NewsModel>();
va = new VolleyAdapter();
lstView = (ListView) findViewById(R.id.listView);
lstView.setAdapter(va);
mRequestQueue = Volley.newRequestQueue(this);
String url = "http://pipes.yahooapis.com/pipes/pipe.run?_id=giWz8Vc33BG6rQEQo_NLYQ&_render=json";
pd = ProgressDialog.show(this,"Loading...","Please Wait...");
try {
Thread.sleep(2000);
} catch(Exception e) {
}
JsonObjectRequest jr = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.i(TAG,response.toString());
parseJSON(response);
va.notifyDataSetChanged();
pd.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i(TAG,error.getMessage());
}
});
mRequestQueue.add(jr);
}
#Override
public void onDestroy() {
super.onDestroy();
dismissPd();
}
private void dismissPd() {
if (pd != null) {
pd.dismiss();
pd = null;
}
}
private void parseJSON(JSONObject json){
try {
JSONObject value = json.getJSONObject("value");
JSONArray items = value.getJSONArray("items");
for (int i=0; i<items.length(); i++) {
JSONObject item = items.getJSONObject(i);
NewsModel nm = new NewsModel();
nm.setTitle(item.optString("title"));
nm.setDescription(item.optString("description"));
nm.setLink(item.optString("link"));
nm.setPubDate(item.optString("pubDate"));
arrNews.add(nm);
}
}
catch(Exception e){
e.printStackTrace();
}
}
class NewsModel {
private String title;
private String link;
private String description;
private String pubDate;
void setTitle(String title) {
this.title = title;
}
void setLink(String link) {
this.link = link;
}
void setDescription(String description) {
this.description = description;
}
void setPubDate(String pubDate) {
this.pubDate = pubDate;
}
String getLink() {
return link;
}
String getDescription() {
return description;
}
String getPubDate() {
return pubDate;
}
String getTitle() {
return title;
}
}
class VolleyAdapter extends BaseAdapter {
#Override
public int getCount() {
return arrNews.size();
}
#Override
public Object getItem(int i) {
return arrNews.get(i);
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
ViewHolder vh;
if (view == null) {
vh = new ViewHolder();
view = lf.inflate(R.layout.row_listview,null);
vh.tvTitle = (TextView) view.findViewById(R.id.txtTitle);
vh.tvDesc = (TextView) view.findViewById(R.id.txtDesc);
vh.tvDate = (TextView) view.findViewById(R.id.txtDate);
view.setTag(vh);
} else {
vh = (ViewHolder) view.getTag();
}
NewsModel nm = arrNews.get(i);
vh.tvTitle.setText(nm.getTitle());
vh.tvDesc.setText(nm.getDescription());
vh.tvDate.setText(nm.getPubDate());
return view;
}
class ViewHolder {
TextView tvTitle;
TextView tvDesc;
TextView tvDate;
}
}
}
try this one then back button is working while dialog is running
pd = ProgressDialog.show(this,"Loading...","Please Wait...");
pd.setCancelable(true);
By use asynctask you write code like this way
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
pd = ProgressDialog.show(ctx, null, "fetching ...");
pd.setCancelable(true);
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
try {
//fetch response from internet and process here
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
pd.cancel();
//do next action here
super.onPostExecute(result);
}
You have to execute the JSON part of the code in AsyncTask.
Define doInBackground to return a String type. From doInBackground, handle the errors, like internet error or json error and accordingly return a suitable error message "internet error" or "json error".
This error will be available as input to onPostExecute (results). In onPostExecute, you can run a Switch Statement to handle each of the conditions. If "internet error", then pd.dismiss() and do a toast.
For a working version of the code, you can refer here...
Related
Although I have tried many things, I cannot fix it. I apply the methods with Alt + Enter, I make the necessary arrangements on the added classes, but I still did not get a smooth result.
Error code;
Class 'Anonymous class derived from FirebaseRecyclerAdapter' must
either be declared abstract or implement abstract method
'onBindViewHolder (VH, int, T)' in 'FirebaseRecyclerAdapter'
Activity.Java
public class PlacesActivity extends AppCompatActivity {
private RecyclerView mBlogList;
private DatabaseReference mDatabase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_places);
mDatabase = FirebaseDatabase.getInstance().getReference().child("Global");
mDatabase.keepSynced(true);
mBlogList = (RecyclerView) findViewById(R.id.placesRecyclerView);
mBlogList.setHasFixedSize(true);
mBlogList.setLayoutManager(new LinearLayoutManager(this));
}
#Override
protected void onStart() {
super.onStart();
FirebaseRecyclerAdapter<Blog, BlogViewHolder>firebaseRecyclerAdapter= new FirebaseRecyclerAdapter<Blog, BlogViewHolder>
(Blog.class, R.layout.blog_row,BlogViewHolder.class,mDatabase) {
protected void populateViewHolder(Blog model, BlogViewHolder viewHolder, int position){
viewHolder.setTitle(model.getTitle());
viewHolder.setDesc(model.getDesc());
viewHolder.setImage(getApplicationContext(), model.getImage());
}
};
firebaseRecyclerAdapter.startListening();;
mBlogList.setAdapter(firebaseRecyclerAdapter);
}
public static class BlogViewHolder extends RecyclerView.ViewHolder
{
View mView;
public BlogViewHolder(View itemView)
{
super(itemView);
mView=itemView;
}
public void setTitle(String title)
{
TextView post_title = (TextView)mView.findViewById(R.id.post_title);
post_title.setText(title);
}
public void setDesc(String desc){
TextView post_desc = (TextView)mView.findViewById(R.id.post_desc);
post_desc.setText(desc);
}
public void setImage(Context ctx, String image)
{
ImageView post_image = (ImageView)mView.findViewById(R.id.post_image);
Picasso.with(ctx).load(image).into(post_image);
}
}
}
Blog.java
public class Blog {
private String title;
private String desc;
private String image;
public Blog(String title, String desc, String image) {
this.title = title;
this.desc = desc;
this.image = image;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public Blog(){
}
}
populateRecyclerView
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) {
}
}
}
I am trying to develop an android app, I am using Retrofit2 for handling all my network stuff and communication with the server.
I have a main activity and I also have login activity.
I am initializing the Retrofit on the main activity and I am trying to send the login activity the retrofit initialized interface and then things got hard.
According to a little research I can't just send the retrofit stuff to the new activity with '.putextra(...)' function.
I will be happy to get some help with that.
My Main Activity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final UserService userConnection;
userConnection = ApiUtils.getUserService();
Toolbar toolBar = (Toolbar)findViewById(R.id.app_bar);
toolBar.setTitle("Welcome #PlaceHolder");
setSupportActionBar(toolBar);
startActivity(new Intent(MainActivity.this,LoginActivity.class));
// Intent i = new Intent(this, LoginActivity.class);
// i.putExtra("userConnection", (Serializable) userConnection);
// startActivity(i);
ScrollView feed = (ScrollView)findViewById(R.id.feedView);
//LinearLayOut Setup
LinearLayout feed1 = (LinearLayout)findViewById(R.id.feed);
Feed feed2 = new Feed(this,feed1);
feed1 = feed2.getFeed();
//***************************************************//
Call call = userConnection.getResponse();
call.enqueue(new Callback() {
#Override
public void onResponse(Call call, Response response) {
if(response.isSuccessful()){
ResObj resObj = (ResObj) response.body();
if(resObj.getpostID().equals("12Aa")){
//login start main activity
//Intent intent = new Intent(MainActivity.this, MainActivity.class);
// intent.putExtra("username", "tomer");
//startActivity(intent);
Log.e("Error is blabla: ","Yes");
} else {
Toast.makeText(MainActivity.this, "The username or password is incorrect", Toast.LENGTH_SHORT).show();
Log.e("Error is blabla: ",response.toString());
}
Log.e("Error is blabla: ",response.message().toString());
} else {
Toast.makeText(MainActivity.this, "Error! Please try again!", Toast.LENGTH_SHORT).show();
Log.e("Error is blabla: ",response.toString());
}
}
#Override
public void onFailure(Call call, Throwable t) {
Toast.makeText(MainActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
Log.e("Error is blabla: ",t.toString());
}
});
}
}
My Login Activity:
public class LoginActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Intent intent = getIntent();
final UserService userConnection =(UserService)getIntent.getSerializableExtra("userConnection");
Button loginBtn = (Button)findViewById(R.id.loginButton);
EditText emailBox = (EditText) findViewById(R.id.emailBox);
EditText passBox = (EditText) findViewById(R.id.passBox);
final String email = emailBox.getText().toString();
final String password = passBox.getText().toString();
loginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Call login = userConnection.login(email,password);
login.enqueue(new Callback() {
#Override
public void onResponse(Call call, retrofit2.Response response) {
if(response.isSuccessful())
{
ResObj resObj = (ResObj) response.body();
if(resObj.loginStatus().equals("connected")){
Log.e("Login Status: ","Success");
finish();
}
else {
Log.e("Login Status: ","Wrong Password or Email");
}
}
}
#Override
public void onFailure(Call call, Throwable t) {
Log.e("Login Status: ","Faild To Recieve Server Message");
}
});
}
});
Button registerBtn = (Button)findViewById(R.id.registerButton);
registerBtn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v){
startActivity(new Intent(LoginActivity.this,RegisterActivity.class));
}
});
}
}
The UserService Interface:
public interface UserService{
#GET("/testDB")
Call<ResObj> getResponse(
);
#POST("/login")
Call<ResObj> login(#Query("userEmail") String userEmail,
#Query("userPassword") String userPassword);
}
The ApiUtiles Class:
public class ApiUtils {
public static final String BASE_URL = "http://**.***.***.***:****";
public static UserService getUserService(){
return RetrofitClient.getClient(BASE_URL).create(UserService.class);
}
}
I will be happy to get solution or guide of how to send retrofit interfaces between activities :)
I'm using android studio
I need to replace the body of an html document with other codes, this is an example that I tried to follow
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.grafico);
wv = (WebView) findViewById(R.id.prova);
wv.setWebViewClient(new MyWebViewClient());
new BackgroundWorker().execute();
}
// load links in WebView instead of default browser
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return false;
}
#RequiresApi(21)
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
view.loadUrl(request.getUrl().toString());
return false;
}
}
private class BackgroundWorker extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0) {
getDarewod();
return null;
}
public void getDarewod() {
try {
Document htmlDocument = Jsoup.connect(url).get();
Element element = htmlDocument.select("#gkHeaderMod > div.grafico-quotazione").first();
// replace body with selected element
htmlDocument.body().empty().append(element.toString());
final String html = htmlDocument.toString();
uiHandler.post(new Runnable() {
#Override
public void run() {
wv.loadData(html, "text/html", "UTF-8");
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
I want to replace the all body with the code in my element variable. However this line doesn't works. How can I do?
htmlDocument.body().empty().append(element.toString());
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();
}
}