App working on Nougat+ versions but crashing on Marshmallow and Lollipop - java

This is the error report whenever I launch the app it crashes and says
Unfortunately, {app-name} has stopped
java.lang.RuntimeException:
at android.app.ActivityThread.performLaunchActivity (ActivityThread.java:2339)
at android.app.ActivityThread.handleLaunchActivity (ActivityThread.java:2413)
at android.app.ActivityThread.access$800 (ActivityThread.java:155)
at android.app.ActivityThread$H.handleMessage (ActivityThread.java:1317)
at android.os.Handler.dispatchMessage (Handler.java:102)
at android.os.Looper.loop (Looper.java:135)
at android.app.ActivityThread.main (ActivityThread.java:5343)
at java.lang.reflect.Method.invoke (Native Method)
at java.lang.reflect.Method.invoke (Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:905)
at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:700)
Caused by: android.view.InflateException:
at android.view.LayoutInflater.createViewFromTag (LayoutInflater.java:763)
at android.view.LayoutInflater.rInflate (LayoutInflater.java:806)
at android.view.LayoutInflater.inflate (LayoutInflater.java:504)
at android.view.LayoutInflater.inflate (LayoutInflater.java:414)
at android.view.LayoutInflater.inflate (LayoutInflater.java:365)
at android.support.v7.app.AppCompatDelegateImplV9.setContentView (AppCompatDelegateImplV9.java:287)
at android.support.v7.app.AppCompatActivity.setContentView (AppCompatActivity.java:139)
at com.khokhar.yousaf.cipher.Splash.onCreate (Splash.java:15)
at android.app.Activity.performCreate (Activity.java:6010)
at android.app.Instrumentation.callActivityOnCreate (Instrumentation.java:1129)
at android.app.ActivityThread.performLaunchActivity (ActivityThread.java:2292)
Caused by: android.content.res.Resources$NotFoundException:
at android.content.res.Resources.loadDrawableForCookie (Resources.java:2444)
at android.content.res.Resources.loadDrawable (Resources.java:2384)
at android.content.res.TypedArray.getDrawable (TypedArray.java:749)
at android.view.View.<init> (View.java:3742)
at android.widget.ImageView.<init> (ImageView.java:149)
at android.widget.ImageView.<init> (ImageView.java:145)
at android.support.v7.widget.AppCompatImageView.<init> (AppCompatImageView.java:71)
at android.support.v7.widget.AppCompatImageView.<init> (AppCompatImageView.java:67)
at android.support.v7.app.AppCompatViewInflater.createImageView (AppCompatViewInflater.java:181)
at android.support.v7.app.AppCompatViewInflater.createView (AppCompatViewInflater.java:105)
at android.support.v7.app.AppCompatDelegateImplV9.createView (AppCompatDelegateImplV9.java:1035)
at android.support.v7.app.AppCompatDelegateImplV9.onCreateView (AppCompatDelegateImplV9.java:1092)
at android.view.LayoutInflater.createViewFromTag (LayoutInflater.java:725)
This is my Splash Screen coding
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Window;
public class Splash extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_splash);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
//thread for splash screen running
Thread logoTimer = new Thread() {
public void run() {
try {
sleep(2500);
} catch (InterruptedException e) {
Log.d("Exception", "Exception" + e);
} finally {
startActivity(new Intent(Splash.this, MainActivity.class));
}
finish();
}
};
logoTimer.start();
}
}
And this XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/splashScreen"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#color/colorPrimary"
android:orientation="vertical"
tools:context="com.khokhar.yousaf.cipher.Splash">
<ImageView
android:id="#+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:background="#drawable/ic_launcher_foreground"
android:contentDescription="#string/app_name"
android:scaleType="fitXY"
android:src="#drawable/mediumload" />
</RelativeLayout>
The drawable image I used is 600x1024 PNG
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.khokhar.yousaf.cipher">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:fullBackupContent="true"
android:hardwareAccelerated="true"
android:icon="#drawable/cee"
android:label="#string/app_name"
android:roundIcon="#drawable/cee"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity"
android:theme="#style/AppTheme">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<!-- Accepts URIs that begin with "java-lang-programming://android-app-google-plus-demo"-->
<data
android:host="cipherengineers"
android:scheme="android-app-cipher-engineers" />
</intent-filter>
</activity>
<activity android:name=".Splash"
android:theme="#style/AppTheme">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>
My MainActivity is basically webview
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
ProgressBar progressBar;
WebView webView;
String url="https://website/";
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar = (ProgressBar) findViewById(R.id.progressBar1);
webView = (WebView) findViewById(R.id.webView);
textView = (TextView) findViewById(R.id.textView1212);
webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
progressBar.setProgress(progress);
textView.setText(progress + "");
}
#Override
public boolean onCreateWindow(WebView view, boolean isDialog,
boolean isUserGesture, Message resultMsg) {
WebView newWebView = new WebView(MainActivity.this);
newWebView.getSettings().setJavaScriptEnabled(true);
newWebView.getSettings().setSupportZoom(true);
newWebView.getSettings().setBuiltInZoomControls(true);
newWebView.getSettings().setPluginState(WebSettings.PluginState.ON);
newWebView.getSettings().setSupportMultipleWindows(true);
view.addView(newWebView);
WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
transport.setWebView(newWebView);
resultMsg.sendToTarget();
newWebView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
return true;
}
});
webView.setWebViewClient(new MyWebViewClient());
WebSettings browserSetting = webView.getSettings();
webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
browserSetting.setJavaScriptCanOpenWindowsAutomatically(true);
browserSetting.setJavaScriptEnabled(true);
browserSetting.setLoadWithOverviewMode(true);
browserSetting.setSupportMultipleWindows(true);
browserSetting.setDatabaseEnabled(true);
browserSetting.setAppCacheEnabled(true);
browserSetting.setDomStorageEnabled(true);
browserSetting.setDomStorageEnabled(true);
browserSetting.setGeolocationEnabled(true);
browserSetting.setSaveFormData(false);
browserSetting.setUseWideViewPort(true);
browserSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
browserSetting.setCacheMode(WebSettings.LOAD_NO_CACHE);
browserSetting.setDomStorageEnabled(true);
if (android.os.Build.VERSION.SDK_INT >= 21) {
CookieManager.getInstance().setAcceptThirdPartyCookies(webView, true);
}else {
CookieManager.getInstance().setAcceptCookie(true);
}
webView.loadUrl(url);
}
private class MyWebViewClient extends WebViewClient {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
progressBar.setVisibility(View.INVISIBLE);
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
progressBar.setVisibility(View.GONE);
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Check if the key event was the Back button and if there's history
if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
webView.goBack();
return true;
}
// If it wasn't the Back key or there's no web page history, bubble up to the default
// system behavior (probably exit the activity)
return super.onKeyDown(keyCode, event);
}
public void onBackPressed() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
MainActivity.this);
// set title
alertDialogBuilder.setTitle("Exit");
// set dialog message
alertDialogBuilder
.setMessage("Are You Sure?")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, close
// current activity
MainActivity.this.finish();
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
alertDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.GRAY));
}
}
I removed background from Splash Screen XML and nothing worked
MainActivity XML
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools"
android:background="#drawable/loading_screen"
android:orientation="vertical"
tools:context="com.khokhar.yousaf.cipher.MainActivity">
<ProgressBar
android:id="#+id/progressBar1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_gravity="center_vertical|center_horizontal"
android:layout_marginTop="218dp"
android:progressTint="?android:attr/fastScrollTextColor"
android:visibility="invisible" />
<TextView
android:id="#+id/textView1212"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="23dp"
android:textColor="#android:color/holo_red_dark"
android:textSize="13sp"
android:textStyle="bold|italic" />
<WebView
android:id="#+id/webView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:animationCache="true"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="41dp" />
</RelativeLayout>
I can't figure it out.

Removing the background from ImageView
The reason is lower versions are not able to find ic_launcher_foreground in the drawable directory which actually exists in drawable-v24.

Remove the background image and write your ImageView like this
<ImageView
android:id="#+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:contentDescription="#string/app_name"
android:scaleType="fitXY"
android:src="#drawable/mediumload" />

you cant start a new Activity on Background Thread.. since you run new Thread and inside you start a new Activity it will crash..
2 solutions : declare Handler outside the Thread
Handler handler = new Handler();
inside the thread run
handler.post(new Runnable() { public void run() { startActivity(..) } });
or use function :
RunOnUiThread(new Runnable() { public void run() { startActivity(...) } );

Related

My webview doesn't start after creating progress bar

I created my new webapp. It worked well. But I wanted to add a progress bar. The progress bar works, but my webview doesn't show anynore. I don't understand why. Can someone may help, please?
I tried all the codes I found online. They are ok for the others, but not for me.
Here my manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:fullBackupOnly="true"
android:icon="#drawable/donorionepng"
android:label="PCDO GENOVA"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.PCDOPCDOGENOVA"
android:usesCleartextTraffic="true">
<activity
android:name=".MainActivity" android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
android:exported="true"/>
<activity
android:name=".SplashActivity" android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
android:exported="true" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Here my MainActivity.java
package it.donorionegenova.pcdopcdogenova;
import androidx.appcompat.app.AppCompatActivity;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import android.content.pm.ActivityInfo;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.ClientCertRequest;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.core.content.res.ResourcesCompat;
import com.onesignal.OneSignal;
import android.annotation.SuppressLint;
public class MainActivity extends AppCompatActivity {
private static final String ONESIGNAL_APP_ID = "........ de2";
private SwipeRefreshLayout swipeRefreshLayout;
private WebView webView;
ProgressBar progressBar;
#SuppressLint("SetJavaScriptEnabled")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ProgressBar progressBar = findViewById(R.id.prBar);
webView = findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("https://www.donorione-genova.it/home-app");
webView.setWebViewClient(new WebViewClient());
webView.setWebChromeClient(new WebChromeClient() {
#Override
public void onProgressChanged(WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
progressBar.setProgress(newProgress);
if (newProgress == 100) {
webView.setVisibility(View.VISIBLE);
progressBar.setVisibility(View.GONE);
} else {
webView.setVisibility(View.GONE);
progressBar.setVisibility(View.VISIBLE);
}
}
});
TextView textView = findViewById(R.id.textview);
textView.postDelayed(() -> textView.setText("loading..."), 500); // delay of 2 seconds before setting a text to textView
textView.postDelayed(() -> textView.setVisibility(View.GONE), 2000);
// Enable verbose OneSignal logging to debug issues if needed.
OneSignal.setLogLevel(OneSignal.LOG_LEVEL.VERBOSE, OneSignal.LOG_LEVEL.NONE);
// OneSignal Initialization
OneSignal.initWithContext(this);
OneSignal.setAppId(ONESIGNAL_APP_ID);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
WebSettings settings = webView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setDisplayZoomControls(false);
settings.supportZoom();
settings.setSupportZoom(true);
settings.setBuiltInZoomControls(true);
// settings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
settings.setLoadWithOverviewMode(true);
settings.setUseWideViewPort(true);
settings.setDomStorageEnabled(true);
settings.setLoadsImagesAutomatically(true);
webView.clearHistory();
webView.clearCache(true);
registerForContextMenu(webView);
webView = findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("https://www.donorione-genova.it/home-app");
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView View, WebResourceRequest request) {
final Uri uri = request.getUrl();
if (uri.toString().startsWith("mailto:")) {
//Handle mail Urls
startActivity(new Intent(Intent.ACTION_SENDTO, uri));
} else if (uri.toString().startsWith("tel:")) {
//Handle telephony Urls
startActivity(new Intent(Intent.ACTION_DIAL, uri));
} else {
//Handle Web Urls
webView.loadUrl(uri.toString());
}
return true;
}
});
//per fare il refresh
swipeRefreshLayout = findViewById(R.id.swipe);
swipeRefreshLayout.setOnRefreshListener(() -> {
swipeRefreshLayout.setRefreshing(true);
new Handler().postDelayed(() -> {
swipeRefreshLayout.setRefreshing(false);
webView.reload();
}, 2000);
});
swipeRefreshLayout.setColorSchemeColors(
ResourcesCompat.getColor(
getResources(), R.color.holo_blue_dark, null),
ResourcesCompat.getColor(
getResources(), R.color.holo_orange_dark, null),
ResourcesCompat.getColor(
getResources(), R.color.holo_green_dark, null),
ResourcesCompat.getColor(
getResources(), R.color.holo_red_dark, null));
}
public void gohome(View v)
{
webView.loadUrl("https://donorione-genova.it/home-app");
}
public void clickexit(View v)
{
moveTaskToBack(true);
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
}
public void onBackPressed() {
if(webView.canGoBack()) {
webView.goBack();
}
else
super.onBackPressed();
}
}
And here my ActivityMain:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
android:id="#+id/swipe"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ProgressBar
android:id="#+id/prBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="?android:attr/progressBarStyleHorizontal" />
<WebView
android:id="#+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:visibility="visible" >
</WebView>
</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
<Button
android:id="#+id/button"
android:layout_width="185dp"
android:layout_height="wrap_content"
android:background="#0063B1"
android:onClick="clickexit"
android:text="#string/Chiudi"
android:textColor="#color/white"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_weight="1"
app:layout_constraintStart_toEndOf="#+id/button2">
</Button>
<Button
android:id="#+id/button2"
android:layout_width="185dp"
android:layout_height="wrap_content"
android:background="#0063B1"
android:onClick="gohome"
android:text="#string/Home"
android:textColor="#color/white"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#+id/button"
app:layout_constraintHorizontal_weight="1"
app:layout_constraintStart_toStartOf="parent">
</Button>
<TextView
android:id="#+id/textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textColor="#0000ff"
android:textSize="40sp"
android:textAlignment="center"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent">
</TextView>
</androidx.constraintlayout.widget.ConstraintLayout>
I didn't use SwipeRefreshLayout, but the documentation says you need to include another layout inside it. As you added a second view inside, you are now using it as a default ViewGroup, which is probably not working as expected. Put a LinearLayout or whatever inside the SwipeRefreshLayout and your components inside your LinearLayout.

Access element from external XML file in Android

I am developing an Android Application.I have create an another XML file for layout:-
Chatfile.XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/suitableblack"
android:orientation="vertical">
<Button
android:id="#+id/signout"
android:layout_width="422dp"
android:layout_height="64dp"
android:text="Button" />
<ListView
android:id="#+id/Msgdisplay"
android:layout_width="374dp"
android:layout_height="593dp"
android:layout_below="#id/signout"
android:layout_marginLeft="20dp"
android:forceDarkAllowed="false" />
<LinearLayout
android:layout_width="390dp"
android:layout_height="83dp"
android:layout_below="#id/Msgdisplay"
android:layout_marginLeft="20dp"
android:orientation="horizontal">
<EditText
android:id="#+id/Msginput"
android:layout_width="482dp"
android:layout_height="67dp"
android:layout_weight="1"
android:ems="10"
android:inputType="textPersonName"
android:text="Name" />
<Button
android:id="#+id/Sendbtn"
android:layout_width="match_parent"
android:layout_height="68dp"
android:layout_weight="1"
android:text="Button" />
</LinearLayout>
So I want to access the button with ID-Sendbtn in my MainActivity.java file and the code for that part is here:-
Button sendbtn=findViewById(R.id.Sendbtn);
sendbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String msg=message.getText().toString();
if(msg.length()==0)
{
Toast.makeText(getApplicationContext(),"Blank message detected",Toast.LENGTH_SHORT);
}
else
{
FirebaseDatabase.getInstance().getReference().push().setValue(new chatcolumns(msg,FirebaseAuth.getInstance().getCurrentUser().getDisplayName()));
}
}
});
But whenever I run this code it gives me following error:-
Process: com.example.anochatzone, PID: 18398
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.anochatzone/com.example.anochatzone.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
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)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.example.anochatzone.MainActivity.onCreate(MainActivity.java:87)
at android.app.Activity.performCreate(Activity.java:6679)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
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) 
My main question is how can I access the button from chatfile.xml in my MainActivity.java
Update
MainActivity.java
package com.example.anochatzone;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Layout;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.*;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.FirebaseDatabase;
import java.util.Objects;
public class MainActivity extends AppCompatActivity {
private FirebaseAuth authenticate;
private String email_str="";
private String password_str="";
private EditText email,password,message;
private Button loginbtn,resetbtn,sendbtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE); //will hide the title
Objects.requireNonNull(getSupportActionBar()).hide(); // hide the title bar
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN); //enable full screen
setContentView(R.layout.activity_main);
email=findViewById(R.id.EmailInput);
password=findViewById(R.id.Passwordinput);
message=findViewById(R.id.Msginput);
loginbtn=findViewById(R.id.Loginbtn);
resetbtn= findViewById(R.id.ResetBtn);
sendbtn=findViewById(R.id.Sendbtn);
authenticate=FirebaseAuth.getInstance();
loginbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),"Please wait while we are processing your request........",Toast.LENGTH_SHORT).show();
email_str=email.getText().toString();
password_str=password.getText().toString();
if(email_str.length()==0||password_str.length()==0)
{
Toast.makeText(getBaseContext(),"Please check email and password",Toast.LENGTH_LONG).show();
}
else
{
authenticate.signInWithEmailAndPassword(email_str,password_str).addOnCompleteListener(MainActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
Log.d("User display name" , FirebaseAuth . getInstance() . getCurrentUser().getDisplayName());
Toast.makeText(getApplicationContext(),"Welcome "+email_str+" you have sucessfully logged in",Toast.LENGTH_LONG).show();
setContentView(R.layout.chatfile);
}
else
{
Toast.makeText(getApplicationContext(),"Failed to sign in .Please check internet connection or try again later",Toast.LENGTH_SHORT).show();
}
}
});
}
}
});
sendbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String msg=message.getText().toString();
if(msg.length()==0)
{
Toast.makeText(getApplicationContext(),"Blank message detected",Toast.LENGTH_SHORT);
}
else
{
FirebaseDatabase.getInstance().getReference().push().setValue(new chatcolumns(msg,FirebaseAuth.getInstance().getCurrentUser().getDisplayName())) ;
}
}
});
}
}
According to your purpose, when you launch or start the app, login page will appear. If login success, the chat page will appear.
So, you need to separate your activity to two activity such as LoginActivity as a launcher activity and ChatActivity(MainActivity) as follow.
For login page, may be one activity_login.xml and LoginActivity.java
In activity_login.xml
<!-- You need one button for login action. -->
<Button
android:id="#+id/btnLogin"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Login"
/>
In LoginActivity.java
#Override protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// This line is important to access your resource id
setContentView(R.layout.activity_login);
findViewById(R.id.btnLogin).setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
// isLoginSuccess is an example condition for you
if (isLoginSuccess) {
// Navigate to mainpage
startActivity(new Intent(LoginActivity.this, MainActivity.class));
// Terminate the login activity for one time show.
finish();
} else {
// TODO: Try again implementations
}
}
});
}
For main page, like above, you need one activity_main.xml and one MainActivity.java
In Chatfile.xml
// other codes....
<Button
android:id="#+id/Sendbtn"
android:layout_width="match_parent"
android:layout_height="68dp"
android:layout_weight="1"
android:text="Button" />
// other codes....
In MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// This line is important for your 'chatfile.xml'
setContentView(R.layout.Chatfile);
// You can access id `SendBtn` right now.
findViewById(R.id.SendBtn).setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
// TODO: implement something here.
}
});
}
In AndroidManifest.xml, you need to change launcher activity as LoginActivity.
<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/AppTheme">
<activity android:name=".LoginActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".MainActivity"/>
</application>
According to my solution, you don't have to consider that what the ui element should be hidden when login success or fail.
If anything wrong in my answer, please let me free to know.
Put below code in your activity_main.xml
<include
layout="#layout/chatfile"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Now you can access the button in Your MainActivity.

glUtilsParamSize error when opening new activity

I have one problem. When i run my app, i want to open new activity with button. That works with one activity,but the other activity(two buttons in main menu,one works other not) just closes the app. Here is the code of that activity,and the logcat of errors. Logcat says there is problem with glutilsparamsize
My problem is that it doesn't want to open activity pronadi. My buttons Opis and Izlaz work and they open activity opis and izlaz button exits,but button pronadi says "com.example.shromid. stopped" and closes the app. I want to open activity pronadi.
LOGCAT errors
01-31 09:49:47.351 4576-4596/com.example.shromid E/eglCodecCommon:
glUtilsParamSize: unknow param 0x00008cdf
01-31 09:49:47.352 4576-4596/com.example.shromid E/eglCodecCommon:
glUtilsParamSize: unknow param 0x00008cdf
01-31 09:49:47.360 4576-4596/com.example.shromid E/eglCodecCommon:
glUtilsParamSize: unknow param 0x00008824
01-31 09:49:47.360 4576-4596/com.example.shromid E/eglCodecCommon:
glUtilsParamSize: unknow param 0x00008824
Activity that i want to open
package com.example.shromid;
import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class Pronadi extends Activity {
Spinner kboja;
Spinner ktekstura;
Spinner koblik;
ArrayAdapter<String> adapter;
ArrayAdapter<String> adapter1;
ArrayAdapter<String> adapter2;
DatabaseHelper db;
List<String>gljive=new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pronadi);
kboja = (Spinner) findViewById(R.id.kboja);
ktekstura = (Spinner) findViewById(R.id.ktekstura);
koblik = (Spinner) findViewById(R.id.koblik);
db = new DatabaseHelper(Pronadi.this);
prepareData();
prepareData1();
prepareData2();
kboja.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(), "" + parent.getItemAtPosition(position).toString(), Toast.LENGTH_SHORT);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
koblik.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(),""+parent.getItemAtPosition(position).toString(),Toast.LENGTH_SHORT);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
ktekstura.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(),""+parent.getItemAtPosition(position).toString(),Toast.LENGTH_SHORT);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
public void prepareData() {
gljive=db.getKlobuk_Boja();
adapter=new ArrayAdapter<String>(Pronadi.this,android.R.layout.simple_spinner_dropdown_item,android.R.id.text1,gljive);
kboja.setAdapter(adapter);
}
public void prepareData1() {
gljive=db.getKlobuk_Oblik();
adapter1=new ArrayAdapter<String>(Pronadi.this,android.R.layout.simple_spinner_dropdown_item,android.R.id.text1,gljive);
koblik.setAdapter(adapter1);
}
public void prepareData2(){
gljive=db.getKlobuk_Tekstura();
adapter2=new ArrayAdapter<String>(Pronadi.this,android.R.layout.simple_spinner_dropdown_item,android.R.id.text1,gljive);
ktekstura.setAdapter(adapter2);
}
}
Activity with buttons to open activity
package com.example.shromid;
import android.content.Intent;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
izlaz();
otvoriopis();
otvoripronadi();
}
public Button btnopis;
public void otvoriopis(){
btnopis=(Button)findViewById(R.id.btnopis);
btnopis.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
Intent otvoriopis= new Intent(MainActivity.this,Opis.class);
startActivity(otvoriopis);
}
});
}
public Button btnpronadi;
public void otvoripronadi(){
btnpronadi=(Button)findViewById(R.id.btnpronadi);
btnpronadi.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
Intent otvoripronadi= new Intent(MainActivity.this,Pronadi.class);
startActivity(otvoripronadi);
}
});
}
public Button btnizlaz;
public void izlaz(){
btnizlaz=(Button)findViewById(R.id.btnizlaz);
btnizlaz.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
finish();
System.exit(0);
}
});
}
}
android manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.shromid">
<application
android:allowBackup="true"
android:icon="#mipmap/app_ikona"
android:roundIcon="#mipmap/app_icon_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".SplashScreen"
android:label="ShromID"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".MainActivity"/>
<activity android:name=".Opis" />
<activity android:name=".Pronadi"></activity>
</application>
</manifest>
Main activity xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/pozadina2"
android:orientation="vertical"
tools:context="com.example.shromid.MainActivity">
<!-- Gumbovi u glavnom meniju -->
<Button
android:id="#+id/btnpronadi"
android:layout_width="183dp"
android:layout_height="56dp"
android:layout_marginBottom="11dp"
android:background="#drawable/gumbpronadi"
android:visibility="visible"
app:layout_constraintBottom_toTopOf="#+id/btnopis"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/imageView3" />
<Button
android:id="#+id/btnopis"
android:layout_width="183dp"
android:layout_height="56dp"
android:layout_marginBottom="11dp"
android:background="#drawable/gumbopis"
app:layout_constraintBottom_toTopOf="#+id/btnizlaz"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/btnpronadi" />
<Button
android:id="#+id/btnizlaz"
android:layout_width="183dp"
android:layout_height="56dp"
android:layout_marginBottom="106dp"
android:background="#drawable/gumbizlaz"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/btnopis" />
<!-- Kraj gumbova u glavnom meniju -->
<!-- Logo u glavnom meniju -->
<ImageView
android:id="#+id/imageView3"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginBottom="4dp"
android:layout_marginEnd="30dp"
android:layout_marginStart="30dp"
android:layout_marginTop="16dp"
android:src="#drawable/gljiveprobna"
app:layout_constraintBottom_toTopOf="#+id/btnpronadi"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" android:contentDescription="#string/todo" />
</android.support.constraint.ConstraintLayout>

Android - Store variable and use in webview link

I'm trying to store the users input from a text field in shared preferences and use that input in a webview link.
Here's what I have so far;
LoginActivity.java
package com.example.app;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.content.Intent;
public class LoginActivity extends Activity {
EditText subdomain;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
subdomain = (EditText) findViewById(R.id.subdomain);
Button btn=(Button)findViewById(R.id.sign_in_button);
btn.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Intent myIntent = new Intent(LoginActivity.this,
MainActivity.class);
LoginActivity.this.startActivity(myIntent);
}
});
}
public void saveInfo (View view) {
SharedPreferences sharedPref = getSharedPreferences("spfile",
Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("name", YourSchool.getText().toString());
editor.commit();
}
}
MainActivity.java
package com.example.app;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends Activity {
private WebView mWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = (WebView) findViewById(R.id.activity_main_webview);
// Force links and redirects to open in the WebView instead of in a
browser
mWebView.setWebViewClient(new WebViewClient());
// Enable Javascript
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
// Use remote resource
mWebView.loadUrl("https://"+client_subdomain+".domain.co.uk/texts");
// Stop local links and redirects from opening in browser instead
of WebView
mWebView.setWebViewClient(new MyAppWebViewClient());
}
public void displayData (View view) {
SharedPreferences sharedPref = getSharedPreferences("spfile",
Activity.MODE_PRIVATE);
String client_subdomain = sharedPref.getString("name", "");
}
// Prevent the back-button from closing the app
#Override
public void onBackPressed() {
if(mWebView.canGoBack()) {
mWebView.goBack();
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is
present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
activity_login.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.app.LoginActivity">
<LinearLayout
android:id="#+id/email_login_form"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<EditText
android:id="#+id/YourSchool"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Your school"
android:maxLines="1"
android:singleLine="true" />
<Button
android:id="#+id/sign_in_button"
style="?android:textAppearanceSmall"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:onClick="webView"
android:text="SIGN IN"
android:textStyle="bold" />
</LinearLayout>
</ScrollView>
</LinearLayout>
activity_main.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<WebView
android:id="#+id/activity_main_webview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.app">
<uses-permission android:name="android.permission.INTERNET" />
<!-- To auto-complete the email text field in the login form with the
user's emails -->
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#android:style/Theme.NoTitleBar.Fullscreen">
<activity
android:name=".MainActivity"
android:label="#string/app_name"></activity>
<activity
android:name=".LoginActivity"
android:label="#string/title_activity_login">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER"
/>
</intent-filter>
</activity>
</application>
</manifest>
My problem is that the client_subdomain is flagged as red in the MainActivity.java and when I try to build the project, I get the error: cannot find symbol variable client_subdomain
I think it's probably something small that I've missed out but any help would be greatly appreciated.
Many thanks,
Sam
Store the variable using sharedPrefeence as below,
SharedPreferences sp = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putString("your_string_key", yourStringValue);
editor.commit();
Then retrieve the value as,
SharedPreferences sp = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE);
String myStringValue = sp.getInt("your_string_key", -1);
Use the variable in the loadUrl as
mWebView.loadUrl("https://"+myStringValue+".mydomain.co.uk");

Android: StoredPreferences + WebView Link

I'm trying to store the users input from a text field in shared preferences and use that input in a webview link.
Here's what I have so far;
LoginActivity.java
package com.example.app;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.content.Intent;
public class LoginActivity extends Activity {
EditText subdomain;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
subdomain = (EditText) findViewById(R.id.subdomain);
Button btn=(Button)findViewById(R.id.sign_in_button);
btn.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Intent myIntent = new Intent(LoginActivity.this,
MainActivity.class);
LoginActivity.this.startActivity(myIntent);
}
});
}
public void saveInfo (View view) {
SharedPreferences sharedPref = getSharedPreferences("spfile",
Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("name", YourSchool.getText().toString());
editor.commit();
}
}
MainActivity.java
package com.example.app;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends Activity {
private WebView mWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = (WebView) findViewById(R.id.activity_main_webview);
// Force links and redirects to open in the WebView instead of in a
browser
mWebView.setWebViewClient(new WebViewClient());
// Enable Javascript
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
// Use remote resource
mWebView.loadUrl("https://"+client_subdomain+".domain.co.uk/texts");
// Stop local links and redirects from opening in browser instead
of WebView
mWebView.setWebViewClient(new MyAppWebViewClient());
}
public void displayData (View view) {
SharedPreferences sharedPref = getSharedPreferences("spfile",
Activity.MODE_PRIVATE);
String client_subdomain = sharedPref.getString("name", "");
}
// Prevent the back-button from closing the app
#Override
public void onBackPressed() {
if(mWebView.canGoBack()) {
mWebView.goBack();
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is
present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
activity_login.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.app.LoginActivity">
<LinearLayout
android:id="#+id/email_login_form"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<EditText
android:id="#+id/YourSchool"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Your school"
android:maxLines="1"
android:singleLine="true" />
<Button
android:id="#+id/sign_in_button"
style="?android:textAppearanceSmall"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:onClick="webView"
android:text="SIGN IN"
android:textStyle="bold" />
</LinearLayout>
</ScrollView>
</LinearLayout>
activity_main.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<WebView
android:id="#+id/activity_main_webview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.app">
<uses-permission android:name="android.permission.INTERNET" />
<!-- To auto-complete the email text field in the login form with the
user's emails -->
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#android:style/Theme.NoTitleBar.Fullscreen">
<activity
android:name=".MainActivity"
android:label="#string/app_name"></activity>
<activity
android:name=".LoginActivity"
android:label="#string/title_activity_login">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER"
/>
</intent-filter>
</activity>
</application>
</manifest>
My problem is that the client_subdomain is flagged as red in the MainActivity.java and when I try to build the project, I get the error: cannot find symbol variable client_subdomain
I think it's probably something small that I've missed out but any help would be greatly appreciated.
Many thanks,
Sam
Its because haven't declared "client_subdomain" as a variable within scope of onCreate
why don't you try changing displayData to
public String displayData () {
SharedPreferences sharedPref = getSharedPreferences("spfile",
Activity.MODE_PRIVATE);
return sharedPref.getString("name", "");
}
and in onCreate of the Main Activity
...
// Enable Javascript
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
// Use remote resource
mWebView.loadUrl("https://"+displayData()+".domain.co.uk/texts");
...
Also, I don't see you ever calling "saveInfo" anywhere in your Login Activity. As well, you should probably change the function too. You aren't grabbing the text from the EditText correctly (whatever YourSchool) is
public void saveInfo() {
SharedPreferences sharedPref = getSharedPreferences("spfile", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("name", subdomain.getText().toString());
editor.commit();
}
And this will be what your onCreate should have,
protected void onCreate(Bundle savedInstanceState) {
...
btn.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
saveInfo();
Intent myIntent = new Intent(LoginActivity.this, MainActivity.class);
LoginActivity.this.startActivity(myIntent);
}
});
...
}

Categories