[source code] Viewpager containing preferencescreens - Android Software Development

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?

Related

hosting widget in my app

I already have a working code that shows up a selected widget in my app, but the thing is how would I use the selected widget to show up in other activities in my app??? please if any1 know share the knowledge. thanks in advance.
this is the 100% working code:
Code:
static final String TAG = "WidgetHostExampleActivity";
AppWidgetManager mAppWidgetManager;
AppWidgetHost mAppWidgetHost;
RelativeLayout mainlayout;
/**
* Called on the creation of the activity.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainlayout = (RelativeLayout) findViewById(R.id.main_layout);
mAppWidgetManager = AppWidgetManager.getInstance(this);
mAppWidgetHost = new AppWidgetHost(this, R.id.APPWIDGET_HOST_ID);
}
/**
* Launches the menu to select the widget. The selected widget will be on
* the result of the activity.
*/
void selectWidget() {
int appWidgetId = this.mAppWidgetHost.allocateAppWidgetId();
Intent pickIntent = new Intent(AppWidgetManager.ACTION_APPWIDGET_PICK);
pickIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
addEmptyData(pickIntent);
startActivityForResult(pickIntent, R.id.REQUEST_PICK_APPWIDGET);
}
/**
* This avoids a bug in the com.android.settings.AppWidgetPickActivity,
* which is used to select widgets. This just adds empty extras to the
* intent, avoiding the bug.
*
* See more: [url]http://code.google.com/p/android/issues/detail?id=4272[/url]
*/
void addEmptyData(Intent pickIntent) {
ArrayList<AppWidgetProviderInfo> customInfo = new ArrayList<AppWidgetProviderInfo>();
pickIntent.putParcelableArrayListExtra(AppWidgetManager.EXTRA_CUSTOM_INFO, customInfo);
ArrayList<Bundle> customExtras = new ArrayList<Bundle>();
pickIntent.putParcelableArrayListExtra(AppWidgetManager.EXTRA_CUSTOM_EXTRAS, customExtras);
}
/**
* If the user has selected an widget, the result will be in the 'data' when
* this function is called.
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == R.id.REQUEST_PICK_APPWIDGET) {
configureWidget(data);
} else if (requestCode == R.id.REQUEST_CREATE_APPWIDGET) {
createWidget(data);
}
} else if (resultCode == RESULT_CANCELED && data != null) {
int appWidgetId = data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
if (appWidgetId != -1) {
mAppWidgetHost.deleteAppWidgetId(appWidgetId);
}
}
}
/**
* Checks if the widget needs any configuration. If it needs, launches the
* configuration activity.
*/
private void configureWidget(Intent data) {
Bundle extras = data.getExtras();
int appWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
AppWidgetProviderInfo appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(appWidgetId);
if (appWidgetInfo.configure != null) {
Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_CONFIGURE);
intent.setComponent(appWidgetInfo.configure);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
startActivityForResult(intent, R.id.REQUEST_CREATE_APPWIDGET);
} else {
createWidget(data);
}
}
/**
* Creates the widget and adds to our view layout.
*/
public void createWidget(Intent data) {
Bundle extras = data.getExtras();
int appWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
AppWidgetProviderInfo appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(appWidgetId);
AppWidgetHostView hostView = mAppWidgetHost.createView(this, appWidgetId, appWidgetInfo);
hostView.setAppWidget(appWidgetId, appWidgetInfo);
mainlayout.addView(hostView);
Log.i(TAG, "The widget size is: " + appWidgetInfo.minWidth + "*" + appWidgetInfo.minHeight);
}
/**
* Registers the AppWidgetHost to listen for updates to any widgets this app
* has.
*/
@Override
protected void onStart() {
super.onStart();
mAppWidgetHost.startListening();
}
/**
* Stop listen for updates for our widgets (saving battery).
*/
@Override
protected void onStop() {
super.onStop();
mAppWidgetHost.stopListening();
}
/**
* Removes the widget displayed by this AppWidgetHostView.
*/
public void removeWidget(AppWidgetHostView hostView) {
mAppWidgetHost.deleteAppWidgetId(hostView.getAppWidgetId());
mainlayout.removeView(hostView);
}
/**
* Handles the menu.
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.i(TAG, "Menu selected: " + item.getTitle() + " / " + item.getItemId() + " / " + R.id.addWidget);
switch (item.getItemId()) {
case R.id.addWidget:
selectWidget();
return true;
case R.id.removeWidget:
removeWidgetMenuSelected();
return false;
}
return super.onOptionsItemSelected(item);
}
/**
* Handle the 'Remove Widget' menu.
*/
public void removeWidgetMenuSelected() {
int childCount = mainlayout.getChildCount();
if (childCount > 1) {
View view = mainlayout.getChildAt(childCount - 1);
if (view instanceof AppWidgetHostView) {
removeWidget((AppWidgetHostView) view);
Toast.makeText(this, R.string.widget_removed_popup, Toast.LENGTH_SHORT).show();
return;
}
}
Toast.makeText(this, R.string.no_widgets_popup, Toast.LENGTH_SHORT).show();
}
/**
* Creates the menu with options to add and remove widgets.
*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}

[Q] GPS with Fragment

Good day. I start learn Fragment and I want use GPS in my Application. and I use Fragment. in fragment who view coordinate i writed next code
Code:
public class MyFragment2 extends Fragment {
public static final String BUTTON_INDEX = "button_index";
private static final int BUTTON_INDEX_DEFAULT = -1;
static TextView txt;
static TextView txt2;
String[] mCatDescription;
public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle saveInstanceState){
View viewHier = inflater.inflate(R.layout.fragment2, container, false);
txt = (TextView)viewHier.findViewById(R.id.textView1);
txt2 = (TextView)viewHier.findViewById(R.id.textView2);
mCatDescription =getResources().getStringArray(R.array.cats);
Bundle args = getArguments();
int buttonIndex = args != null ? args.getInt(BUTTON_INDEX, BUTTON_INDEX_DEFAULT):BUTTON_INDEX_DEFAULT;
if(buttonIndex != BUTTON_INDEX_DEFAULT){
setDiscription(buttonIndex);
}
return viewHier;
}
public void setDiscription(int buttonIndex){
GPSWork gpsWork = new GPSWork();
switch(buttonIndex){
case 1:
txt2.setText("one");
break;
case 2:
gpsWork.GetCoordinates();
break;
case 3:
txt2.setText("therd");
break;
}
}
}
Ok. when we click on button 2 we call method GetCoordinates(). this class have next code
Code:
public class GPSWork{
LocationManager locationManager;
public GPSWork(){
locationManager = (LocationManager)MainActivity.mContext.getSystemService(Context.LOCATION_SERVICE);
}
public void GetCoordinates(){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
5000, 5, locationListener);
}
private LocationListener locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
MyFragment2.txt2.setText("OK");
}
@Override
public void onProviderDisabled(String provider) {
MyFragment2.txt2.setText("OK");
}
@Override
public void onProviderEnabled(String provider) {
MyFragment2.txt2.setText("OK");
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
MyFragment2.txt2.setText("OK");
}
};
}
how we see, we should get text OK on TextView on MainActivity. but we don't have text, whats wrong? and if I change code in method GetCoordinates() on
Code:
public void GetCoordinates(){
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
1000, 10, locationListener);
}
all work fine, i see text in TextView (OK )

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