Hello Boys,
I am a new Android developer and I'm developing an app with the API of Google Maps.
Into an area of the map I place many markers.
The application works correctly, but the map scroolling and the map zoom isn't quick, everything goes slow.
The marker that I have included in the map is in the "png" format image, and his weighs is approximately 600 bytes.
it is possible that many marker object cause low map scrool?
this is the code of my APP:
Code:
plublic class IDC extends MapActivity {
private LocationManager locationManager;
private LocationListener locationListener;
private MapController mc;
private MapView mapView;
private String myPosition;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String errore="";
myPosition="";
try{
mapView = (MapView) findViewById(R.id.mapview);
mc = mapView.getController();
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationListener = new GPSLocationListener();
//getMyLocation();
MyDBHelper myDB = new MyDBHelper(IDS.this);
Cursor cursor= myDB.query(new String[] { "x", "y", "y2", "w", "k", "latitude", "longitude"});
//Log.i("NOMI", "TOT. NOMI"+cursor.getCount());
List<Overlay> mapOverlays = mapView.getOverlays();
Drawable drawable = this.getResources().getDrawable(R.drawable.mm_20_blue);
MyItemizedOverlay itemizedoverlay = new MyItemizedOverlay(drawable,IDS.this);
List<Address> address = new ArrayList<Address>();
Log.i("TOT TUPLE", " = "+cursor.getCount());
while(cursor.moveToNext()){
String s= cursor.getString(0);
errore=s;
String nome[]=s.split("-");
// Log.i("Pos Colonna NOME", ""+cursor.getColumnIndex("nome"));
// Log.i("Pos. in Colonna", ""+cursor.getString(0));
//address.addAll(gc.getFromLocationName(nome[1], 1));
//Address a= address.get(address.size()-1);
String la=cursor.getString(5);
String lo=cursor.getString(6);
double latitude= Double.parseDouble(la);
double longitude= Double.parseDouble(lo);
int lan= (int)(latitude*1E6);
int lon= (int)(longitude*1E6);
GeoPoint point = new GeoPoint(lan, lon);
String tel1=cursor.getString(1);
String tel2=cursor.getString(2);
String mail=cursor.getString(4);
String web=cursor.getString(3);
String info[]= {tel1,tel2,nome[1],web,mail};
MyOverlayItem overlayitem = new MyOverlayItem(point, "Hello", nome[0], info);
//mc.animateTo(point);
itemizedoverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedoverlay);
}
mapView.setBuiltInZoomControls(true);
mc.setZoom(6);
}catch (Exception e) {
e.printStackTrace();
}
}
}
Code:
public class MyItemizedOverlay extends ItemizedOverlay {
private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
private Context mContext;
private CustomizeDialog customizeDialog;
public MyItemizedOverlay(Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
}
public MyItemizedOverlay(Drawable defaultMarker, Context context) {
super(boundCenterBottom(defaultMarker));
mContext = context;
}
protected boolean onTap(int index)
MyOverlayItem item = (MyOverlayItem) mOverlays.get(index);
customizeDialog = new CustomizeDialog(mContext);
customizeDialog.setPersonalText(item.getSnippet());
String []info= item.getInfo();
customizeDialog.setT1(info[0]);
customizeDialog.setT2(info[1]);
customizeDialog.setA(info[2]);
customizeDialog.setW(info[3]);
customizeDialog.setM(info[4]);
customizeDialog.show();
return true;
}
protected OverlayItem createItem(int i) {
return mOverlays.get(i);
}
public int size() {
return mOverlays.size();
}
public void addOverlay(OverlayItem overlay) {
mOverlays.add(overlay);
populate();
}
}
what is the problem??....PLEASE, HELP ME!!
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?
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;
}
I am trying to convert a WidgetHostActivity to Fragment but i get an error when i am trying to open WidgetManager. Here is the convert i have done so far (without OnStart and OnStop)...
Code:
public class FragmentBlue extends Fragment implements OnLongClickListener
{
static final String TAG = "FragmentBlue";
public static final int RESULT_OK = -1;
public static final int RESULT_CANCELED = 0;
AppWidgetManager mAppWidgetManager;
AppWidgetHost mAppWidgetHost;
ViewGroup mainlayout;
TextView text;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_blue, container, false);
mainlayout = (ViewGroup) view.findViewById(R.id.main_layout);
text = (TextView)view.findViewById(R.id.tvtext);
mainlayout.setOnLongClickListener(this);
mAppWidgetManager = AppWidgetManager.getInstance(getActivity());
mAppWidgetHost = new AppWidgetHost(getActivity(), R.id.APPWIDGET_HOST_ID);
return view;
}
/**
* Launches the menu to select the widget. The selected widget will be on
* the result of the activity.
*/
void selectWidget() {
text.setText(null);
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.
*
*
*/
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
public 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(getActivity(), appWidgetId, appWidgetInfo);
hostView.setAppWidget(appWidgetId, appWidgetInfo);
mainlayout.addView(hostView);
Log.i(TAG, "The widget size is: " + appWidgetInfo.minWidth + "*" + appWidgetInfo.minHeight);
}
I think the problem is into startActivityForResult(pickIntent, R.id.REQUEST_PICK_APPWIDGET); cause when i change R.id.REQUEST_PICK_APPWIDGET to a number (e.g. 1) WidgetManager opens and when i choose an installed widget it does nothing (just closing the window). I hope it is understandable.
My need: I want to extract the links of websites that appear on Google search result page and display them in a textView. The Google search may vary according to the user's needs. The purpose of this (app) is to get the most related, nearest results for the user.
The mechanism is when the user inputs their search words and clicked on the button, the links that are extracted should appear on the textView.
Errors: I don't get an error in the code or any results on the textView.
My Question: Where have I gone wrong? How can I correct it? Is there any other way to do this?
TestHomeFragment.java
public class TestHomeFragment extends Fragment {
ImageButton b_search;
TextView search_webview;
String userLocation = "Sri Lanka";
TextView textView;
List<String> sriLankanUrls;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.test_home_fragment, container, false);
// --------------------------- Search Mechanism -----------------------------------------//
sriLankanUrls = new ArrayList<>();
b_search.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
String searchQuery="buy "+et_search.getText().toString()+ " in " + userLocation ;
new GoogleSearchScraperTask().execute();
}
}); return view;
}
private class GoogleSearchScraperTask extends AsyncTask<Void, Void, StringBuilder> {
@Override
protected StringBuilder doInBackground(Void... voids) {
StringBuilder resultBuilder = new StringBuilder();
try {
// Specify the Google search query
String searchQuery="buy "+et_search.getText().toString()+ " in " + userLocation ;
// Fetch the search results page
Document doc = Jsoup.connect("https://www.google.com/search?q=" + searchQuery).get();
// Extract sentences containing "https://"
Elements searchResults = doc.select("div.g");
for (Element result : searchResults) {
String snippet = result.select("span.st").text();
if (snippet.contains("http")) {
resultBuilder.append(snippet).append("\n");
}
}
} catch (IOException e) {
e.printStackTrace();
}return resultBuilder;
}
@Override
protected void onPostExecute(StringBuilder resultBuilder) {
super.onPostExecute(resultBuilder);
// Set the scraped sentences in the TextView
textView.setText(resultBuilder.toString());
}
}
}