Null exception starting activity with intent - java

I'm receiving an exception that equals null when attempting to create a new activity using Intent. Basically my program terminates when I try to create this new Activity i.e. switch the screen the user sees to one with an animated treasure box (png files from xml, which works when they are run from the MainActivity).
Here is a picture from Android Studio of the error I am receiving:
I'm developing a Vuzix M100 application on a device running vr4.0.4.
Here are the two activities I am running:
MainActivity.java
package com.rit.se.treasurehuntvuz;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import android.util.Log;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onStop() {
super.onStop();
}
#Override
protected void onRestart() {
super.onRestart();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
public void onBackPressed() {
try {
Intent showTreasureIntent = new Intent(this, ShowTreasureActivity.class);
startActivity(showTreasureIntent);
}
catch(Exception exception) {
Log.e("MainActivity", exception.getMessage());
}
}
}
ShowTreasureActivity.java
package com.rit.se.treasurehuntvuz;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;
public class ShowTreasureActivity extends AppCompatActivity {
private ImageView treasureImage;
private AnimationDrawable treasureAnimation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_showtreasure);
treasureImage = (ImageView)findViewById(R.id.treasureAnimationView);
treasureImage.setBackgroundResource(R.drawable.anim_treasure);
treasureAnimation = (AnimationDrawable) treasureImage.getBackground();
treasureAnimation.setOneShot(true);
}
#Override
public void onWindowFocusChanged (boolean hasFocus)
{
treasureAnimation.start();
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onStop() {
super.onStop();
}
#Override
protected void onRestart() {
super.onRestart();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
public void onBackPressed() {
}
}

Thanks to #Joel Duggan, it turned out I was lacking an entry in the manifest file.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.rit.se.treasurehuntvuz">
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".ShowTreasureActivity">
</activity>
</application>
</manifest>

Related

I can't start activity from service while app is hidden

I have two activities: MainActivity and ActivityTwo. When starting application, I start service serviceApp, which after some events should start ActivityTwo. For the test, I made the launch after 10 seconds and AsyncTask, but if the application is hidden, activity does not start
How do I launch activity even if the app is hidden?
MainActivity
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SwitchCompat;
import android.app.ActivityManager;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import java.security.Provider;
import java.util.List;
public class MainActivity extends AppCompatActivity {
SharedPreferences setting;
#Override
protected void onCreate(Bundle savedInstanceState) {
Intent service = new Intent(this, serviceApp.class);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setting = getSharedPreferences("settings", MODE_PRIVATE);
SwitchCompat switchCompat = findViewById(R.id.switchBLock);
switchCompat.setOnCheckedChangeListener((view, bool) -> {
SharedPreferences.Editor editor = setting.edit();
editor.putBoolean("block", bool);
editor.apply();
if(bool){
startService(service);
}else{
stopService(service);
}
});
if(setting.getBoolean("block", false)){
switchCompat.setChecked(true);
}
}
}
ActivityTwo
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;
public class ActivityTwo extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_two);
}
}
serviceApp
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.IBinder;
public class serviceApp extends Service {
Context context;
public serviceApp() {
context = this;
}
#Override
public void onCreate() {
super.onCreate();
new Async().execute();
}
class Async extends AsyncTask<Void, Void, Void>{
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
Intent startMain = new Intent();
startMain.setClass(context, ActivityTwo.class);
startMain.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);
}
#Override
protected Void doInBackground(Void... voids) {
for(int i = 0; i < 2; i++) {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return null;
}
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
AndroidManifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.test">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.AppCompat.NoActionBar">
<activity android:name="com.example.test.ActivityTwo"></activity>
<service
android:name=".serviceApp"/>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
I found an easy way to fix this ailment, you need to give the application the SYSTEM_ALERT_WINDOW permission
https://developer.android.com/guide/components/activities/background-starts
AndroidManifest.xml
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
MainActivity
Intent myIntent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
startActivity(myIntent);

Application different error depending on device

Logcart is giving error like, on my phone
2020-05-03 17:48:38.715 1785-2071/com.example.tasteportal04b E/libGLESv2: ASUS:glGetString HOOK !!!! name=0x1f01,ret=Adreno (TM) 512
On some devices like Samsung S6, the app is not starting, displaying a crash message, on my Asus works perfectly
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.tasteportal04b">
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="#drawable/ic_taste" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<application
android:name=".nootificare"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme"
android:usesCleartextTraffic="true"
android:screenOrientation="portrait"
android:hardwareAccelerated="true"
android:largeHeap="true"
>
<activity android:name=".MainActivity"
android:hardwareAccelerated="false">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".NewActivity" android:screenOrientation="portrait"
android:theme="#style/SplashTheme"></activity>
</application>
</manifest>
NewActivity.java
package com.example.tasteportal04b;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.view.HapticFeedbackConstants;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.getbase.floatingactionbutton.FloatingActionButton;
import java.util.Objects;
public class NewActivity extends AppCompatActivity {
Toolbar toolbar;
private WebView webView;
private ProgressBar progressbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new);
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Objects.requireNonNull(getSupportActionBar()).setTitle("TASTE Live");
toolbar.setSubtitle("v1.0");
toolbar.setLogo(R.mipmap.tasteico);
toolbar.setTitleTextColor(getResources().getColor(R.color.colortitle));
toolbar.setSubtitleTextColor(getResources().getColor(R.color.colorsubtitle));
webView = findViewById(R.id.webView);
progressbar = findViewById(R.id.progressbar);
progressbar.setMax(100);
webView.loadUrl("https://");
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setBuiltInZoomControls(false);
webView.setBackgroundColor(Color.TRANSPARENT);
webView.setWebChromeClient(new WebChromeClient(){
#Override
public void onProgressChanged(WebView view, int newProgress)
{
super.onProgressChanged(view, newProgress);
progressbar.setProgress(newProgress);
}
});
FloatingActionButton facebook = findViewById(R.id.Facebook);
FloatingActionButton classroom = findViewById(R.id.Classroom);
FloatingActionButton blog = findViewById(R.id.Blog);
FloatingActionButton youtube = findViewById(R.id.Youtube);
FloatingActionButton drive = findViewById(R.id.Drive);
facebook.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
v.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
try {
Intent gofb = new Intent(Intent.ACTION_VIEW, Uri.parse("fb://page/"));
startActivity(gofb);
} catch(Exception e) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/TASTEATB")));
}
showToast("T.A.S.T.E Facebook");
}
});
classroom.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
v.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
Intent goclass = new Intent(Intent.ACTION_VIEW, Uri.parse("https://classroom.google.com/u/0/c/NzgzMTc2MDk5NjNa"));
startActivity(goclass);
showToast("T.A.S.T.E Classroom");
}
});
blog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
v.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
Intent goblog = new Intent(Intent.ACTION_VIEW, Uri.parse("https://"));
startActivity(goblog);
showToast("T.A.S.T.E Blog");
}
});
youtube.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
v.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
Intent goyt = new Intent(Intent.ACTION_VIEW);
try {
goyt.setData(Uri.parse("https://"));
goyt.setPackage("com.google.android.youtube");
} catch(Exception e) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.youtube.com/channel/")));
}
startActivity(goyt);
showToast("T.A.S.T.E Youtube");
}
});
drive.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
v.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
Intent godrive = new Intent(Intent.ACTION_VIEW, Uri.parse("https://"));
startActivity(godrive);
showToast("T.A.S.T.E Drive");
}
});
}//inchide oncreate
public void showToast(String message){
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId())
{
case R.id.bug:
Intent gobug = new Intent(Intent.ACTION_VIEW, Uri.parse("https://"));
startActivity(gobug);
showToast("Raporteaza un bug");
break;
case R.id.update:
showToast("Update aplicatie");
webView.loadUrl("https://");
break;
}
return super.onOptionsItemSelected(item);
}
}

Webview - How to stay on the current page on Rotate

I developed a website for my entreprisee and I work almost exclusively with PHP
So the Java language (and android studio) is a really new for me. Despite this I have to create an APK to use the website (in order to block the android home on this site)
But when I turn the screen, the webview displays the homepage rather than the current page.
I did some research and I integrated what I saw here: Android - Preventing WebView reload on Rotate
But that does not work and I do not understand why I always come back on "Google.com"
MainActivity.java
package eu.test.chrome;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
public class MainActivity extends AppCompatActivity {
WebView webView;
SwipeRefreshLayout swipe;
ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar = (ProgressBar) findViewById(R.id.awv_progressBar);
swipe = (SwipeRefreshLayout) findViewById(R.id.swipe);
LoadWeb();
progressBar.setMax(100);
progressBar.setProgress(1);
swipe = (SwipeRefreshLayout) findViewById(R.id.swipe);
swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
webView.reload();
}
});
webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
progressBar.setProgress(progress);
}
});
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
progressBar.setVisibility(View.VISIBLE);
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
webView.loadUrl("file:///android_asset/error.html");
}
public void onPageFinished(WebView view, String url) {
//Don't show ProgressBar
progressBar.setVisibility(View.GONE);
//Hide the SwipeRefreshLayout
swipe.setRefreshing(false);
}
});
}
/* I integrated what I saw here: https://stackoverflow.com/questions/12131025/android-preventing-webview-reload-on-rotate but that does not work
#Override
protected void onSaveInstanceState(Bundle outState )
{
super.onSaveInstanceState(outState);
webView.saveState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState)
{
super.onRestoreInstanceState(savedInstanceState);
webView.restoreState(savedInstanceState);
}*/
public void LoadWeb() {
webView = (WebView) findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setAppCacheEnabled(true);
webView.loadUrl("https://www.google.com/");
swipe.setRefreshing(true);
}
#Override
public void onBackPressed() {
if (webView.canGoBack()) {
webView.goBack();
} else {
finish();
}
}
}
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:id="#+id/rel_parent"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<ProgressBar
android:id="#+id/awv_progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="26dp"
android:indeterminate="true" />
<android.support.v4.widget.SwipeRefreshLayout
android:id="#+id/swipe"
android:layout_width="match_parent"
android:layout_height="match_parent">
<WebView
android:id="#+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</android.support.v4.widget.SwipeRefreshLayout>
</LinearLayout>
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="eu.test.chrome">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:hardwareAccelerated="false"
android:configChanges="orientation|screenSize"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
In Order to Load the Url Before Rotation, you need to make some additions.
public class MainActivity extends AppCompatActivity {
WebView webView;
SwipeRefreshLayout swipe;
ProgressBar progressBar;
private final String CACHE_URL_KEY = "CACHE_URL";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar = (ProgressBar) findViewById(R.id.awv_progressBar);
swipe = (SwipeRefreshLayout) findViewById(R.id.swipe);
LoadWeb(savedInstanceState);
progressBar.setMax(100);
progressBar.setProgress(1);
swipe = (SwipeRefreshLayout) findViewById(R.id.swipe);
swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
webView.reload();
}
});
webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
progressBar.setProgress(progress);
}
});
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
progressBar.setVisibility(View.VISIBLE);
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
webView.loadUrl("file:///android_asset/error.html");
}
public void onPageFinished(WebView view, String url) {
//Don't show ProgressBar
progressBar.setVisibility(View.GONE);
//Hide the SwipeRefreshLayout
swipe.setRefreshing(false);
}
});
}
#Override
protected void onSaveInstanceState(Bundle outState )
{
outState.putString(CACHE_URL_KEY,webView.getUrl());
super.onSaveInstanceState(outState);
}
public void LoadWeb(Bundle savedInstanceState) {
webView = (WebView) findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setAppCacheEnabled(true);
if (savedInstanceState != null) {
String savedUrl = savedInstanceState.getString(CACHE_URL_KEY);
webView.loadUrl(savedUrl);
}else {
webView.loadUrl("https://www.google.com/");
}
swipe.setRefreshing(true);
}
#Override
public void onBackPressed() {
if (webView.canGoBack()) {
webView.goBack();
} else {
finish();
}
}
}
These are the Steps Made:
You need to Create a Key to identify the Saved URL
private final String CACHE_URL_KEY = "CACHE_URL";
You need to save the URL Each Time you rotate
#Override
protected void onSaveInstanceState(Bundle outState ) {
outState.putString(CACHE_URL_KEY,webView.getUrl());
super.onSaveInstanceState(outState);
}
You Need to Check if There is a Rotation or not. If yes, savedInstanceState won't be null therefore retrieve the Url and load it.
Else Load Default page
if (savedInstanceState != null) {
String savedUrl = savedInstanceState.getString(CACHE_URL_KEY);
webView.loadUrl(savedUrl);
}else {
webView.loadUrl("https://www.google.com/");
}
Also, Pass the saved state to LoadWeb method
Try this
import android.graphics.Bitmap;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.support.v4.widget.SwipeRefreshLayout;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
public class Main2Activity extends AppCompatActivity {
WebView webView;
SwipeRefreshLayout swipe;
ProgressBar progressBar;
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
LoadWeb();
progressBar = (ProgressBar) findViewById(R.id.awv_progressBar);
progressBar.setMax(100);
progressBar.setProgress(1);
swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
webView.reload();
}
});
webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
progressBar.setProgress(progress);
}
});
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
progressBar.setVisibility(View.VISIBLE);
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
webView.loadUrl("https://stackoverflow.com/questions/47885592/how-to-add-a-progress-loading-bar-in-webview/47885692#47885692");
}
public void onLoadResource(WebView view, String url) { //Doesn't work
// swipe.setRefreshing(true);
}
public void onPageFinished(WebView view, String url) {
//Hide the SwipeReefreshLayout
progressBar.setVisibility(View.GONE);
swipe.setRefreshing(false);
}
});
}
public void LoadWeb() {
swipe = (SwipeRefreshLayout) findViewById(R.id.swipe);
webView = (WebView) findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setAppCacheEnabled(true);
webView.loadUrl("http://dev.ncryptedprojects.com/bistrostays_v3/");
swipe.setRefreshing(true);
}
#Override
protected void onSaveInstanceState(Bundle outState )
{
super.onSaveInstanceState(outState);
webView.saveState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState)
{
super.onRestoreInstanceState(savedInstanceState);
webView.restoreState(savedInstanceState);
}
#Override
public void onBackPressed() {
if (webView.canGoBack()) {
webView.goBack();
} else {
finish();
}
}
}
and in your manifest file
<activity android:name=".MainActivity"
android:configChanges="orientation|screenSize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
Create Method in Android like :
#JavascriptInterface
public boolean CallByMobApp(){
return true;
}
Create Calling function in JavaScript :
$(window).load(function () {
IsCallByMobileApp = false;
try {
IsCallByMobileApp = app.CallByMobApp();/*Is call by android app*/
} catch (e) {
IsCallByMobileApp = false;
}
}
According to this method you can manage which page to be open.
You call the method LoadWeb each time. You need to check if savedInstanceState == null then call LoadWeb. If savedInstanceState != null then don't call LoadWeb

cannot be cast to com.google.android.gms.location.LocationListener exception in android

i am facing an exception in my application, the exception is related to com.google.android.gms.location.LocationListner in android, please help me in this regards
My MainActivity.java file:
package com.ideabiz.fusedlocationprovider;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener {
TextView txtOutputLat, txtOutputLon;
Location mLastLocation;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
String lat, lon;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtOutputLat = (TextView) findViewById(R.id.textView);
txtOutputLon = (TextView) findViewById(R.id.textView2);
buildGoogleApiClient();
}
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(100); // Update location every second
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, (com.google.android.gms.location.LocationListener) this);
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
lat = String.valueOf(mLastLocation.getLatitude());
lon = String.valueOf(mLastLocation.getLongitude());
}
updateUI();
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onLocationChanged(Location location) {
lat = String.valueOf(location.getLatitude());
lon = String.valueOf(location.getLongitude());
updateUI();
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
buildGoogleApiClient();
}
synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
#Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
protected void onDestroy() {
super.onDestroy();
mGoogleApiClient.disconnect();
}
void updateUI() {
txtOutputLat.setText(lat);
txtOutputLon.setText(lon);
}
}
My logcat file:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.ideabiz.fusedlocationprovider, PID: 18114
java.lang.ClassCastException: com.ideabiz.fusedlocationprovider.MainActivity cannot be cast to com.google.android.gms.location.LocationListener
at com.ideabiz.fusedlocationprovider.MainActivity.onConnected(MainActivity.java:52)
My Manifest.xml file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.ideabiz.fusedlocationprovider">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
</application>
</manifest>
If you take a look on the logcat, the error stated that you have imported wrong LocationListener. Check on your imported library at the top part of the class, it supposed to be com.google.android.gms.location.LocationListener not android.location.LocationListener.

start an activity from a TimerTask class

How can I start an activity in another class. It's in eclipse. It is just for start Main activity after a while.
public class FirstShow extends ActionBarActivity {
#SuppressLint("ShowToast")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first_show);
Timer tm;
tm = new Timer();
ttask task = new ttask();
tm.schedule(task, 30000);
}
}
class ttask extends TimerTask {
#Override
public void run() {
// TODO Auto-generated method stub
FirstShow.class.startActivity());
}
}
I want to start another activity after a couple of seconds. How can I do that?
package com.example.teststart;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
public class FirstActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Intent i=new Intent(FirstActivity.this,secondactivity.class);
startActivity(i);
}
}, 3000);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.first, menu);
return true;
}
}
package com.example.teststart;
import android.app.Activity;
import android.os.Bundle;
public class secondactivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.secondactvity);
}
}
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.teststart.FirstActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.example.teststart.secondactivity"
android:label="#string/app_name" />
</application>
Friend if you want normally want to start activity after few second than use my code:----->
Thread thread = new Thread() {
public void run() {
try {
sleep(3*1000);
Intent i=new Intent(getBaseContext(),ManuList.class);
startActivity(i);
finish();
} catch (Exception e) {
}
}
};
thread.start();
}
public class FirstShow extends ActionBarActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first_show);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Intent i=new Intent(FirstShow.this,secondactivity.class);
startActivity(i);
}
}, 3000);
}
}

Categories