If the user were to select an item from the drop down navigation menu, it appears as selected only until the application closes. Then, on reopening the app, it displays the first item as selected. How can I keep an item permanently selected until the user changes it even after the activity closes? FYI There is only one activity in my application.
MainActivity.java
package com.student.connect;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.ActionBar;
import android.net.Uri;
import android.os.Bundle;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.support.v4.app.FragmentActivity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ArrayAdapter;
import android.widget.Toast;
public class MainActivity extends FragmentActivity implements
ActionBar.OnNavigationListener {
/**
* The serialization (saved instance state) Bundle key representing the
* current dropdown position.
*/
private static final String STATE_SELECTED_NAVIGATION_ITEM = "selected_navigation_item";
#SuppressWarnings("unused")
private WebView student_zangle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set up the action bar to show a dropdown list.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
actionBar.setTitle(" ");
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setLogo(R.drawable.logo);
actionBar.setDisplayUseLogoEnabled(true);
// Set up the dropdown list navigation in the action bar.
actionBar.setListNavigationCallbacks(
// Specify a SpinnerAdapter to populate the dropdown list.
new ArrayAdapter<String>(getActionBarThemedContextCompat(),
android.R.layout.simple_list_item_1,
android.R.id.text1, new String[] {
"Select a District",
"Clovis Unified",
"Claremont Unified",
"San Diego Unified",
"Pleasanton Unified",
"San Juan Unified", }), this);
}
/**
* Backward-compatible version of {#link ActionBar#getThemedContext()} that
* simply returns the {#link android.app.Activity} if
* <code>getThemedContext</code> is unavailable.
*/
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
private Context getActionBarThemedContextCompat() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
return getActionBar().getThemedContext();
} else {
return this;
}
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
// Restore the previously serialized current dropdown position.
if (savedInstanceState.containsKey(STATE_SELECTED_NAVIGATION_ITEM)) {
getActionBar().setSelectedNavigationItem(
savedInstanceState.getInt(STATE_SELECTED_NAVIGATION_ITEM));
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
// Serialize the current dropdown position.
outState.putInt(STATE_SELECTED_NAVIGATION_ITEM, getActionBar()
.getSelectedNavigationIndex());
}
#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;
}
#SuppressLint("NewApi")
#Override
public boolean onNavigationItemSelected(int position, long id)
{
WebView student_zangle = (WebView) findViewById(R.id.student_zangle);
student_zangle.setWebViewClient( new YourWebClient());
WebSettings settings = student_zangle.getSettings();
settings.setLoadWithOverviewMode(true);
settings.setUseWideViewPort(true);
settings.setJavaScriptEnabled(true);
settings.setJavaScriptCanOpenWindowsAutomatically(true);
settings.setAllowUniversalAccessFromFileURLs(true);
settings.setAllowContentAccess(true);
settings.setBuiltInZoomControls(true);
settings.setDisplayZoomControls(false);
if ( position == 0 )
{
Toast.makeText(getApplicationContext(), "Select a District from the Menu Above", Toast.LENGTH_LONG).show();
}
else if ( position == 1 )
{
student_zangle.loadUrl("https://zangleweb01.clovisusd.k12.ca.us/studentconnect/");
student_zangle.zoomOut();
student_zangle.zoomOut();
student_zangle.zoomOut();
}
else if ( position == 2 )
{
student_zangle.loadUrl("http://studentconnect.cusd.claremont.edu/");
}
else if ( position == 3 )
{
student_zangle.loadUrl("https://zangle.sandi.net/studentconnect/");
}
else if ( position == 4 )
{
student_zangle.loadUrl("https://sis.pleasanton.k12.ca.us/StudentPortal/");
}
else if ( position == 5 )
{
student_zangle.loadUrl("https://sis.sanjuan.edu/studentportal");
}
student_zangle.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
settings.setUserAgentString("Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.4) Gecko/20100101 Firefox/4.0");
student_zangle.setDownloadListener(new DownloadListener()
{
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype, long contentLength)
{
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setType("application/x-rar-compressed");
intent.setData(Uri.parse(url));
startActivity(intent);
}
});
return true;
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
moveTaskToBack(true);
}
return super.onKeyDown(keyCode, event);
}
private class YourWebClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.contains("mailto"))
{
String mail = url.replaceFirst("mailto:", "");
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("message/rfc822");
intent.putExtra(Intent.EXTRA_EMAIL, mail );
startActivity(intent);
return true;
}
view.loadUrl(url);
return true;
}
}
}
Use SharedPreferences for this case.
//write your selected position in preferences when the user clicks the DropDown menu
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
preferences.edit().putInt("selectedPosition", selectedItemIndex).commit();
When the user returns to the Activity (launching the app again), you have to read the value from Preferences, like this:
int position = PreferenceManager.getDefaultSharedPreferences(this).getInt("selectedPosition",0);
Then just select your dropdown menu item programatically.
The SharedPreferences data is kept even when the app closes. So you can trust it because it's persistent data and does not depend on your App state.
Note that your Preferences will be empty if the user unninstalls the app or clears the app data.
Related
I have a on/off switch called audio_switch. In my MainActivity file I want to look if the switch is on, if so, it should set a variable audio = 1. This piece of code mentioned can be found at the bottom of my MainActivity. On the very top after you can see I added a line to find my audio file. A few lines later I used an if(audio == 1) statement to check if the switch is on, so it will play the audio. This however does not work, it does however when I change the statement to audio == audio
package com.joeridukker.main;
import android.animation.ArgbEvaluator;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.support.constraint.ConstraintLayout;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
public static int audio;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final MediaPlayer MansNotHot = MediaPlayer.create(this, R.raw.mans_not_hot);
if(audio == 1){
MansNotHot.start();
}
int secondsDelayed = 1;
Handler start = new Handler();
start.postDelayed(new Runnable() {
public void run() {
Animation wait = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.wait);
ConstraintLayout Entire = (ConstraintLayout) findViewById(R.id.Entire);
ImageView Logo = (ImageView) findViewById(R.id.Logo);
TextView Welcome = (TextView) findViewById(R.id.Welcome);
Welcome.startAnimation(wait);
Entire.startAnimation(wait);
Logo.startAnimation(wait);
// Actions to do after 10 seconds
}
}, 0);
Handler animation = new Handler();
animation.postDelayed(new Runnable() {
public void run() {
Animation slide_up = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.fade_and_slide_upwards);
Animation slide_down = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.fade_and_slide_downwards);
TextView Welcome = (TextView) findViewById(R.id.Welcome);
ImageView Logo = (ImageView) findViewById(R.id.Logo);
Logo.startAnimation(slide_down);
Welcome.startAnimation(slide_up);
// Actions to do after 10 seconds
}
}, 500);
Handler entire_animation = new Handler();
entire_animation.postDelayed(new Runnable() {
public void run() {
Animation fade_in = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.fade_in);
ConstraintLayout Entire = (ConstraintLayout) findViewById(R.id.Entire);
TextView Welcome = (TextView) findViewById(R.id.Welcome);
Entire.startAnimation(fade_in);
ObjectAnimator.ofObject(
Welcome,
"textColor",
new ArgbEvaluator(),
Color.argb(140,0,0,0),
Color.WHITE
).setDuration(500)
.start();
}
}, 500);
new Handler().postDelayed(new Runnable() {
public void run() {
Handler splash = new Handler();
int a = 1;
Intent Intent = new Intent(MainActivity.this, Differentiate.class);
Intent.putExtra("HEADER", a);
startActivity(Intent);
overridePendingTransition(R.anim.fade_in_switch_fast,R.anim.fade_out_switch_fast);
finish();
}
}, secondsDelayed * 2500);
}
public static class SettingsActivity extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.pref_general);
//Check the current value in preference.
SharedPreferences switchPrefStatus = PreferenceManager.getDefaultSharedPreferences(getActivity());
boolean switchPrefValue = switchPrefStatus.getBoolean("audio_switch", false);
Toast.makeText(getActivity(), "Current value: " + switchPrefValue, Toast.LENGTH_SHORT).show();
Preference switchPref = (Preference) findPreference("audio_switch");
switchPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object o) {
boolean isOn = (boolean) o;
//Do what you want with the value!:)
if (isOn) {
audio = 1;
}else{
audio = 0;
}
return true;
}
});
}
}
}
My SettingsActivity
package com.joeridukker.main;
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.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.preference.RingtonePreference;
import android.support.v4.app.NavUtils;
import android.support.v7.app.ActionBar;
import android.text.TextUtils;
import android.view.MenuItem;
import java.util.List;
/**
* A {#link PreferenceActivity} that presents a set of application settings. On
* handset devices, settings are presented as a single list. On tablets,
* settings are split by category, with category headers shown to the left of
* the list of settings.
* <p>
* See <a href="http://developer.android.com/design/patterns/settings.html">
* Android Design: Settings</a> for design guidelines and the <a
* href="http://developer.android.com/guide/topics/ui/settings.html">Settings
* API Guide</a> for more information on developing a Settings UI.
*/
public class SettingsActivity extends AppCompatPreferenceActivity {
/**
* A preference value change listener that updates the preference's summary
* to reflect its new value.
*/
private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object value) {
String stringValue = value.toString();
if (preference instanceof ListPreference) {
// For list preferences, look up the correct display value in
// the preference's 'entries' list.
ListPreference listPreference = (ListPreference) preference;
int index = listPreference.findIndexOfValue(stringValue);
// Set the summary to reflect the new value.
preference.setSummary(
index >= 0
? listPreference.getEntries()[index]
: null);
} else if (preference instanceof RingtonePreference) {
// For ringtone preferences, look up the correct display value
// using RingtoneManager.
if (TextUtils.isEmpty(stringValue)) {
// Empty values correspond to 'silent' (no ringtone).
preference.setSummary(R.string.pref_ringtone_silent);
} else {
Ringtone ringtone = RingtoneManager.getRingtone(
preference.getContext(), Uri.parse(stringValue));
if (ringtone == null) {
// Clear the summary if there was a lookup error.
preference.setSummary(null);
} else {
// Set the summary to reflect the new ringtone display
// name.
String name = ringtone.getTitle(preference.getContext());
preference.setSummary(name);
}
}
} else {
// For all other preferences, set the summary to the value's
// simple string representation.
preference.setSummary(stringValue);
}
return true;
}
};
/**
* Helper method to determine if the device has an extra-large screen. For
* example, 10" tablets are extra-large.
*/
private static boolean isXLargeTablet(Context context) {
return (context.getResources().getConfiguration().screenLayout
& Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_XLARGE;
}
/**
* Binds a preference's summary to its value. More specifically, when the
* preference's value is changed, its summary (line of text below the
* preference title) is updated to reflect the value. The summary is also
* immediately updated upon calling this method. The exact display format is
* dependent on the type of preference.
*
* #see #sBindPreferenceSummaryToValueListener
*/
private static void bindPreferenceSummaryToValue(Preference preference) {
// Set the listener to watch for value changes.
preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener);
// Trigger the listener immediately with the preference's
// current value.
sBindPreferenceSummaryToValueListener.onPreferenceChange(preference,
PreferenceManager
.getDefaultSharedPreferences(preference.getContext())
.getString(preference.getKey(), ""));
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setupActionBar();
}
/**
* Set up the {#link android.app.ActionBar}, if the API is available.
*/
private void setupActionBar() {
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
// Show the Up button in the action bar.
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
if (!super.onMenuItemSelected(featureId, item)) {
NavUtils.navigateUpFromSameTask(this);
}
return true;
}
return super.onMenuItemSelected(featureId, item);
}
/**
* {#inheritDoc}
*/
#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);
}
/**
* This method stops fragment injection in malicious applications.
* Make sure to deny any unknown fragments here.
*/
protected boolean isValidFragment(String fragmentName) {
return PreferenceFragment.class.getName().equals(fragmentName)
|| GeneralPreferenceFragment.class.getName().equals(fragmentName)
|| DataSyncPreferenceFragment.class.getName().equals(fragmentName)
|| NotificationPreferenceFragment.class.getName().equals(fragmentName);
}
/**
* This fragment shows general preferences only. It is used when the
* activity is showing a two-pane settings UI.
*/
static int audio;
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class GeneralPreferenceFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_general);
setHasOptionsMenu(true);
Preference switchPref = (Preference) findPreference("audio_switch");
switchPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object o) {
boolean isOn = (boolean) o;
if (isOn) {
audio = 1;
}else{
audio = 0;
}
return 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);
}
}
/**
* This fragment shows notification preferences only. It is used when the
* activity is showing a two-pane settings UI.
*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class NotificationPreferenceFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_notification);
setHasOptionsMenu(true);
// Bind the summaries of EditText/List/Dialog/Ringtone preferences
// to their values. When their values change, their summaries are
// updated to reflect the new value, per the Android Design
// guidelines.
bindPreferenceSummaryToValue(findPreference("notifications_new_message_ringtone"));
}
#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);
}
}
/**
* This fragment shows data and sync preferences only. It is used when the
* activity is showing a two-pane settings UI.
*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class DataSyncPreferenceFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_data_sync);
setHasOptionsMenu(true);
// Bind the summaries of EditText/List/Dialog/Ringtone preferences
// to their values. When their values change, their summaries are
// updated to reflect the new value, per the Android Design
// guidelines.
bindPreferenceSummaryToValue(findPreference("sync_frequency"));
}
#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);
}
}
}
I use RecycleView in my application and I want to implement AsyncTask so it will work faster, because it takes a few seconds until fragment is loaded.
To be more specific, when clicking to enter the fragment which contains the RecyclerView, it hangs a few seconds and I understood that by using AsyncTask it will load only the items that shown on screen and only if I scroll down it will load the the next items. So it will fix the delaying...
How to do it please?
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.app.Fragment;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;
import entities.Order;
import entities.User;
public class HomeFragment extends Fragment implements TransAdapter.ClickListener {
private RecyclerView rvTrans;
private TransAdapter adapter;
private MenuItem mSearchAction;
private SearchView searchView;
private ActionBar actionBar;
private boolean isSearchOpened = false;
private EditText etSearch;
public HomeFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home, container, false);
rvTrans = (RecyclerView) view.findViewById(R.id.rv_transactions);
rvTrans.setLayoutManager(new LinearLayoutManager(getActivity()));
adapter = new TransAdapter(getActivity());
adapter.setClickListener(this);
rvTrans.setAdapter(adapter);
try {
adapter.setOrderList(HomeActivity.backEnd.booksForSale());
} catch (Exception e) {
Toast.makeText(getActivity().getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId())
{
case R.id.action_search:
handleMenuSearch();
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
mSearchAction = menu.findItem(R.id.action_search);
searchView = (SearchView) MenuItemCompat.getActionView(mSearchAction);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
adapter.clearData();
try {
adapter.setOrderList(HomeActivity.backEnd.bookGlobalSearch(query));
} catch (Exception e) {
Toast.makeText(getActivity().getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
}
#Override
public void itemClicked(Order order) {
Intent intent = new Intent(getActivity(), DetailsActivity.class);
intent.putExtra("BOOK_PICTURE", order.getBookPicture());
intent.putExtra("BOOK_NAME", order.getBookName());
intent.putExtra("BOOK_AUTHOR", order.getAuthorName());
intent.putExtra("BOOK_GENRE", order.getGenre());
intent.putExtra("BOOK_PUBLISHING", order.getPublishingYear());
startActivity(intent);
}
private void handleMenuSearch() {
actionBar = ((AppCompatActivity)getActivity()).getSupportActionBar(); //get the actionbar
if(isSearchOpened){ //test if the search is open
if(actionBar != null)
{
actionBar.setDisplayShowCustomEnabled(false); //disable a custom view inside the actionbar
actionBar.setDisplayShowTitleEnabled(true); //show the title in the action bar
}
// hides the keyboard
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(etSearch.getWindowToken(), 0);
isSearchOpened = false;
} else { // open the search entry
if(actionBar != null)
{
actionBar.setDisplayShowCustomEnabled(true); //enable it to display a
// custom view in the action bar.
// action.setCustomView(R.layout.search_bar);//add the custom view
actionBar.setDisplayShowTitleEnabled(false); //hide the title
}
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(etSearch, InputMethodManager.SHOW_IMPLICIT);
isSearchOpened = true;
}
}
}
Thanks!
May be you confuse using of async task.
Async task should be using in long operation to avoiding block UI thread (Ex. http request, pagination, etc.)
But this no mean your businness logic will be run too fast (this will run in parallel).
If in your recyclerView you load big image or image from url you need to manage directly your logic with cache pattern
you can start take a look how this logic work in project like picasso or Processing Bitmaps Off the UI Thread directly from google developers http://developer.android.com/training/displaying-bitmaps/process-bitmap.html#async-task
Hope this may help!!!
I'm creating a simple note app in android. I am basically using two activity classes named as Main Page and Second Activity. I'm storing some data in the shared preferences in second activity and want to use it in my first Activity. I'm storing data in shared preferences as (String,Integer) key-pair. In my main activity class, when i'm getting the value from shared preferences as Integer and compare it with value 0,i'm getting an exception that java.lang.string can't be cast to java.lang.integer. I don't know why this exception is coming. Android studio is not giving me an exception but when i run my app, my app crashes. I have attach the code for reference.
MainActivity class:
package com.example.prateeksharma.noteballondor;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class MainPage extends ActionBarActivity {
Notes notes = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_page);
}
#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_page, menu);
return true;
}
#Override
protected void onResume() {
super.onResume();
SharedPreferences sharedPreferences = getSharedPreferences("com.example.prateeksharma.noteballondor", Context.MODE_PRIVATE);
//Map<String, Integer> notesMap = (Map<String, Integer>)sharedPreferences.getAll();
List<Notes> listNotes = new ArrayList<>();
Map<String, ?> prefsMap = sharedPreferences.getAll();
for (Map.Entry<String, ?> entry: prefsMap.entrySet()) {
if (entry.getValue() == 0){
notes = new Notes();
}
notes.setNoteText(entry.getKey());
listNotes.add(notes);
sharedPreferences.edit().putInt(entry.getKey(),2);
}
NotesArrayAdapter notesArrayAdapter = new NotesArrayAdapter(this,R.layout.list_layout, listNotes);
final ListView listview = (ListView) findViewById(R.id.listView);
listview.setAdapter(notesArrayAdapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
/**/
#Override
public void onItemClick(AdapterView<?> parent, final View view,
int position, long id) {
notes = (Notes) parent.getItemAtPosition(position);
Intent intent = new Intent(MainPage.this, SecondActivity.class);
intent.putExtra("Notes",notes);
startActivity(intent);
}
});
}
#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
switch (item.getItemId()) {
case R.id.new_link:
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra("Notes",(android.os.Parcelable)null);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
SecondActivity Class:
package com.example.prateeksharma.noteballondor;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
public class SecondActivity extends ActionBarActivity {
public SharedPreferences sharedPreferences;
SharedPreferences.Editor edit;
Notes notes;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
sharedPreferences = getSharedPreferences("com.example.prateeksharma.noteballondor", Context.MODE_PRIVATE);
edit = sharedPreferences.edit();
}
#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_second, menu);
return true;
}
#Override
protected void onResume() {
super.onResume();
Intent intent = getIntent();
notes = (Notes)intent.getParcelableExtra("Notes");
EditText editText = (EditText) findViewById(R.id.editText);
if(notes != null){
editText.setText(notes.getNoteText());
}
else{
editText.setText(null);
}
}
#Override
protected void onStop() {
super.onStop();
getIntent().removeExtra(notes.getNoteText());
}
#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();
Intent intent = getIntent();
//noinspection SimplifiableIfStatement
switch (item.getItemId()) {
case R.id.save:
EditText editText = (EditText)findViewById(R.id.editText);
if (notes != null){
edit.putInt(String.valueOf(editText.getText()),1);
}
else{
edit.putInt(String.valueOf(editText.getText()),0);
}
edit.commit();
return true;
case R.id.delete:
if(notes != null){
edit.remove(notes.getNoteText());
edit.commit();
finish();
return true;
}
default:
return super.onOptionsItemSelected(item);
}
}
}
Notes class that I'm using:
package com.example.prateeksharma.noteballondor;
import android.os.Parcel;
import android.os.Parcelable;
/**
* Created by Dell on 02-06-2015.
*/
public class Notes implements Parcelable {
private String noteText;
public String getNoteText() {
return noteText;
}
public void setNoteText(String noteText) {
this.noteText = noteText;
}
private Notes(Parcel in) {
noteText = in.readString();
}
public Notes(){
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(noteText);
}
#SuppressWarnings("unused")
public static final Parcelable.Creator<Notes> CREATOR = new Parcelable.Creator<Notes>() {
#Override
public Notes createFromParcel(Parcel in) {
return new Notes(in);
}
#Override
public Notes[] newArray(int size) {
return new Notes[size];
}
};
}
Can anybody tell me why this error is coming in MainActivity class at this line
if (entry.getValue() == 0)
Thank you..
Try to replace
if ((Integer)entry.getValue() == 0){
With
If((Integer.parseInt( entry.getValue()) ==0){
I have a WebView that is supposed to load the mobile version of a website, but when I try to load it inside the WebView it only appears as a white screen. I have tried loading the same URL in my android browser, and on my desktop with a User-Agent Switcher. I know the page is done loading also, because I have a method onPageFinished() that displays a toast when the page is displayed. Every time I load the application I am greeted with a white screen and then a few seconds later, the Toast message.
EDIT: I have tried different mobile web sites, and they all work in the WebView, the only one that is giving me trouble is this one: https://zangleweb01.clovisusd.k12.ca.us/StudentConnect/Home/Login
MainActivity.java
package com.student.connect;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.ActionBar;
import android.net.Uri;
import android.os.Bundle;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.support.v4.app.FragmentActivity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ArrayAdapter;
import android.widget.Toast;
public class MainActivity extends FragmentActivity implements
ActionBar.OnNavigationListener {
/**
* The serialization (saved instance state) Bundle key representing the
* current dropdown position.
*/
private static final String STATE_SELECTED_NAVIGATION_ITEM = "selected_navigation_item";
#SuppressWarnings("unused")
private WebView student_zangle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set up the action bar to show a dropdown list.
final ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
// Set up the dropdown list navigation in the action bar.
actionBar.setListNavigationCallbacks(
// Specify a SpinnerAdapter to populate the dropdown list.
new ArrayAdapter<String>(getActionBarThemedContextCompat(),
android.R.layout.simple_list_item_1,
android.R.id.text1, new String[] {
getString(R.string.title_section1),
getString(R.string.title_section2),
getString(R.string.title_section3), }), this);
}
/**
* Backward-compatible version of {#link ActionBar#getThemedContext()} that
* simply returns the {#link android.app.Activity} if
* <code>getThemedContext</code> is unavailable.
*/
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
private Context getActionBarThemedContextCompat() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
return getActionBar().getThemedContext();
} else {
return this;
}
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
// Restore the previously serialized current dropdown position.
if (savedInstanceState.containsKey(STATE_SELECTED_NAVIGATION_ITEM)) {
getActionBar().setSelectedNavigationItem(
savedInstanceState.getInt(STATE_SELECTED_NAVIGATION_ITEM));
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
// Serialize the current dropdown position.
outState.putInt(STATE_SELECTED_NAVIGATION_ITEM, getActionBar()
.getSelectedNavigationIndex());
}
#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;
}
#SuppressLint("NewApi")
#Override
public boolean onNavigationItemSelected(int position, long id)
{
WebView student_zangle = (WebView) findViewById(R.id.student_zangle);
student_zangle.setWebViewClient( new YourWebClient());
student_zangle.loadUrl("https://zangleweb01.clovisusd.k12.ca.us/StudentConnect/Home/Login");
student_zangle.setDrawingCacheEnabled(false);
WebSettings settings = student_zangle.getSettings();
student_zangle.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
settings.setJavaScriptEnabled(true);
settings.setJavaScriptCanOpenWindowsAutomatically(true);
settings.setAllowUniversalAccessFromFileURLs(true);
settings.setAllowContentAccess(true);
student_zangle.setDownloadListener(new DownloadListener()
{
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype, long contentLength)
{
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setType("application/x-rar-compressed");
intent.setData(Uri.parse(url));
startActivity(intent);
}
});
return true;
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
moveTaskToBack(true);
}
return super.onKeyDown(keyCode, event);
}
private class YourWebClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.contains("mailto"))
{
String mail = url.replaceFirst("mailto:", "");
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("message/rfc822");
intent.putExtra(Intent.EXTRA_EMAIL, mail );
startActivity(intent);
return true;
}
view.loadUrl(url);
return true;
}
public void onPageFinished(WebView view, String url)
{
Toast.makeText(getApplicationContext(), "done",
Toast.LENGTH_LONG).show();
}
}
}
Try buildDrawingCache with following changes:
student_zangle.setDrawingCacheEnabled(true);
student_zangle.buildDrawingCache();
Note : You should avoid calling this method when hardware acceleration is enabled
I am writing help system for my application. I use WebView inside AlertDialog. HTML Help pages are stored in assets/ directory and have link reference to each other.
Minimal code to reproduce problem:
package qa.so.wv;
import android.content.Context;
import android.app.AlertDialog;
import android.webkit.WebView;
import android.content.DialogInterface;
import android.view.ContextThemeWrapper;
import android.webkit.WebSettings;
import android.webkit.WebViewClient;
import android.widget.Toast;
public class DialogInformation {
public void showFile(Context context, String file) {
AlertDialog.Builder dialog = new AlertDialog.Builder(new ContextThemeWrapper(context, R.style.InformationDialogStyle));
final Context ctx = context;
final WebView wv = new WebView(context);
wv.setWebViewClient(
new WebViewClient(){
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
);
WebSettings settings = wv.getSettings();
settings.setDefaultTextEncodingName("utf-8");
wv.loadUrl(
"file:///android_asset/"+file
);
dialog.setView(wv);
dialog.setPositiveButton(
context.getString(R.string.cont),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}
);
dialog.setNeutralButton(
"Back",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (wv.isFocused() && wv.canGoBack()) {
wv.goBack();
} else {
Toast.makeText(
ctx,
"No go back for Back button",
Toast.LENGTH_LONG
).show();
}
}
}
);
dialog.setOnCancelListener(
new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
if (wv.isFocused() && wv.canGoBack()) {
wv.goBack();
} else {
Toast.makeText(
ctx,
"No go back for system return 'hardware' button",
Toast.LENGTH_LONG
).show();
}
}
}
);
dialog.show();
}
}
This class is used there:
package qa.so.wv;
import android.os.Bundle;
import android.app.ListActivity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.view.MenuItem;
import android.view.Menu;
import android.widget.Toast;
import android.webkit.WebView;
public class ShowArchive extends ListActivity
{
// options menu items constants
protected static final int MENU_HELP = Menu.FIRST+11;
protected static final int MENU_QUIT = Menu.FIRST+16;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
/* Create Menu Items */
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, MENU_HELP, 0, R.string.menu_help);
menu.add(0, MENU_QUIT, 0, R.string.menu_quit);
return true;
}
/* Handles Menu Item Selection */
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_HELP:
DialogInformation dn = new DialogInformation();
dn.showFile(
this,
getString(R.string.help_file)
);
return true;
case MENU_QUIT:
finish();
return true;
}
return false;
}
}
And two example pages from assets/ directory
page one:
<html>
link to 2-nd file"
<p>
Some text.
</p>
</html>
and page two:
<html>
<p>2-nd file</p>
</html>
I call "Help" from menu. Page one is displayed. I click to link. Page two correctly loaded.
When I click on "Back" button or hardware "Cancel" button Help dialog disappear instead of loading previously displayed page.
Help me solve this problem, please.
Try this
#Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (event.getKeyCode()) {
case KeyEvent.KEYCODE_BACK:
if(webView.canGoBack()) {
webView.goBack();
} else {
finish();
}
return true;
}
}
return super.dispatchKeyEvent(event);
}