[Q] PreferenceFragment - problems in changing language preference - Java for Android App Development

I have written the following code to allow user to display in chinese or english language. But when I select the language in the settings. There is no response and change in the App. I would like to ask if anyone could see the problems. Thank you for your help!
I have created the following folders
- values-en
- values-rTW
- values-rCN
Code:
public class AppPrefActivity extends Activity {
private SharedPreferences.OnSharedPreferenceChangeListener prefListener;
SharedPreferences pref;
public static final String PREF_LANGUAGE = "language_pref";
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
getFragmentManager().beginTransaction().replace(android.R.id.content, new PrefsFragement()).commit();
}
public static class PrefsFragement extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener{
@Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preference);
}
@Override
public void onResume() {
super.onResume();
getPreferenceManager().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
@Override
public void onPause() {
getPreferenceManager().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
super.onPause();
}
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if(key.equals(PREF_LANGUAGE))
{
Preference connectionPref = findPreference(key);
connectionPref.setSummary(sharedPreferences.getString(key, ""));
changeLanguagePref(sharedPreferences.getString(key, ""));
}
}
private void changeLanguagePref(String lang){
Locale locale = null;
if (lang.equals("Traditional Chinese")){
locale = new Locale("zh_rTW");
}else if (lang.equals("Simplified Chinese")){
locale = new Locale("zh_rCN");
}else{
locale = new Locale("en");
}
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
this.getResources().updateConfiguration(config, null);
}
}
}
This is part of the xml for language selection
Code:
<PreferenceCategory android:title="@string/pref_cat_app">
<ListPreference
android:title="@string/pref_def_lang"
android:entries="@array/app_language"
android:entryValues="@array/app_language"
android:defaultValue="English"
android:key="language_pref"/>

you need to recreate the activity after you reload all the resources.

Related

[source code] Viewpager containing preferencescreens

Hi,
since the compability package does not ship PreferenceListFragment, I built my own one, which I am using in my gtalk widget app.
I was asked for the source, so here it is. It's quite a hacky workaround..
Edit: Someone asked about the license: Use it however you like
Code:
public class PreferenceListFragment extends ListFragment{
private PreferenceManager mPreferenceManager;
/**
* The starting request code given out to preference framework.
*/
private static final int FIRST_REQUEST_CODE = 100;
private static final int MSG_BIND_PREFERENCES = 0;
private Handler mHandler = new Handler() {
[user=439709]@override[/user]
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_BIND_PREFERENCES:
bindPreferences();
break;
}
}
};
private ListView lv;
private int xmlId;
public PreferenceListFragment(int xmlId){
this.xmlId = xmlId;
}
//must be provided
public PreferenceListFragment(){
}
[user=439709]@override[/user]
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle b){
postBindPreferences();
return lv;
}
[user=439709]@override[/user]
public void onDestroyView(){
super.onDestroyView();
ViewParent p = lv.getParent();
if(p != null)
((ViewGroup)p).removeView(lv);
}
[user=439709]@override[/user]
public void onCreate(Bundle b) {
super.onCreate(b);
if(b != null)
xmlId = b.getInt("xml");
mPreferenceManager = onCreatePreferenceManager();
lv = (ListView) LayoutInflater.from(getActivity()).inflate(R.layout.preference_list_content, null);
lv.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
addPreferencesFromResource(xmlId);
postBindPreferences();
((OnPreferenceAttachedListener)getActivity()).onPreferenceAttached(getPreferenceScreen(), xmlId);
}
[user=439709]@override[/user]
public void onStop(){
super.onStop();
try{
Method m = PreferenceManager.class.getDeclaredMethod("dispatchActivityStop");
m.setAccessible(true);
m.invoke(mPreferenceManager);
}catch(Exception e){
e.printStackTrace();
}
}
[user=439709]@override[/user]
public void onDestroy() {
super.onDestroy();
lv = null;
try{
Method m = PreferenceManager.class.getDeclaredMethod("dispatchActivityDestroy");
m.setAccessible(true);
m.invoke(mPreferenceManager);
}catch(Exception e){
e.printStackTrace();
}
}
[user=439709]@override[/user]
public void onSaveInstanceState(Bundle outState) {
outState.putInt("xml", xmlId);
super.onSaveInstanceState(outState);
}
[user=439709]@override[/user]
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try{
Method m = PreferenceManager.class.getDeclaredMethod("dispatchActivityResult", int.class, int.class, Intent.class);
m.setAccessible(true);
m.invoke(mPreferenceManager, requestCode, resultCode, data);
}catch(Exception e){
e.printStackTrace();
}
}
/**
* Posts a message to bind the preferences to the list view.
* <p>
* Binding late is preferred as any custom preference types created in
* {@link #onCreate(Bundle)} are able to have their views recycled.
*/
private void postBindPreferences() {
if (mHandler.hasMessages(MSG_BIND_PREFERENCES)) return;
mHandler.obtainMessage(MSG_BIND_PREFERENCES).sendToTarget();
}
private void bindPreferences() {
final PreferenceScreen preferenceScreen = getPreferenceScreen();
if (preferenceScreen != null) {
preferenceScreen.bind(lv);
}
}
/**
* Creates the {@link PreferenceManager}.
*
* [user=2056652]@return[/user] The {@link PreferenceManager} used by this activity.
*/
private PreferenceManager onCreatePreferenceManager() {
try{
Constructor<PreferenceManager> c = PreferenceManager.class.getDeclaredConstructor(Activity.class, int.class);
c.setAccessible(true);
PreferenceManager preferenceManager = c.newInstance(this.getActivity(), FIRST_REQUEST_CODE);
return preferenceManager;
}catch(Exception e){
e.printStackTrace();
return null;
}
}
/**
* Returns the {@link PreferenceManager} used by this activity.
* [user=2056652]@return[/user] The {@link PreferenceManager}.
*/
public PreferenceManager getPreferenceManager() {
return mPreferenceManager;
}
/**
* Sets the root of the preference hierarchy that this activity is showing.
*
* [user=955119]@param[/user] preferenceScreen The root {@link PreferenceScreen} of the preference hierarchy.
*/
public void setPreferenceScreen(PreferenceScreen preferenceScreen){
try{
Method m = PreferenceManager.class.getDeclaredMethod("setPreferences", PreferenceScreen.class);
m.setAccessible(true);
boolean result = (Boolean) m.invoke(mPreferenceManager, preferenceScreen);
if (result && preferenceScreen != null) {
postBindPreferences();
}
}catch(Exception e){
e.printStackTrace();
}
}
/**
* Gets the root of the preference hierarchy that this activity is showing.
*
* [user=2056652]@return[/user] The {@link PreferenceScreen} that is the root of the preference
* hierarchy.
*/
public PreferenceScreen getPreferenceScreen(){
try{
Method m = PreferenceManager.class.getDeclaredMethod("getPreferenceScreen");
m.setAccessible(true);
return (PreferenceScreen) m.invoke(mPreferenceManager);
}catch(Exception e){
e.printStackTrace();
return null;
}
}
/**
* Adds preferences from activities that match the given {@link Intent}.
*
* [user=955119]@param[/user] intent The {@link Intent} to query activities.
*/
public void addPreferencesFromIntent(Intent intent) {
throw new RuntimeException("too lazy to include this bs");
}
/**
* Inflates the given XML resource and adds the preference hierarchy to the current
* preference hierarchy.
*
* [user=955119]@param[/user] preferencesResId The XML resource ID to inflate.
*/
public void addPreferencesFromResource(int preferencesResId) {
try{
Method m = PreferenceManager.class.getDeclaredMethod("inflateFromResource", Context.class, int.class, PreferenceScreen.class);
m.setAccessible(true);
PreferenceScreen prefScreen = (PreferenceScreen) m.invoke(mPreferenceManager, getActivity(), preferencesResId, getPreferenceScreen());
setPreferenceScreen(prefScreen);
}catch(Exception e){
e.printStackTrace();
}
}
/**
* Finds a {@link Preference} based on its key.
*
* [user=955119]@param[/user] key The key of the preference to retrieve.
* [user=2056652]@return[/user] The {@link Preference} with the key, or null.
* [user=690402]@see[/user] PreferenceGroup#findPreference(CharSequence)
*/
public Preference findPreference(CharSequence key) {
if (mPreferenceManager == null) {
return null;
}
return mPreferenceManager.findPreference(key);
}
public interface OnPreferenceAttachedListener{
public void onPreferenceAttached(PreferenceScreen root, int xmlId);
}
}
How to use:
Code:
public class Settings extends FragmentActivity implements OnPreferenceAttachedListener, OnPreferenceChangeListener, OnPreferenceClickListener{
private Preference filterPref;
private ViewPager viewPager;
public void onCreate(Bundle b){
super.onCreate(b);
setContentView(R.layout.settings);
viewPager = (ViewPager) findViewById(R.id.pager);
PagerAdapter adapter = new PagerAdapter(getSupportFragmentManager(), this);
viewPager.setAdapter(adapter);
TitlePageIndicator titleIndicator = (TitlePageIndicator) findViewById(R.id.titles);
titleIndicator.setViewPager(viewPager);
titleIndicator.setFooterIndicatorStyle(IndicatorStyle.Underline);
viewPager.setCurrentItem(1);
}
//setup your onPreferenceClickListener/onPreferenceChangeListener here
[user=439709]@override[/user]
public void onPreferenceAttached(PreferenceScreen root, int xmlId){
if(root == null)
return; //for whatever reason in very rare cases this is null
if(xmlId == R.xml.widget_settings){ //example id
root.findPreference("somePreference").setOnPreferenceClickListener(this);
}
}
//handle your preferenceChanged events here (if needed)
[user=439709]@override[/user]
public boolean onPreferenceChange(Preference preference, Object newValue) {
return true;
}
//handle your preferenceClick events here (if needed)
[user=439709]@override[/user]
public boolean onPreferenceClick(Preference pref){
return true;
}
}
and the adapter I am using:
Code:
public class PagerAdapter extends FragmentPagerAdapter implements TitleProvider{
PreferenceListFragment[] fragments;
String[] titles;
public PagerAdapter(FragmentManager fm, Context context) {
super(fm);
fragments = new PreferenceListFragment[4];
fragments[0] = new PreferenceListFragment(R.xml.settings);
fragments[1] = new PreferenceListFragment(R.xml.widget_settings);
fragments[2] = new PreferenceListFragment(R.xml.s_widget_settings);
fragments[3] = new PreferenceListFragment(R.xml.color_settings);
titles = new String[4];
titles[0] = context.getString(R.string.main_settings);
titles[1] = context.getString(R.string.widget_settings);
titles[2] = context.getString(R.string.s_widget_settings);
titles[3] = context.getString(R.string.color_settings_main);
}
[user=439709]@override[/user]
public Fragment getItem(int position){
return fragments[position];
}
[user=439709]@override[/user]
public int getCount() {
return fragments.length;
}
[user=439709]@override[/user]
public String getTitle(int position) {
return titles[position];
}
}
Lastly you will need this xml file: preference_list_content.xml (belongs into /res/layout/) (pulled from aosp)
Code:
<?xml version="1.0" encoding="utf-8"?>
<!--
/* //device/apps/common/assets/res/layout/list_content.xml
**
** Copyright 2006, The Android Open Source Project
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
-->
<ListView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:drawSelectorOnTop="false"
android:scrollbarAlwaysDrawVerticalTrack="true"
/>
Thanks for sharing.
=]
Thank you for sharing!
THANK YOU, much appropriated
Working fine on my devices (Nexus S and GNex), but received logs with crashes here:
Code:
((OnPreferenceAttachedListener)getActivity()).onPreferenceAttached(getPreferenceScreen(), xmlId);
NullPointerException here:
Code:
@Override
public void onPreferenceAttached(PreferenceScreen root, int xmlId) {
List<PreferenceScreen> rootPref=new ArrayList<PreferenceScreen>() ;
rootPref.add(root);
root.getSharedPreferences().registerOnSharedPreferenceChangeListener(
this);
hm, I received logs, that the listview is null when bindPreferences() is called. =/
thank you, i will use this on my application NSTools
Hello, i ma new at this and i am trying to understand the code, what exactly are "R.array.display_filter_array" and "R.layout.preference_list_content", these are the only things i have left to try this code, hope you can help me
Thank you
I added the missing layout file in the first post.
I also added a check for nullpointer in onPreferenceAttached().
R.array.display_filter_array correspondends to a string array I defined.
getResources().getStringArray(int stringId) will return an array of localized strings defined in res/values/strings.xml.
Thank you so much for this! I've been wracking my brain for a long time to come up with a way to use a PreferenceFragment on pre-Honeycomb devices, and this fits my needs exactly. So much love.
I'll let you know if I run across any issues.
Hi.
First I'd like to thank you for sharing this.
I have an issue with this : each preference row is only taking the width it's really nead, instead of using all width available like any Preference view. The result is kinda ugly (widgets of preferences not aligned in the right and click area way too little).
But if I start a new Activity and come back, they are well displayed. The only difference between the code I use and yours is I don't use a ViewPage, I directly use the ListFragment as Fragment.
Can someone help me please ?
Thanks in advance.
Hey guys, I just wanted to share a different initialization scheme. I couldn't get the activity to survive orientation change without fc. So i came up with this...
Extended PreferenceFragment
Code:
package org.teameos.settings.device;
import android.os.Bundle;
public class DiagPreferences extends PreferenceListFragment {
public static DiagPreferences newInstance(int xml) {
DiagPreferences f = new DiagPreferences(xml);
Bundle b = new Bundle();
b.putInt("xml", xml);
f.setArguments(b);
return f;
}
public DiagPreferences(int xmlId) {
// TODO Auto-generated constructor stub
super(xmlId);
}
public DiagPreferences() {
super();
}
The adapter
Code:
public ViewPagerAdapter(Context context, FragmentManager fm) {
super(fm);
mContext = context;
mFragments = new ArrayList<Pair<Fragment, String>>();
mFragments.add(Pair.create(
(Fragment) UpdatesPreferences.newInstance(R.xml.updates_and_menus),
mContext.getString(R.string.eos_ota_menus)));
mFragments.add(Pair.create((Fragment) DiagPreferences.newInstance(R.xml.diagnostics),
mContext.getString(R.string.eos_diag)));
mFragments.add(Pair.create((Fragment) PrlPreferences.newInstance(R.xml.prl_management),
mContext.getString(R.string.prl_management)));
}
using the above code (you cant use constructors) and using newInstance its not working
you need modify this in Oncreate
Code:
super.onCreate(b);
if(b != null){
xmlId = b.getInt("xml");
}else
{
xmlId = getArguments().getInt("xml");
}
This code gave me a warning about memory leak we shouls use WeakReference or use as static
Code:
private Handler mHandler = new Handler() {
[user=439709]@override[/user]
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_BIND_PREFERENCES:
bindPreferences();
break;
}
}
};
like this:
Code:
private [B][COLOR="Red"]static[/COLOR] [/B]Handler mHandler = new Handler() {
[user=439709]@override[/user]
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_BIND_PREFERENCES:
bindPreferences();
break;
}
}
};
and in all "dependencies" of that function like bindPreferences and so on.
Ps AMAZING Work BTW thanks a lot
Great code, but I can't find TitleProvider anywhere... I believe it used to be part of PagerViewer? How to remove this?

Help JazzyViewPager and FragmentStatePagerAdapter

The problem is that the transitions wont work but all over the app is working fine. It's just the transition effects that aren't working. I've already tried all of them but no luck, the slides have their default transition. There are no errors in the codes too so I don't know what I've done wrong so please help. This is also my first app so please be kind. I didn't include the instantiateitem on pageradapter because if I do there will be a nullpointerexception. :/ I'm using JazzyViewPager for the transitions and Fragment State Pager Adapter. I've also searched for possible topics that might help me but none of them worked.
Main Activity:
Code:
public class MainActivity extends FragmentActivity {
private JazzyViewPager mJazzy;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setupJazziness(TransitionEffect.CubeIn);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add("Toggle Fade");
String[] effects = this.getResources().getStringArray(R.array.jazzy_effects);
for (String effect : effects)
menu.add(effect);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getTitle().toString().equals("Toggle Fade")) {
mJazzy.setFadeEnabled(!mJazzy.getFadeEnabled());
} else {
TransitionEffect effect = TransitionEffect.valueOf(item.getTitle().toString());
setupJazziness(effect);
}
return true;
}
private void setupJazziness(TransitionEffect effect) {
mJazzy = (JazzyViewPager) findViewById(R.id.jazzy_pager);
mJazzy.setTransitionEffect(effect);
mJazzy.setAdapter(new FragmentAdapter(getSupportFragmentManager()));
mJazzy.setPageMargin(30);
}
FragmentStatePagerAdapter:
Code:
public class FragmentAdapter extends FragmentStatePagerAdapter{
public FragmentAdapter(FragmentManager fm) {
super(fm);
// TODO Auto-generated constructor stub
}
@Override
public Fragment getItem(int position)
{
// TODO Auto-generated method stub
Fragment fragment = new Fragment1();
switch(position){
case 0:
fragment = new Fragment1();
break;
case 1:
fragment = new Fragment2();
break;
case 2:
fragment = new Fragment3();
break;
}
return fragment;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return 3;
}
@Override
public boolean isViewFromObject(View view, Object object) {
if(object != null){
return ((Fragment)object).getView() == view;
}else{
return false;
}
}
}
Fragment1:
Code:
public class Fragment1 extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.fragment1_layout, null);
return v;
}
activity_main xml:
Code:
<com.jfeinstein.jazzyviewpager.JazzyViewPager xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:app1="http://schemas.android.com/apk/res/com.eight.yamjay"
android:id="@+id/jazzy_pager"
app1:style="cubeout"
android:layout_width="match_parent"
android:layout_height="match_parent" />
This is the guide that I've been following.

Passing data between two fragments

Hello guys,
I have a list of fragments created and I want to delete these fragment by long pressing on them. However, before doing so I want dialog fragment to pop up and offer the user the choice to delete or not. I have created the two fragments but I can't get the data across each other. I can't give functionality to the 'OK' button. Here is my code:
Code:
public class CourseListFragment extends Fragment implements
OnItemClickListener, OnItemLongClickListener {
public static final String ARG_ITEM_ID = "course_list";
public static final String YES_NO = "modify";
Activity activity;
ListView courseListView;
ArrayList<Course> courses;
CourseListAdapter courseListAdapter;
CourseDAO courseDAO;
private GetEmpTask task;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activity = getActivity();
courseDAO = new CourseDAO(activity);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.schedule_fragment_course_list,
container, false);
findViewsById(view);
task = new GetEmpTask(activity);
task.execute((Void) null);
courseListView.setOnItemClickListener(this);
courseListView.setOnItemLongClickListener(this);
return view;
}
private void findViewsById(View view) {
courseListView = (ListView) view.findViewById(R.id.list_course);
}
@Override
public void onItemClick(AdapterView<?> list, View view, int position,
long id) {
Course course = (Course) list.getItemAtPosition(position);
if (course != null) {
Bundle arguments = new Bundle();
arguments.putParcelable("selectedCourse", course);
CustomCourseDialogFragment customEmpDialogFragment = new CustomCourseDialogFragment();
customEmpDialogFragment.setArguments(arguments);
customEmpDialogFragment.show(getFragmentManager(),
CustomCourseDialogFragment.ARG_ITEM_ID);
}
}
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
// Show dialogFragment
FragmentManager fm = getActivity().getSupportFragmentManager();
CheckDialogFragment dialog = new CheckDialogFragment();
dialog.show(fm, YES_NO);
Course employee = (Course) parent.getItemAtPosition(position);
// Use AsyncTask to delete from database
courseDAO.deleteEmployee(employee);
courseListAdapter.remove(employee);
return true;
}
public class GetEmpTask extends AsyncTask<Void, Void, ArrayList<Course>> {
private final WeakReference<Activity> activityWeakRef;
public GetEmpTask(Activity context) {
this.activityWeakRef = new WeakReference<Activity>(context);
}
@Override
protected ArrayList<Course> doInBackground(Void... arg0) {
ArrayList<Course> courseList = courseDAO.getCourses();
return courseList;
}
@Override
protected void onPostExecute(ArrayList<Course> empList) {
if (activityWeakRef.get() != null
&& !activityWeakRef.get().isFinishing()) {
courses = empList;
if (empList != null) {
if (empList.size() != 0) {
courseListAdapter = new CourseListAdapter(activity,
empList);
courseListView.setAdapter(courseListAdapter);
} else {
Toast.makeText(activity, "No Course Records",
Toast.LENGTH_LONG).show();
}
}
}
}
}
/*
* This method is invoked from MainActivity onFinishDialog() method. It is
* called from CustomEmpDialogFragment when an employee record is updated.
* This is used for communicating between fragments.
*/
public void updateView() {
task = new GetEmpTask(activity);
task.execute((Void) null);
}
@Override
public void onResume() {
getActivity().setTitle("Course Schedule");
getActivity().getActionBar().setTitle("Course Schedule");
super.onResume();
}
}
//Dialog Fragment
Code:
public class CheckDialogFragment extends DialogFragment {
CourseListAdapter courseListAdapter;
CourseDAO courseDAO;
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// TODO Auto-generated method stub
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity())
.setTitle("Do you want to delete?")
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
}
})
.setNegativeButton(android.R.string.cancel,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
dialog.cancel();
}
});
return builder.create();
}
}
I have problems trying to get the data from onItemLongClick() of CourseListFragment to CourseListFragment. Any help would be greatly appreciated.

[Q] Changing to another Activity when pressing on a Gridviewpager

I am trying to start a new certain Activity based on which page I am clicking on in a Gridview.
I tried to understand the Sample GridViewPager which is coming along with the sdk and trying to adapt the given explanation on stackoverflow (question # 26343337). But I really don't know how to bring these two things together and even where to start.
The first java.file Selection
Code:
public class Selection extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.selection_grid);
final GridViewPager pager = (GridViewPager) findViewById(R.id.pager);
pager.setAdapter(new Workers(this, getFragmentManager()));
DotsPageIndicator dotsPageIndicator = (DotsPageIndicator) findViewById(R.id.page_indicator);
dotsPageIndicator.setPager(pager);
}
}
and the second java.file Users (thats the Adapter):
Code:
public class Users extends FragmentGridPagerAdapter {
private static final int TRANSITION_DURATION_MILLIS = 100;
private final Context mContext;
private List<Row> mRows;
private ColorDrawable mDefaultBg;
private ColorDrawable mClearBg;
public Users (Context ctx, FragmentManager fm) {
super(fm);
mContext = ctx;
mRows = new ArrayList<Workers.Row>();
mRows.add(new Row(cardFragment(R.string.title, R.string.user1)));
mRows.add(new Row(cardFragment(R.string.title, R.string.user2)));
mRows.add(new Row(cardFragment(R.string.title, R.string.user3)));
mRows.add(new Row(cardFragment(R.string.title, R.string.user4)));
// In case in one row several cardFragments are needed
// mRows.add(new Row(
// cardFragment(R.string.cards_title, R.string.cards_text),
// cardFragment(R.string.expansion_title, R.string.expansion_text)));
mDefaultBg = new ColorDrawable(R.color.dark_grey);
mClearBg = new ColorDrawable(android.R.color.transparent);
}
LruCache<Integer, Drawable> mRowBackgrounds = new LruCache<Integer, Drawable>(3) {
@Override
protected Drawable create(final Integer row) {
int resid = BG_IMAGES[row % BG_IMAGES.length];
new DrawableLoadingTask(mContext) {
@Override
protected void onPostExecute(Drawable result) {
TransitionDrawable background = new TransitionDrawable(new Drawable[] {
mDefaultBg,
result
});
mRowBackgrounds.put(row, background);
notifyRowBackgroundChanged(row);
background.startTransition(TRANSITION_DURATION_MILLIS);
}
}.execute(resid);
return mDefaultBg;
}
};
private Fragment cardFragment(int titleRes, int textRes) {
Resources res = mContext.getResources();
CardFragment fragment =
CardFragment.create(res.getText(titleRes), res.getText(textRes));
// Add some extra bottom margin to leave room for the page indicator
fragment.setCardMarginBottom(
res.getDimensionPixelSize(R.dimen.card_margin_bottom));
return fragment;
}
static final int[] BG_IMAGES = new int[] {
R.drawable.user1,
R.drawable.user2,
R.drawable.user3,
R.drawable.user4
};
/** A convenient container for a row of fragments. */
private class Row {
final List<Fragment> columns = new ArrayList<Fragment>();
public Row(Fragment... fragments) {
for (Fragment f : fragments) {
add(f);
}
}
public void add(Fragment f) {
columns.add(f);
}
Fragment getColumn(int i) {
return columns.get(i);
}
public int getColumnCount() {
return columns.size();
}
}
@Override
public Fragment getFragment(int row, int col) {
Row adapterRow = mRows.get(row);
return adapterRow.getColumn(col);
}
@Override
public Drawable getBackgroundForRow(final int row) {
return mRowBackgrounds.get(row);
}
@Override
public int getRowCount() {
return mRows.size();
}
@Override
public int getColumnCount(int rowNum) {
return mRows.get(rowNum).getColumnCount();
}
class DrawableLoadingTask extends AsyncTask<Integer, Void, Drawable> {
private static final String TAG = "Loader";
private Context context;
DrawableLoadingTask(Context context) {
this.context = context;
}
@Override
protected Drawable doInBackground(Integer... params) {
Log.d(TAG, "Loading asset 0x" + Integer.toHexString(params[0]));
return context.getResources().getDrawable(params[0]);
}
}
}

[Volley] Main UI extremely slow

In my app i just have a splash screen and a main activity. In the main thread i have three EditText boxes and a spinner with a string array. On clicking the Button, input from three EditText and spinner selection is posted to my mysql database. For the button click network operation, i used Volley since its east and i dont have to use AsyncTask which am not familiar with.
Apart from this, on entering the main UI .. app first check for network connectivity using ConnectivityManager class. After onClick app checks for empty/invalid imputs using TextUtils.
Now the problem is that when i run my app, its very slow and taking upto 65mb of RAM. IS something wrong with my code. Should i run something else as AsynTask ? Can someone check my code and refine it .. thank you
SplashActivity.java
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
public class SplashActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
int SPLASH_TIME_OUT = 5000;
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Intent i = new Intent(SplashActivity.this, MainActivity.class);
startActivity(i);
finish();
}
}, SPLASH_TIME_OUT);
}
}
Click to expand...
Click to collapse
MainActivity.java
Code:
public class MainActivity extends Activity {
EditText name, phonenumber, address;
Button insert;
RequestQueue requestQueue;
Spinner spinner;
String insertUrl = "localhost";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Spinner s = (Spinner) findViewById(R.id.spinner);
s.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
/* CHECK INTERNET CONNECTION */
boolean mobileNwInfo;
ConnectivityManager conxMgr = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
try { mobileNwInfo = conxMgr.getActiveNetworkInfo().isConnected(); }
catch (NullPointerException e) { mobileNwInfo = false; }
if (!mobileNwInfo) {
Toast.makeText(this, "No Network, please check your connection. ", Toast.LENGTH_LONG).show();
}
/* CHECK INTERNET CONNECTION PROCEDURE DONE */
name = (EditText) findViewById(R.id.editText);
phonenumber= (EditText) findViewById(R.id.editText2);
address = (EditText) findViewById(R.id.editText3);
insert = (Button) findViewById(R.id.insert);
requestQueue = Volley.newRequestQueue(getApplicationContext());
spinner = (Spinner) findViewById(R.id.spinner);
insert.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
/* CHECK EMPTY STRING */
EditText txtUserName = (EditText) findViewById(R.id.editText);
EditText txtUserAddress = (EditText) findViewById(R.id.editText3);
EditText txtUserPhone = (EditText) findViewById(R.id.editText2);
String strUserName = name.getText().toString();
String strUserAddress = address.getText().toString();
String strUserPhone = phonenumber.getText().toString();
if(TextUtils.isEmpty(strUserName)) {
txtUserName.setError("You can't leave this empty.");
return;
}
if(TextUtils.isEmpty(strUserPhone)) {
txtUserPhone.setError("You can't leave this empty.");
return;
}
if(TextUtils.isEmpty(strUserPhone) || strUserPhone.length() < 10) {
txtUserPhone.setError("Enter a valid phone number.");
return;
}
if(TextUtils.isEmpty(strUserAddress)) {
txtUserAddress.setError("You can't leave this empty.");
return;
}
/* LOADING PROCESS DIALOG */
final ProgressDialog pd = new ProgressDialog(MainActivity.this);
pd.setMessage("Booking Service ....");
pd.show();
/* REQUEST RESPONSE/ERROR */
StringRequest request = new StringRequest(Request.Method.POST, insertUrl, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
pd.hide();
System.out.println(response);
name.setText("");
phonenumber.setText("");
address.setText("");
Toast.makeText(getApplicationContext(), "Service successfully booked !!", Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
pd.hide();
Toast.makeText(getApplicationContext(), "Error: Please try again later.", Toast.LENGTH_LONG).show();
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> parameters = new HashMap<>();
parameters.put("name", name.getText().toString());
parameters.put("phonenumber", phonenumber.getText().toString());
parameters.put("address", address.getText().toString());
parameters.put("service", spinner.getItemAtPosition(spinner.getSelectedItemPosition()).toString());
return parameters;
}
};
requestQueue.add(request);
}
});
}
}
Well it's hard to say what exactly is wrong with it. Maybe text is to long. You can try to measure each operation performance with System.nanoseconds(easiest) and localize the problem first. It would be easier to say what to do with it.
Yes you should try to figure out what part is causing the problem. Try to cut the code down to essentials and measure the execution time. Maybe you will be able to tell what part exactly is not working as wanted.

Categories

Resources