When I tried to access (file:///sdcard/) using mobile browsers (ex. Firefox, Opera ..etc). It shows me an index page for the SDCard (see the screenshot).
However, when I access the same url using a webview and give it a storage permission and does not show the Index page. My code is below:
package com.example.webbrowser;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.Toast;
import java.io.IOException;
import android.content.Context;
import android.net.ConnectivityManager;
import android.webkit.CookieManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
class NetworkState {
public static boolean connectionAvailable(Context context){
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
return connectivityManager.getActiveNetworkInfo() !=null;
}
}
class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
CookieManager.getInstance().setAcceptCookie(true);
return true;
}
}
public class MainActivity extends AppCompatActivity {
WebView webView;
EditText editText;
ProgressBar progressBar;
Button back, forward, stop, refresh, homeButton;
Button goButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.web_address_edit_text);
back = (Button) findViewById(R.id.back_arrow);
forward = (Button) findViewById(R.id.forward_arrow);
stop = (Button) findViewById(R.id.stop);
goButton = (Button)findViewById(R.id.go_button);
refresh = (Button) findViewById(R.id.refresh);
homeButton = (Button) findViewById(R.id.home);
progressBar = (ProgressBar) findViewById(R.id.progress_bar);
progressBar.setMax(100);
progressBar.setVisibility(View.VISIBLE);
webView = (WebView) findViewById(R.id.web_view);
if (savedInstanceState != null) {
webView.restoreState(savedInstanceState);
} else {
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setUseWideViewPort(true);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setSupportZoom(true);
webView.getSettings().setSupportMultipleWindows(true);
webView.getSettings().setAllowContentAccess(true);
webView.getSettings().setAllowFileAccess(true);
webView.getSettings().setAllowUniversalAccessFromFileURLs(true);
webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
webView.setBackgroundColor(Color.WHITE);
webView.setWebChromeClient(new WebChromeClient() {
#Override
public void onProgressChanged(WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
progressBar.setProgress(newProgress);
if (newProgress < 100 && progressBar.getVisibility() == ProgressBar.GONE) {
progressBar.setVisibility(ProgressBar.VISIBLE);
}
if (newProgress == 100) {
progressBar.setVisibility(ProgressBar.GONE);
}else{
progressBar.setVisibility(ProgressBar.VISIBLE);
}
}
});
}
}
public void go_button(View view) {
try {
if(!NetworkState.connectionAvailable(MainActivity.this)){
Toast.makeText(MainActivity.this, "Check connection", Toast.LENGTH_SHORT).show();
}else {
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(editText.getWindowToken(), 0);
webView.loadUrl(editText.getText().toString());
editText.setText("");
}
}catch (Exception e) {
e.printStackTrace();
}
}
public void home_button(View view) {
webView.loadUrl("https://google.com");
}
public void refresh_button(View view) {
webView.reload();
}
public void stop_button(View view) {
webView.stopLoading();
}
public void forward_button(View view) {
if (webView.canGoForward()) {
webView.goForward();
}
}
public void back_button(View view) {
if (webView.canGoBack()) {
webView.goBack();
}
}
}
Android mainifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.webbrowser">
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
android:usesCleartextTraffic="true"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.WebBrowser">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Any help ?
Related
I have two activities: MainActivity and ActivityTwo. When starting application, I start service serviceApp, which after some events should start ActivityTwo. For the test, I made the launch after 10 seconds and AsyncTask, but if the application is hidden, activity does not start
How do I launch activity even if the app is hidden?
MainActivity
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SwitchCompat;
import android.app.ActivityManager;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import java.security.Provider;
import java.util.List;
public class MainActivity extends AppCompatActivity {
SharedPreferences setting;
#Override
protected void onCreate(Bundle savedInstanceState) {
Intent service = new Intent(this, serviceApp.class);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setting = getSharedPreferences("settings", MODE_PRIVATE);
SwitchCompat switchCompat = findViewById(R.id.switchBLock);
switchCompat.setOnCheckedChangeListener((view, bool) -> {
SharedPreferences.Editor editor = setting.edit();
editor.putBoolean("block", bool);
editor.apply();
if(bool){
startService(service);
}else{
stopService(service);
}
});
if(setting.getBoolean("block", false)){
switchCompat.setChecked(true);
}
}
}
ActivityTwo
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;
public class ActivityTwo extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_two);
}
}
serviceApp
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.IBinder;
public class serviceApp extends Service {
Context context;
public serviceApp() {
context = this;
}
#Override
public void onCreate() {
super.onCreate();
new Async().execute();
}
class Async extends AsyncTask<Void, Void, Void>{
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
Intent startMain = new Intent();
startMain.setClass(context, ActivityTwo.class);
startMain.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);
}
#Override
protected Void doInBackground(Void... voids) {
for(int i = 0; i < 2; i++) {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return null;
}
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
AndroidManifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.test">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.AppCompat.NoActionBar">
<activity android:name="com.example.test.ActivityTwo"></activity>
<service
android:name=".serviceApp"/>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
I found an easy way to fix this ailment, you need to give the application the SYSTEM_ALERT_WINDOW permission
https://developer.android.com/guide/components/activities/background-starts
AndroidManifest.xml
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
MainActivity
Intent myIntent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
startActivity(myIntent);
Below is the code for my music player. I use Videoview to play a local list of selective songs.
I want to store and resume the playback position when orientation changes (portrait/landscape).
I have used onSaveInstanceState and onRestoreInstanceState methods. No errors on build, but still the songs reset every time.
I couldn't figure out what's wrong.
package io.automaton.android.morningbinge;
import androidx.appcompat.app.AlertDialog;
import android.app.Activity;
import android.content.DialogInterface;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.widget.Toast;
import android.widget.VideoView;
import android.widget.MediaController;
import java.util.ArrayList;
public class MainActivity extends Activity
implements MediaPlayer.OnCompletionListener {
VideoView vw;
ArrayList<Integer> videolist = new ArrayList<>();
int currvideo = 0;
int mPositionWhenPaused=0;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
vw = (VideoView)findViewById(R.id.videoView);
vw.setMediaController(new MediaController(this));
vw.setOnCompletionListener(this);
// video name should be in lower case alphabet.
videolist.add(R.raw.onbadhu_kolum);
videolist.add(R.raw.kala_bhairava_ashtakam);
videolist.add(R.raw.panchamukh_hanumath_kavacham);
videolist.add(R.raw.kandha_shashti_kavasam);
setVideo(videolist.get(0));
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
//we use onSaveInstanceState in order to store the video playback position for orientation change
savedInstanceState.putInt("Position", vw.getCurrentPosition());
vw.pause();
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
//we use onRestoreInstanceState in order to play the video playback from the stored position
mPositionWhenPaused = savedInstanceState.getInt("Position");
vw.seekTo(mPositionWhenPaused);
}
public void setVideo(int id)
{
String uriPath
= "android.resource://"
+ getPackageName() + "/" + id;
Uri uri = Uri.parse(uriPath);
vw.setVideoURI(uri);
vw.start();
}
public void onCompletion(MediaPlayer mediapalyer)
{
AlertDialog.Builder obj = new AlertDialog.Builder(this);
obj.setTitle("Playback Finished!");
obj.setIcon(R.mipmap.ic_launcher);
MyListener m = new MyListener();
obj.setPositiveButton("Replay", m);
obj.setNegativeButton("Next", m);
obj.setMessage("Want to replay or play next video?");
obj.show();
}
class MyListener implements DialogInterface.OnClickListener {
public void onClick(DialogInterface dialog, int which)
{
if (which == -1) {
vw.seekTo(0);
vw.start();
}
else {
++currvideo;
if (currvideo == videolist.size())
currvideo = 0;
setVideo(videolist.get(currvideo));
}
}
}
}
I sorted out the issue. I changed the way the list is being called to play with the setOnPreparedListener, seeking to last played position.
...
Main Activity
package io.automaton.android.morningbinge;
import androidx.appcompat.app.AlertDialog;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.res.Configuration;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import android.widget.VideoView;
import android.widget.MediaController;
import android.media.MediaPlayer.OnPreparedListener;
import java.util.ArrayList;
public class MainActivity extends Activity
implements MediaPlayer.OnCompletionListener {
VideoView vw;
ArrayList<Integer> videolist = new ArrayList<>();
int currvideo = 0;
int mPositionWhenPaused=0;
private static final String TAG = "MyActivity";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
vw = (VideoView)findViewById(R.id.videoView);
vw.setMediaController(new MediaController(this));
vw.setOnCompletionListener(this);
videolist.add(R.raw.onbadhu_kolum);
videolist.add(R.raw.kala_bhairava_ashtakam);
videolist.add(R.raw.panchamukh_hanumath_kavacham);
videolist.add(R.raw.kandha_shashti_kavasam);
try {
//set the uri of the video to be played
vw.setVideoURI(Uri.parse("android.resource://" + getPackageName() + "/" + videolist.get(0)));
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
View decorView = getWindow().getDecorView();
int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN;
decorView.setSystemUiVisibility(uiOptions);
vw.requestFocus();
vw.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mediaPlayer) {
vw.seekTo(mPositionWhenPaused);
if (mPositionWhenPaused == 0) {
vw.start();
} else {
vw.pause();
}
}
});
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putInt("Position", vw.getCurrentPosition());
Log.i("Orientation Change", "Warn-orientation change and saved");
vw.pause();
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mPositionWhenPaused = savedInstanceState.getInt("Position");
vw.seekTo(mPositionWhenPaused);
Log.i("restored", "restored after orientation change");
}
public void onCompletion(MediaPlayer mediapalyer)
{
++currvideo;
if (currvideo == videolist.size())
currvideo = 0;
setVideo(videolist.get(currvideo));
}
}
...
android manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="io.automaton.android.morningbinge">
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.INTERNET" />
<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=".MainActivity"
android:configChanges="orientation|screenSize|screenLayout|keyboardHidden">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
...
Logcart is giving error like, on my phone
2020-05-03 17:48:38.715 1785-2071/com.example.tasteportal04b E/libGLESv2: ASUS:glGetString HOOK !!!! name=0x1f01,ret=Adreno (TM) 512
On some devices like Samsung S6, the app is not starting, displaying a crash message, on my Asus works perfectly
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.tasteportal04b">
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="#drawable/ic_taste" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<application
android:name=".nootificare"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme"
android:usesCleartextTraffic="true"
android:screenOrientation="portrait"
android:hardwareAccelerated="true"
android:largeHeap="true"
>
<activity android:name=".MainActivity"
android:hardwareAccelerated="false">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".NewActivity" android:screenOrientation="portrait"
android:theme="#style/SplashTheme"></activity>
</application>
</manifest>
NewActivity.java
package com.example.tasteportal04b;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.view.HapticFeedbackConstants;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.getbase.floatingactionbutton.FloatingActionButton;
import java.util.Objects;
public class NewActivity extends AppCompatActivity {
Toolbar toolbar;
private WebView webView;
private ProgressBar progressbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new);
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Objects.requireNonNull(getSupportActionBar()).setTitle("TASTE Live");
toolbar.setSubtitle("v1.0");
toolbar.setLogo(R.mipmap.tasteico);
toolbar.setTitleTextColor(getResources().getColor(R.color.colortitle));
toolbar.setSubtitleTextColor(getResources().getColor(R.color.colorsubtitle));
webView = findViewById(R.id.webView);
progressbar = findViewById(R.id.progressbar);
progressbar.setMax(100);
webView.loadUrl("https://");
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setBuiltInZoomControls(false);
webView.setBackgroundColor(Color.TRANSPARENT);
webView.setWebChromeClient(new WebChromeClient(){
#Override
public void onProgressChanged(WebView view, int newProgress)
{
super.onProgressChanged(view, newProgress);
progressbar.setProgress(newProgress);
}
});
FloatingActionButton facebook = findViewById(R.id.Facebook);
FloatingActionButton classroom = findViewById(R.id.Classroom);
FloatingActionButton blog = findViewById(R.id.Blog);
FloatingActionButton youtube = findViewById(R.id.Youtube);
FloatingActionButton drive = findViewById(R.id.Drive);
facebook.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
v.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
try {
Intent gofb = new Intent(Intent.ACTION_VIEW, Uri.parse("fb://page/"));
startActivity(gofb);
} catch(Exception e) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/TASTEATB")));
}
showToast("T.A.S.T.E Facebook");
}
});
classroom.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
v.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
Intent goclass = new Intent(Intent.ACTION_VIEW, Uri.parse("https://classroom.google.com/u/0/c/NzgzMTc2MDk5NjNa"));
startActivity(goclass);
showToast("T.A.S.T.E Classroom");
}
});
blog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
v.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
Intent goblog = new Intent(Intent.ACTION_VIEW, Uri.parse("https://"));
startActivity(goblog);
showToast("T.A.S.T.E Blog");
}
});
youtube.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
v.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
Intent goyt = new Intent(Intent.ACTION_VIEW);
try {
goyt.setData(Uri.parse("https://"));
goyt.setPackage("com.google.android.youtube");
} catch(Exception e) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.youtube.com/channel/")));
}
startActivity(goyt);
showToast("T.A.S.T.E Youtube");
}
});
drive.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
v.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
Intent godrive = new Intent(Intent.ACTION_VIEW, Uri.parse("https://"));
startActivity(godrive);
showToast("T.A.S.T.E Drive");
}
});
}//inchide oncreate
public void showToast(String message){
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId())
{
case R.id.bug:
Intent gobug = new Intent(Intent.ACTION_VIEW, Uri.parse("https://"));
startActivity(gobug);
showToast("Raporteaza un bug");
break;
case R.id.update:
showToast("Update aplicatie");
webView.loadUrl("https://");
break;
}
return super.onOptionsItemSelected(item);
}
}
I had my preferences screen working, but now stopped showing anything at all and nothing I try is fixing it. When I click the button, the preferences screen shows, but when I click on the one category, I just get a blank screen instead of whats in that category.
All the Views show for that category in Android Studio, but when I run, nothing shows up -_- It must be something to do with opening the specific category, I can't figure it out though.
I'm sure it's something simple, but I'd be super grateful if someone could help. Its driving me mad :O
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="nathaniel.watispend">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
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=".TransactionsActivity" />
<activity
android:name=".SettingsActivity"
android:label="#string/title_activity_settings" />
<activity android:name=".GraphActivity"></activity>
</application>
pref_general.xml
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<Preference android:title="Test"
android:key="privacyButton"
android:summary=""/>
</PreferenceScreen>
pref_headers.xml
<preference-headers xmlns:android="http://schemas.android.com/apk/res/android">
<header
android:fragment="nathaniel.watispend.SettingsActivity$GeneralPreferenceFragment"
android:icon="#drawable/ic_info_black_24dp"
android:title="#string/pref_header_general" />
</preference-headers>
SettingsActivity.xml
package nathaniel.watispend;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.support.v7.app.ActionBar;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.preference.RingtonePreference;
import android.text.TextUtils;
import android.view.MenuItem;
import java.util.List;
public class SettingsActivity extends AppCompatPreferenceActivity {
private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object value) {
String stringValue = value.toString();
if (preference instanceof ListPreference) {
ListPreference listPreference = (ListPreference) preference;
int index = listPreference.findIndexOfValue(stringValue);
preference.setSummary(
index >= 0
? listPreference.getEntries()[index]
: null);
} else if (preference instanceof RingtonePreference) {
if (TextUtils.isEmpty(stringValue)) {
preference.setSummary(R.string.pref_ringtone_silent);
} else {
Ringtone ringtone = RingtoneManager.getRingtone(
preference.getContext(), Uri.parse(stringValue));
if (ringtone == null) {
preference.setSummary(null);
} else {
String name = ringtone.getTitle(preference.getContext());
preference.setSummary(name);
}
}
} else {
preference.setSummary(stringValue);
}
return true;
}
};
private static boolean isXLargeTablet(Context context) {
return (context.getResources().getConfiguration().screenLayout
& Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_XLARGE;
}
private static void bindPreferenceSummaryToValue(Preference preference) {
preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener);
sBindPreferenceSummaryToValueListener.onPreferenceChange(preference,
PreferenceManager
.getDefaultSharedPreferences(preference.getContext())
.getString(preference.getKey(), ""));
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setupActionBar();
}
private void setupActionBar() {
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
// Show the Up button in the action bar.
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
#Override
public boolean onIsMultiPane() {
return isXLargeTablet(this);
}
/**
* {#inheritDoc}
*/
#Override
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void onBuildHeaders(List<Header> target) {
loadHeadersFromResource(R.xml.pref_headers, target);
}
protected boolean isValidFragment(String fragmentName) {
return PreferenceFragment.class.getName().equals(fragmentName)
|| GeneralPreferenceFragment.class.getName().equals(fragmentName);
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class GeneralPreferenceFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
startActivity(new Intent(getActivity(), SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
}
Hello my App crash if I try to open my AddIP.class fragment
My error code says:
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{de.kwietzorek.fulcrumwebview/de.kwietzorek.fulcrumwebview.MainActivity$AddIP}: java.lang.InstantiationException: java.lang.Class has no zero argument constructor
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="de.kwietzorek.fulcrumwebview" >
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true">
<activity android:name=".MainActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".MainActivity$AddIP"></activity>
</application>
<uses-permission android:name="android.permission.INTERNET" />
</manifest>
MainActivity.java
package de.kwietzorek.fulcrumwebview;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import java.util.ArrayList;
public class MainActivity extends FragmentActivity {
String selected;
Spinner spinner;
WebView myWebView;
ArrayList<String> server_name_list = null;
/* Menu */
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.add_server:
Intent intent = new Intent(this, AddIP.class);
this.startActivity(intent);
return true;
case R.id.menu_refresh:
myWebView.reload();
return true;
default:
return true;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//WebView
myWebView = (WebView) findViewById(R.id.webView);
myWebView.setWebViewClient(new WebC());
WebSettings webSettings = myWebView.getSettings();
//JavaScript enable
webSettings.setJavaScriptEnabled(true);
//Server name spinner
if (server_name_list != null) {
spinner = (Spinner) findViewById(R.id.server_spinner);
ArrayAdapter<String> server_adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, server_name_list);
server_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(server_adapter);
server_adapter.notifyDataSetChanged();
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
selected = parent.getItemAtPosition(pos).toString();
myWebView.loadUrl(selected);
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
//WebView Client
public class WebC extends WebViewClient {
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
}
}
public class AddIP extends Fragment {
Button btn_back, btn_add;
EditText server_ip, server_name;
String new_server_ip, new_server_name;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_ip);
server_ip = (EditText) findViewById(R.id.edit_server_address);
server_name = (EditText) findViewById(R.id.edit_server_name);
/* Back Button */
btn_back = (Button) findViewById(R.id.btn_back);
btn_back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
});
/* Add IP Button */
btn_add = (Button) findViewById(R.id.btn_add);
btn_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
/*new_server_ip = server_ip.getText().toString();
MainActivity.server_array_ip.add(new_server_ip);*/
new_server_name = server_name.getText().toString();
server_name_list.add(new_server_name);
}
});
}
}
}
Add this method to your faragment :
public AddIP() {
}
in some situation you need an empty constructor method for your fragment