Android Wear app has stopped working in android studio emulator - javascript

I'm trying to run a code in my android studio emulator but after I run it, the emulator keeps showing "(App name) has stopped. Open app again".
This is an app to get accelerometer and gyro sensor data from Android wear.
I've checked the logcat and found this error in the process.
03-06 04:18:57.364 3189-3189/com.drejkim.androidwearmotionsensors E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.drejkim.androidwearmotionsensors, PID: 3189
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.hardware.Sensor.getStringType()' on a null object reference
at com.drejkim.androidwearmotionsensors.SensorFragment.onCreateView(SensorFragment.java:63)
at android.app.Fragment.performCreateView(Fragment.java:2353)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:995)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1171)
at android.app.BackStackRecord.run(BackStackRecord.java:816)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1578)
at android.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:563)
at android.support.wearable.view.FragmentGridPagerAdapter.finishUpdate(FragmentGridPagerAdapter.java:196)
at android.support.wearable.view.GridViewPager.populate(GridViewPager.java:1161)
at android.support.wearable.view.GridViewPager.populate(GridViewPager.java:1008)
at android.support.wearable.view.GridViewPager.onMeasure(GridViewPager.java:1322)
at android.view.View.measure(View.java:19857)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6083)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
at android.view.View.measure(View.java:19857)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6083)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
at android.support.wearable.view.WatchViewStub.onMeasure(WatchViewStub.java:136)
at android.view.View.measure(View.java:19857)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6083)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
at android.view.View.measure(View.java:19857)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6083)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
at com.android.internal.policy.DecorView.onMeasure(DecorView.java:690)
at android.view.View.measure(View.java:19857)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2275)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1366)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1675)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1254)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6338)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:874)
at android.view.Choreographer.doCallbacks(Choreographer.java:686)
at android.view.Choreographer.doFrame(Choreographer.java:621)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:860)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
And here're three of my java codes:
SensorFragments.java:
package com.drejkim.androidwearmotionsensors;
import android.app.Fragment;
import android.content.Context;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.util.FloatMath;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class SensorFragment extends Fragment implements SensorEventListener {
private static final float SHAKE_THRESHOLD = 1.1f;
private static final int SHAKE_WAIT_TIME_MS = 250;
private static final float ROTATION_THRESHOLD = 2.0f;
private static final int ROTATION_WAIT_TIME_MS = 100;
private View mView;
private TextView mTextTitle;
private TextView mTextValues;
private SensorManager mSensorManager;
private Sensor mSensor;
private int mSensorType;
private long mShakeTime = 0;
private long mRotationTime = 0;
public static SensorFragment newInstance(int sensorType) {
SensorFragment f = new SensorFragment();
// Supply sensorType as an argument
Bundle args = new Bundle();
args.putInt("sensorType", sensorType);
f.setArguments(args);
return f;
}
#Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle args = getArguments();
if(args != null) {
mSensorType = args.getInt("sensorType");
}
mSensorManager = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);
mSensor = mSensorManager.getDefaultSensor(mSensorType);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mView = inflater.inflate(R.layout.sensor, container, false);
mTextTitle = (TextView) mView.findViewById(R.id.text_title);
mTextTitle.setText(mSensor.getStringType());
mTextValues = (TextView) mView.findViewById(R.id.text_values);
return mView;
}
#Override
public void onResume() {
super.onResume();
mSensorManager.registerListener(this, mSensor, SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
public void onPause() {
super.onPause();
mSensorManager.unregisterListener(this);
}
#Override
public void onSensorChanged(SensorEvent event) {
// If sensor is unreliable, then just return
if (event.accuracy == SensorManager.SENSOR_STATUS_UNRELIABLE)
{
return;
}
mTextValues.setText(
"x = " + Float.toString(event.values[0]) + "\n" +
"y = " + Float.toString(event.values[1]) + "\n" +
"z = " + Float.toString(event.values[2]) + "\n"
);
if(event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
detectShake(event);
}
else if(event.sensor.getType() == Sensor.TYPE_GYROSCOPE) {
detectRotation(event);
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
// References:
// - http://jasonmcreynolds.com/?p=388
// - http://code.tutsplus.com/tutorials/using-the-accelerometer-on-android--mobile-22125
private void detectShake(SensorEvent event) {
long now = System.currentTimeMillis();
if((now - mShakeTime) > SHAKE_WAIT_TIME_MS) {
mShakeTime = now;
float gX = event.values[0] / SensorManager.GRAVITY_EARTH;
float gY = event.values[1] / SensorManager.GRAVITY_EARTH;
float gZ = event.values[2] / SensorManager.GRAVITY_EARTH;
// gForce will be close to 1 when there is no movement
float gForce = FloatMath.sqrt(gX*gX + gY*gY + gZ*gZ);
// Change background color if gForce exceeds threshold;
// otherwise, reset the color
if(gForce > SHAKE_THRESHOLD) {
mView.setBackgroundColor(Color.rgb(0, 100, 0));
}
else {
mView.setBackgroundColor(Color.BLACK);
}
}
}
private void detectRotation(SensorEvent event) {
long now = System.currentTimeMillis();
if((now - mRotationTime) > ROTATION_WAIT_TIME_MS) {
mRotationTime = now;
// Change background color if rate of rotation around any
// axis and in any direction exceeds threshold;
// otherwise, reset the color
if(Math.abs(event.values[0]) > ROTATION_THRESHOLD ||
Math.abs(event.values[1]) > ROTATION_THRESHOLD ||
Math.abs(event.values[2]) > ROTATION_THRESHOLD) {
mView.setBackgroundColor(Color.rgb(0, 100, 0));
}
else {
mView.setBackgroundColor(Color.BLACK);
}
}
}
}
MainActivity.Java:
package com.drejkim.androidwearmotionsensors;
import android.app.Activity;
import android.os.Bundle;
import android.support.wearable.view.DotsPageIndicator;
import android.support.wearable.view.GridViewPager;
import android.support.wearable.view.WatchViewStub;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WatchViewStub stub = (WatchViewStub) findViewById(R.id.watch_view_stub);
stub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() {
#Override public void onLayoutInflated(WatchViewStub stub) {
final GridViewPager pager = (GridViewPager) findViewById(R.id.pager);
pager.setAdapter(new SensorFragmentPagerAdapter(getFragmentManager()));
DotsPageIndicator indicator = (DotsPageIndicator) findViewById(R.id.page_indicator);
indicator.setPager(pager);
}
});
}
}
SensorFragmentPagerAdapter.java:
package com.drejkim.androidwearmotionsensors;
import android.app.Fragment;
import android.app.FragmentManager;
import android.hardware.Sensor;
import android.support.wearable.view.FragmentGridPagerAdapter;
public class SensorFragmentPagerAdapter extends FragmentGridPagerAdapter {
private int[] sensorTypes = {
Sensor.TYPE_ACCELEROMETER,
Sensor.TYPE_GYROSCOPE
};
public SensorFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getFragment(int row, int column) {
return SensorFragment.newInstance(sensorTypes[column]);
}
#Override
public int getRowCount() {
return 1; // fix to 1 row
}
#Override
public int getColumnCount(int row) {
return sensorTypes.length;
}
}
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.drejkim.androidwearmotionsensors" >
<uses-feature android:name="android.hardware.type.watch" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#android:style/Theme.DeviceDefault" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Can someone help me out? I got this code from some source and I don't know how to fix it since the logcat is showing a long fatal exception script highlighted in red. Thank you, I'll really appreciate it if someone can help.

From the error message in LogCat you can read that mSensor is null when you try to execute
mTextTitle.setText(mSensor.getStringType());
This means that the your sensor manager is unable to find a default sensor that matches the requested type
mSensor = mSensorManager.getDefaultSensor(mSensorType);
as stated in the documentation.

Related

Closing dialog inside shouldOverrideUrlLoading() or ignoring in project, when is custom url open

I am trying to auth google user in WebView, I found a good solution for these days, it works fine for google login, but I cannot disable dialog in other urls like (, sms: , smsto:)
Example Situation: User click on telephone number in my app, it will open the phone dial, but when he returns back.. there is a empty dialog window with close button, i use it for google login with JS.
How can i close this dialog message inside the shouldOverrideUrlLoading()? Or is there any better solution to not open other links in the dialog? How can i improve my code to solve my problem? Thank you guys!
package com.example.app;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.net.http.SslCertificate;
import android.net.http.SslError;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.webkit.CookieManager;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.URLUtil;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import java.lang.reflect.Field;
import java.security.cert.X509Certificate;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public class MainActivity extends Activity {
private WebView mWebView;
private String userAgent;
private Context contextPop;
private WebView webViewPop;
private AlertDialog builder;
#Override
#SuppressLint("SetJavaScriptEnabled")
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
userAgent = System.getProperty("http.agent");
mWebView = findViewById(R.id.activity_main_webview);
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setDomStorageEnabled(true);
webSettings.setUseWideViewPort(true);
webSettings.setAppCacheEnabled(false);
webSettings.setAllowFileAccess(true);
webSettings.setAllowFileAccessFromFileURLs(true);
webSettings.setAllowUniversalAccessFromFileURLs(true);
webSettings.setUserAgentString(userAgent+ "com.example.app");
mWebView.clearCache(true);
// REMOTE RESOURCE
mWebView.loadUrl("https://example.eu/");
mWebView.setWebChromeClient(new CustomChromeClient());
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
webSettings.setSupportMultipleWindows(true);
contextPop = this.getApplicationContext();
// LOCAL RESOURCE
// mWebView.loadUrl("file:///android_asset/index.html");
}
#Override
public void onBackPressed() {
if(mWebView.canGoBack()) {
mWebView.goBack();
} else {
super.onBackPressed();
}
}
final Context myApp = this;
class CustomChromeClient extends WebChromeClient {
#Override
public boolean onCreateWindow(WebView view, boolean isDialog,
boolean isUserGesture, Message resultMsg) {
webViewPop = new WebView(contextPop);
webViewPop.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
String host = Uri.parse(url).getHost();
if (url.startsWith("tel:") || url.startsWith("sms:") || url.startsWith("smsto:") || url.startsWith("mms:") || url.startsWith("mmsto:"))
{
webViewPop.destroy();
Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse(url));
startActivity(intent);
return true;
}
//Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
//view.getContext().startActivity(intent);
return false;
}
});
// Enable Cookies
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
if (android.os.Build.VERSION.SDK_INT >= 21) {
cookieManager.setAcceptThirdPartyCookies(webViewPop, true);
cookieManager.setAcceptThirdPartyCookies(mWebView, true);
}
WebSettings popSettings = webViewPop.getSettings();
// WebView tweaks for popups
webViewPop.setVerticalScrollBarEnabled(false);
webViewPop.setHorizontalScrollBarEnabled(false);
popSettings.setJavaScriptEnabled(true);
popSettings.setSaveFormData(true);
popSettings.setEnableSmoothTransition(true);
// Set User Agent
popSettings.setUserAgentString(userAgent + "Your App Info/Version");
// to support content re-layout for redirects
popSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
// handle new popups
webViewPop.setWebChromeClient(new CustomChromeClient());
// set the WebView as the AlertDialog.Builder’s view
builder = new AlertDialog.Builder(MainActivity.this, AlertDialog.THEME_DEVICE_DEFAULT_LIGHT).create();
builder.setTitle("");
builder.setView(webViewPop);
builder.setButton("Close", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
webViewPop.destroy();
dialog.dismiss();
}
});
builder.show();
builder.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
transport.setWebView(webViewPop);
resultMsg.sendToTarget();
return true;
}
#Override
public void onCloseWindow(WebView window) {
//Toast.makeText(contextPop,"onCloseWindow called",Toast.LENGTH_SHORT).show();
try {
webViewPop.destroy();
} catch (Exception e) {
Log.d("Webview Destroy Error: ", e.getStackTrace().toString());
}
try {
builder.dismiss();
} catch (Exception e) {
Log.d("Builder Dismiss Error: ", e.getStackTrace().toString());
}
}
#Override
public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
new AlertDialog.Builder(myApp)
.setMessage(message)
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
result.confirm();
}
})
.setNegativeButton(android.R.string.cancel,
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
result.cancel();
}
})
.setCancelable(false)
.create()
.show();
return true;
}
#Override
public boolean onJsAlert(WebView view, final String url, String message,
JsResult result) {
new AlertDialog.Builder(myApp)
.setMessage(message)
.setNeutralButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
arg0.dismiss();
}
})
.setCancelable(false)
.show();
result.cancel();
return true;
}
}
}

Open Android app with Webview by pressing deeplink URL from notifications

Background:
* Full Stack developer training (recently finished studies).
* Am not very (putting it mildly) Java savvy.
for the past couple of days I've been trying to make the tapping on a OneSignal notification open the app according to the URL stored in the notification payload.
What did work was:
* If the app is showing on the screen and you press the notification it works fine and opens it accordingly.
It does ALMOST work in the way that if the app is in the background and you press the notification it either:
1. Launches the app but on the main page
OR
2. Doesn't launch the app but when you actively go back to the app it shows the correct content (according to the URL of the notification)
Following is the code:
Thank you!
package app.web.hodaya;
import com.onesignal.OSNotificationOpenResult;
import com.onesignal.OneSignal;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import org.json.JSONObject;
import static com.onesignal.OneSignal.sendTag;
import static com.onesignal.OneSignal.sendTags;
public class MainActivity extends AppCompatActivity {
private WebView webView;
#Override
protected void onCreate(Bundle savedInstanceState) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
WebView.setWebContentsDebuggingEnabled(true);
}
CalculateObject calcObject = new CalculateObject();
PassingStringThrough passString = new PassingStringThrough();
ExampleNotificationOpenedHandler notificationOpened = new ExampleNotificationOpenedHandler();
UpdateOneSignalSettingTags sendTag = new UpdateOneSignalSettingTags();
super.onCreate(savedInstanceState);
// OneSignal Initialization
OneSignal.startInit(this)
.inFocusDisplaying(OneSignal.OSInFocusDisplayOption.Notification)
.unsubscribeWhenNotificationsAreDisabled(true)
.setNotificationOpenedHandler(new ExampleNotificationOpenedHandler())
.init();
setContentView(R.layout.activity_main);
webView = findViewById(R.id.webView);
webView.setWebViewClient(new WebViewClient());
webView.loadUrl("https://hodaya-app.firebaseapp.com/");
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webView.getSettings().setDomStorageEnabled(true);
webView.addJavascriptInterface(passString, "ob1");
try {
this.getSupportActionBar().hide();
} catch (NullPointerException e) {
}
}
#Override
public void onBackPressed() {
if (webView.canGoBack()) {
webView.goBack();
} else {
super.onBackPressed();
}
}
class PassingStringThrough {
#JavascriptInterface
public void passString(
String m, String m1, String n, String n1, String e, String e1,
String name, String name1, String gender, String gender1) {
sendTag(m, m1);
sendTag(n, n1);
sendTag(e, e1);
sendTag(name, name1);
sendTag(gender, gender1);
/* alternatively*/
// tags.put(m, m1);
// tags.put(n, n1);
// tags.put(e, e1);
// OneSignal.sendTags(tags);
Log.d("settingsPassedCorrectly", "I just got executed!" + m + m1 + n + n1 + e + e1 + name + name1 + gender + gender1);
}
}
class ExampleNotificationOpenedHandler implements OneSignal.NotificationOpenedHandler {
#Override
public void notificationOpened(OSNotificationOpenResult result) {
Log.i("OSNotificationPayload", "result.notification.payload.toJSONObject().toString(): " + result.notification.payload.toJSONObject().toString());
JSONObject data = result.notification.payload.additionalData;
String customKey;
if (data != null) {
customKey = data.optString("tryli", null);
// if (customKey != null)
Log.i("DeepLinkToCustomkey", "customkey set with value: " + customKey);
WebView webView1;
// setContentView(R.layout.activity_main);
webView1 = findViewById(R.id.webView);
webView1.setWebViewClient(new WebViewClient());
webView1.loadUrl(customKey);
// WebView webView = null;
}

How to Load Interstitial Ads from Webview

I am new to android, recently I developed an application which runs on WebView means in my activity I placed a webview doing the gamin activity through html,js pages by loading those to webview.
Here my request is "How to load the Interstitial Ads from the webpage files(html,js) I googled most of the suggestions related to Ionic App but my app is AndroidStudio related.
so please help
Loading an ad from WebView isn't that straightforward but could be done. So let's take the following example:
class MainActivity extends AppCompatActivity {
protected InterstitialAd mInterstitialAd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// load interstitial ad
mInterstitialAd = new InterstitialAd(getContext());
mInterstitialAd.setAdUnitId("YOUR_AD_ID");
mInterstitialAd.loadAd(new AdRequest.Builder().build());
WebView browser = findViewById(R.id.webview);
browser.addJavascriptInterface(new InterceptorJavaScript(context), "Interceptor");
WebSettings webSettings = browser.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setDomStorageEnabled(true);
browser.setWebViewClient(new CapturingWebViewClient());
browser.loadUrl("http://website.com");
}
/**
* This class will handle all JS events from the UI back to
* Java code and will trigger the Interstitial ad
*/
private class InterceptorJavaScript {
Context webViewContext;
/**
* Instantiate the interface and set the context
*/
InterceptorJavaScript(Context webView) {
webViewContext = webView;
}
#JavascriptInterface
#SuppressWarnings("unused")
public void startInterstitial() {
// we need to run it on the main UI thread
Handler mHandler = new Handler(Looper.getMainLooper());
mHandler.post(new Runnable() {
#Override
public void run() {
if (MainActivity.mInterstitialAd.isLoaded()) {
MainActivity.mInterstitialAd.show();
}
// preload new ad
BrowserFragment.mInterstitialAd.loadAd(new AdRequest.Builder().build());
}
});
}
}
private class CapturingWebViewClient extends WebViewClient {
/**
* This method will inject the JavaScritp that will trigger
* your Java code and show the interstitial in the main UI thread
*/
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
view.loadUrl(
"javascript:Interceptor.startInterstitial();"
);
// Attach JS event to your button so you can call the JS function. I've used jQuery just for simplicity
view.loadUrl(
"javascript:$('#btn').on('click', function(){ Interceptor.startInterstitial(); });"
);
}
}
}
hello this is the code....
import android.os.Bundle; import android.view.Window; import android.view.WindowManager;
import android.support.v7.app.AppCompatActivity;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
public class a4 extends AppCompatActivity {
AdView mAdView;
InterstitialAd mInterstitialAd;
WebView WebViewWithCSS;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_a4);
WebViewWithCSS = (WebView)findViewById(R.id.webView);
WebSettings webSetting = WebViewWithCSS.getSettings();
webSetting.setJavaScriptEnabled(true);
WebViewWithCSS.setWebViewClient(new WebViewClient());
WebViewWithCSS.loadUrl("file:///android_asset/4.html");
mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder()
.build();
mAdView.loadAd(adRequest);
mInterstitialAd = new InterstitialAd(this);
// set the ad unit ID
mInterstitialAd.setAdUnitId(getString(R.string.interstitial_full_screen));
adRequest = new AdRequest.Builder()
.build();
// Load ads into Interstitial Ads
mInterstitialAd.loadAd(adRequest);
mInterstitialAd.setAdListener(new AdListener() {
public void onAdLoaded() {
showInterstitial();
}
});
}
#Override
public void onPause() {
if (mAdView != null) {
mAdView.pause();
}
super.onPause();
}
#Override
public void onResume() {
super.onResume();
if (mAdView != null) {
mAdView.resume();
}
}
#Override
public void onDestroy() {
if (mAdView != null) {
mAdView.destroy();
}
super.onDestroy();
}
private void showInterstitial() {
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
}
}
}

App runs fine on avd but not on actual device

I'm kind of new to android, actually this is my first app. The app is not completed through, i wanted to test the UI, it works fine on AVD, but when I copy the .apk file from bin folder to my phone, it installs fine, but wont work ends up with force close error. I have no idea what's the problem, I saw on other post about parsing the content in edittext, i took out the layout and ran it again still not working. again, I am new to this, please help me.
Mainactivity.java
package com.example.studentapp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.TextView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.ExpandableListView.OnGroupCollapseListener;
import android.widget.ExpandableListView.OnGroupExpandListener;
import com.example.studentapp.ExpandableListAdapter;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
DrawerLayout mDrawerLayout;
ExpandableListView mDrawerList;
ExpandableListAdapter listAdapter;
List<String> listDataHeader;
HashMap<String, List<String>> listDataChild;
private ActionBarDrawerToggle actionBarDrawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getfragment(125);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ExpandableListView) findViewById(R.id.left_drawer);
// preparing list data
prepareListData();
listAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild);
// setting list adapter
mDrawerList.setAdapter(listAdapter);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer icon to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description */
R.string.drawer_close /* "close drawer" description */
);
// 2.2 Set actionBarDrawerToggle as the DrawerListener
mDrawerLayout.setDrawerListener(actionBarDrawerToggle);
// 2.3 enable and show "up" arrow
getActionBar().setDisplayHomeAsUpEnabled(true);
// Listview Group click listener
mDrawerList.setOnGroupClickListener(new OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v,
int groupPosition, long id) {
Toast.makeText(getApplicationContext(),
"Group Clicked " + (groupPosition),
Toast.LENGTH_SHORT).show();
//return true for non collapsable items, and false for collapsable items.
if(groupPosition==1 || groupPosition==2)
{ // getfragment(groupPosition);
getActionBar().setTitle(listDataHeader.get(groupPosition));
return true;}
else
return false;
}
});
// Listview Group expanded listener
mDrawerList.setOnGroupExpandListener(new OnGroupExpandListener() {
#Override
public void onGroupExpand(int groupPosition) {
Toast.makeText(getApplicationContext(),
listDataHeader.get(groupPosition) + " Expanded",
Toast.LENGTH_SHORT).show();
}
});
// Listview Group collasped listener
mDrawerList.setOnGroupCollapseListener(new OnGroupCollapseListener() {
#Override
public void onGroupCollapse(int groupPosition) {
Toast.makeText(getApplicationContext(),
listDataHeader.get(groupPosition) + " Collapsed",
Toast.LENGTH_SHORT).show();
}
});
// Listview on child click listener
mDrawerList.setOnChildClickListener(new OnChildClickListener() {
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
// TODO Auto-generated method stub
Toast.makeText(
getApplicationContext(),
listDataHeader.get(groupPosition)
+ " : "
+ listDataChild.get(
listDataHeader.get(groupPosition)).get(
childPosition), Toast.LENGTH_SHORT)
.show();
getActionBar().setTitle(listDataChild.get(
listDataHeader.get(groupPosition)).get(
childPosition));
return false;
}
});
}
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
actionBarDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
actionBarDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// call ActionBarDrawerToggle.onOptionsItemSelected(), if it returns true
// then it has handled the app icon touch event
if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private void prepareListData() {
listDataHeader = new ArrayList<String>();
listDataChild = new HashMap<String, List<String>>();
// Adding header data
listDataHeader.add("Center Details");
// Adding child data
List<String> CentDet = new ArrayList<String>();
CentDet.add("Study Center");
CentDet.add("Information Center");
CentDet.add("Overseas Center");
listDataHeader.add("Login");
listDataHeader.add("PCP Schedule");
listDataHeader.add("Course");
List<String> courseS = new ArrayList<String>();
courseS.add("Study Materials");
courseS.add("Syllabus");
listDataHeader.add("Exam");
List<String> Exams = new ArrayList<String>();
Exams.add("Hall Ticket");
Exams.add("Exam Venue");
Exams.add("Exam Schedule");
Exams.add("Practical Schedule");
Exams.add("Model Question Papers");
listDataHeader.add("Results");
List<String> Resultss= new ArrayList<String>();
Resultss.add("Regular Stream");
Resultss.add("Overseas");
listDataChild.put(listDataHeader.get(0), CentDet); // Header, Child data
listDataChild.put(listDataHeader.get(1), null);
listDataChild.put(listDataHeader.get(2), null);
listDataChild.put(listDataHeader.get(3), courseS);
listDataChild.put(listDataHeader.get(4), Exams);
listDataChild.put(listDataHeader.get(5), Resultss);
}
void getfragment(int x)
{
android.app.FragmentManager fragmentManager1 = getFragmentManager();
android.app.FragmentTransaction fragmentTransaction1 = fragmentManager1.beginTransaction();
fragmenttwo lm_fragment = new fragmenttwo();
switch (x)
{
// case 1:
// lm_fragment.fragmenttwoo(1);
//
//break;
case 2:
lm_fragment.fragmenttwoo(2);
break;
case 3:
lm_fragment.fragmenttwoo(3);
break;
case 125:
lm_fragment.fragmenttwoo(125);
break;
}
fragmentTransaction1.replace(R.id.content_frame, lm_fragment);
fragmentTransaction1.commit();
}
}
fragmenttwo.java
package com.example.studentapp;
import android.annotation.TargetApi;
import android.app.Fragment;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class fragmenttwo extends Fragment{
public int x;
public fragmenttwo(){}
public void fragmenttwoo(int n)
{
switch(n)
{
case 125:
x = com.example.studentapp.R.layout.sample;
break;
// case 1:
// x = com.example.studentapp.R.layout.login;
// break;
case 2:
x = com.example.studentapp.R.layout.pcpschedule;
break;
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
/** * Inflate the layout for this fragment */
// switch(x)
// {
// int idno= r.layout.layoutu want for each case
//put the idno on below as parameter instead of r.layout.sample
//}
return inflater.inflate( x, container, false);
}
}
ExpandableListAdpater.java
package com.example.studentapp;
import java.util.HashMap;
import java.util.List;
import android.content.Context;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.TextView;
public class ExpandableListAdapter extends BaseExpandableListAdapter {
private Context _context;
private List<String> _listDataHeader; // header titles
// child data in format of header title, child title
private HashMap<String, List<String>> _listDataChild;
public ExpandableListAdapter(Context context, List<String> listDataHeader,
HashMap<String, List<String>> listChildData) {
this._context = context;
this._listDataHeader = listDataHeader;
this._listDataChild = listChildData;
}
#Override
public Object getChild(int groupPosition, int childPosititon) {
return this._listDataChild.get(this._listDataHeader.get(groupPosition))
.get(childPosititon);
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public View getChildView(int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
final String childText = (String) getChild(groupPosition, childPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_item, null);
}
TextView txtListChild = (TextView) convertView
.findViewById(R.id.lblListItem);
txtListChild.setText(childText);
return convertView;
}
#Override
public int getChildrenCount(int groupPosition) {
return this._listDataChild.get(this._listDataHeader.get(groupPosition))
.size();
}
#Override
public Object getGroup(int groupPosition) {
return this._listDataHeader.get(groupPosition);
}
#Override
public int getGroupCount() {
return this._listDataHeader.size();
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
String headerTitle = (String) getGroup(groupPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_group, null);
}
TextView lblListHeader = (TextView) convertView
.findViewById(R.id.lblListHeader);
lblListHeader.setTypeface(null, Typeface.BOLD);
lblListHeader.setText(headerTitle);
return convertView;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
any help would be appreciated.
As suggested i used adb and here is the logcat log, it says virtual method getfragment cannot be resolved...
06-03 21:18:03.789: W/dalvikvm(11126): VFY: unable to resolve virtual method 8281: Lcom/example/studentapp/MainActivity;.getFragmentManager ()Landroid/app/FragmentManager;
06-03 21:18:03.789: D/dalvikvm(11126): VFY: replacing opcode 0x6e at 0x0000
06-03 21:18:03.789: D/dalvikvm(11126): VFY: dead code 0x0003-0029 in Lcom/example/studentapp/MainActivity;.getfragment (I)V
06-03 21:18:03.812: W/dalvikvm(11126): VFY: unable to resolve virtual method 8279: Lcom/example/studentapp/MainActivity;.getActionBar ()Landroid/app/ActionBar;
06-03 21:18:03.812: D/dalvikvm(11126): VFY: replacing opcode 0x6e at 0x005b
06-03 21:18:03.812: D/dalvikvm(11126): VFY: dead code 0x005e-008b in Lcom/example/studentapp/MainActivity;.onCreate (Landroid/os/Bundle;)V
06-03 21:18:03.820: I/ApplicationPackageManager(11126): cscCountry is not German : INS
06-03 21:18:03.976: D/AndroidRuntime(11126): Shutting down VM
06-03 21:18:03.976: W/dalvikvm(11126): threadid=1: thread exiting with uncaught exception (group=0x40018578)
06-03 21:18:03.976: E/AndroidRuntime(11126): FATAL EXCEPTION: main
06-03 21:18:03.976: E/AndroidRuntime(11126): java.lang.NoSuchMethodError: com.example.studentapp.MainActivity.getFragmentManager
06-03 21:18:03.976: E/AndroidRuntime(11126): at com.example.studentapp.MainActivity.getfragment(MainActivity.java:223)
06-03 21:18:03.976: E/AndroidRuntime(11126): at com.example.studentapp.MainActivity.onCreate(MainActivity.java:42)
06-03 21:18:03.976: E/AndroidRuntime(11126): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
06-03 21:18:03.976: E/AndroidRuntime(11126): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1615)
06-03 21:18:03.976: E/AndroidRuntime(11126): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1667)
06-03 21:18:03.976: E/AndroidRuntime(11126): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
06-03 21:18:03.976: E/AndroidRuntime(11126): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:935)
06-03 21:18:03.976: E/AndroidRuntime(11126): at android.os.Handler.dispatchMessage(Handler.java:99)
06-03 21:18:03.976: E/AndroidRuntime(11126): at android.os.Looper.loop(Looper.java:130)
06-03 21:18:03.976: E/AndroidRuntime(11126): at android.app.ActivityThread.main(ActivityThread.java:3687)
06-03 21:18:03.976: E/AndroidRuntime(11126): at java.lang.reflect.Method.invokeNative(Native Method)
06-03 21:18:03.976: E/AndroidRuntime(11126): at java.lang.reflect.Method.invoke(Method.java:507)
06-03 21:18:03.976: E/AndroidRuntime(11126): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
06-03 21:18:03.976: E/AndroidRuntime(11126): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
06-03 21:18:03.976: E/AndroidRuntime(11126): at dalvik.system.NativeStart.main(Native Method)
Read the logcat: noSuchMethodError on line 223. Double click that line in the logcat and you will end up on line 223 of your MainActivity. Tell us the code.
CscCountry is not German?
Or you are running on a device that does not know getActionBar().

Can I show progress dialog and error message while parsing XML using JavaScript?

I am developing android web application for a blog like website.
For this I am showing HTML page contenting list of categories which when clicked shows articles related to that category.
I am fetching this articles from website's RSS feeds which is in XML format and by using JavaScript I am parsing it to display on HTML page.
This process of parsing XML takes lot of time to load a page.During this period I am getting blank screen.I have implemented progress dialog which works fine when page is loading for the first time but when XML is getting parsed by JavaScript it does not appear.
Here is how I implemented Process dialog.
Activity.java:
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.main);
getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
Window.PROGRESS_VISIBILITY_ON);
webview = (WebView) findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true);
webview.setBackgroundColor(0);
final ProgressDialog progressDialog = new ProgressDialog(activity);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMessage("Loading...please wait");
progressDialog.setCancelable(true);
webview.setWebViewClient(new WebViewClient()
{
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
view.loadUrl(url);
return true;
}
});
webview.loadUrl("file:///android_asset/HomePage.html");
// WebChromeClient give progress etc info
webview.setWebChromeClient(new WebChromeClient()
{
public void onProgressChanged(WebView view, int progress)
{
progressDialog.show();
progressDialog.setProgress(0);
activity.setProgress(progress * 1000);
progressDialog.incrementProgressBy(progress);
if (progress == 100 && progressDialog.isShowing())
progressDialog.dismiss();
}
});
}
How can I show progress dialog while XML is being parsed by JavaScript?
Also I want to show an error message if no internet connectivity available for same thing is their any way to do so?
I have used call function as "tel:phone number" which was working but after I added de
public boolean shouldOverrideUrlLoading it is not working? what's i done wrong?
for your questions You can use following code in your activity.java file
package com.package name;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;
import android.widget.Toast;
public class Myactivity extends Activity {
TextView myLabel;
WebView wv;
final Activity activity=this;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.main);
getWindow().setFeatureInt(Window.FEATURE_PROGRESS,Window.PROGRESS_VISIBILITY_ON);
wv=(WebView)findViewById(R.id.webview);
wv.getSettings().setJavaScriptEnabled(true);
wv.setBackgroundColor(0);
final ProgressDialog progressDialog = new ProgressDialog(activity);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMessage("Loading...please wait");
progressDialog.setCancelable(true);
wv.setWebViewClient(new WebViewClient()
{
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
if (url.startsWith("tel:")) {
Intent intent = new Intent(Intent.ACTION_DIAL,
Uri.parse(url));
startActivity(intent);
return true;
}else{
view.loadUrl(url);
return true;
}
}
});
wv.loadUrl("file:///android_asset/page.html");
// WebChromeClient give progress etc info
wv.setWebChromeClient(new WebChromeClient()
{
public void onProgressChanged(WebView view, int progress)
{
progressDialog.show();
progressDialog.setProgress(0);
activity.setProgress(progress * 1000);
progressDialog.incrementProgressBy(progress);
if (progress == 100 && progressDialog.isShowing())
progressDialog.dismiss();
}
});
if (AppStatus.getInstance(this).isOnline(this)) {
Toast t = Toast.makeText(this,"Welcome !!!!",8000);
t.show();
} else {
AlertDialog alertDialog = new AlertDialog.Builder(
CafeNashikActivity.this).create();
// Setting Dialog Title
alertDialog.setTitle("No Internet");
// Setting Dialog Message
alertDialog.setMessage("Internet Connection not available!");
// Setting Icon to Dialog
//alertDialog.setIcon(R.drawable.tick);
// Setting OK Button
alertDialog.setButton("Exit", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
MyActivity.this.finish();
}
});
// Showing Alert Message
alertDialog.show();
}
}
}
Hope this will help you.

Categories

Resources