Search Results

Search found 186 results on 8 pages for 'getitem'.

Page 6/8 | < Previous Page | 2 3 4 5 6 7 8  | Next Page >

  • ArrayIndexOutOfBoundsException with custom Android Adapter for multiple views in ListView

    - by Dan Watling
    I am attempting to create a custom Adapter for my ListView since each item in the list can have a different view (a link, toggle, or radio group), but when I try to run the Activity that uses the ListView I receive an error and the app stops. The application is targeted for the Android 1.6 platform. The code: public class MenuListAdapter extends BaseAdapter { private static final String LOG_KEY = MenuListAdapter.class.getSimpleName(); protected List<MenuItem> list; protected Context ctx; protected LayoutInflater inflater; public MenuListAdapter(Context context, List<MenuItem> objects) { this.list = objects; this.ctx = context; this.inflater = (LayoutInflater)this.ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public View getView(int position, View convertView, ViewGroup parent) { Log.i(LOG_KEY, "Position: " + position + "; convertView = " + convertView + "; parent=" + parent); MenuItem item = list.get(position); Log.i(LOG_KEY, "Item=" + item ); if (convertView == null) { convertView = this.inflater.inflate(item.getLayout(), null); } return convertView; } @Override public boolean areAllItemsEnabled() { return false; } @Override public boolean isEnabled(int position) { return true; } @Override public int getCount() { return this.list.size(); } @Override public MenuItem getItem(int position) { return this.list.get(position); } @Override public long getItemId(int position) { return position; } @Override public int getItemViewType(int position) { Log.i(LOG_KEY, "getItemViewType: " + this.list.get(position).getLayout()); return this.list.get(position).getLayout(); } @Override public int getViewTypeCount() { Log.i(LOG_KEY, "getViewTypeCount: " + this.list.size()); return this.list.size(); } } The error I receive: java.lang.ArrayIndexOutOfBoundsException at android.widget.AbsListView$RecycleBin.addScrapView(AbsListView.java:3523) at android.widget.ListView.measureHeightOfChildren(ListView.java:1158) at android.widget.ListView.onMeasure(ListView.java:1060) at android.view.View.measure(View.java:7703) I do know that the application is returning from getView and everything seems in order. Any ideas on what could be causing this would be appreciated. Thanks, -Dan

    Read the article

  • changing image on listview at runtime in android

    - by Raj
    Hi, I am using a LinearLayout to display some Text and image. I have the images at drawable/ and i am implimenting this with ListActivity with some onListItemClick functionality. now i wants to change the image for the rows which are processed by onclick functionality to show the status as processed. can some one help me in this issue to change the image at runtime. the following is my implimentation. public class ListWithImage extends ListActivity { /** Called when the activity is first created. */ private SimpleCursorAdapter myAdapter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // raj setContentView(R.layout.main); Cursor cursor = getContentResolver().query(People.CONTENT_URI, null, null, null, null); startManagingCursor(cursor); String[] columns = new String[] {People.NAME, People.NUMBER}; int[] names = new int[] {R.id.contact_name, R.id.contact_number}; myAdapter = new SimpleCursorAdapter(this, R.layout.main, cursor, columns, names); setListAdapter(myAdapter); } @Override protected void onListItemClick(ListView listView, View view, int position, long id) { super.onListItemClick(listView, view, position, id); Intent intent = new Intent(Intent.ACTION_CALL); Cursor cursor = (Cursor) myAdapter.getItem(position); long phoneId = cursor.getLong(cursor.getColumnIndex(People.PRIMARY_PHONE_ID)); intent.setData(ContentUris.withAppendedId(Phones.CONTENT_URI, phoneId)); startActivity(intent); } } and main.xml is : <LinearLayout android:layout_height="wrap_content" android:orientation="vertical" android:layout_width="250px"> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Name: " /> <TextView android:id="@+id/contact_name" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Phone: " /> <TextView android:id="@+id/contact_number" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>

    Read the article

  • Android GridView Custom BaseAdapter ImageView ImageButton OnItemClick doesn´t work

    - by Marek
    i have a problem using a GridView with a CustomAdapter (extends BaseAdapter). any Activity implements the OnItemClickListener. if i use ImageView as item everything works fine, OnItemClick-Events will be fired/catched I have not found a useful example for a GridView with a custom BaseAdapter using ImageButton. Has anyone an idea? Many thanks in advantage! Snippets: class MyActivity extends Activity implements OnItemClickListener { ... @Override public void onCreate() { ... GridView gridview = (GridView) findViewById(R.id.gridview); gridview.setOnItemClickListener(this); gridview.setAdapter(new ImageButtonAdapter(this)); } ... @Override public void onItemClick(AdapterView<?> adapter, View view, int arg2, long arg3) { Log.e("onItemClick()", "arg2=" + arg2 + ", arg3=" + arg3); } } public class ImageButtonAdapter extends BaseAdapter { private Context mContext; public LayoutMenuAdapter(Context c) { mContext = c; } public int getCount() { return mThumbIds.length; } public Object getItem(int position) { return null; } public long getItemId(int position) { return 0; } public View getView(int position, View convertView, ViewGroup parent) { /* IF I USE THIS PART EVERYTHING WORKS FINE */ // ImageView imageView; // if (convertView == null) { // imageView = new ImageView(mContext); // imageView.setLayoutParams(new GridView.LayoutParams(100, 100)); // imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); // imageView.setPadding(0, 0, 0, 0); // imageView.setFocusable(false); // } else { // imageView = (ImageView) convertView; // } // imageView.setImageResource(mThumbIds[position]); // return imageView; /* IF I USE THIS PART NO THE ACTIVITY/LISTENER RECEIVES NO EVENT */ ImageButton imageButton; if (convertView == null) { imageButton = new ImageButton(mContext); imageButton.setLayoutParams(new GridView.LayoutParams(100, 100)); imageButton.setScaleType(ImageView.ScaleType.CENTER_CROP); imageButton.setPadding(0, 0, 0, 0); imageButton.setFocusable(false); } else { imageButton = (ImageButton) convertView; } imageButton.setImageResource(mThumbIds[position]); return imageButton; } // references to images private Integer[] mThumbIds = { R.drawable.media}; }

    Read the article

  • wxPython ListCtrl Column Ignores Specific Fields

    - by g.d.d.c
    I'm rewriting this post to clarify some things and provide a full class definition for the Virtual List I'm having trouble with. The class is defined like so: from wx import ListCtrl, LC_REPORT, LC_VIRTUAL, LC_HRULES, LC_VRULES, \ EVT_LIST_COL_CLICK, EVT_LIST_CACHE_HINT, EVT_LIST_COL_RIGHT_CLICK, \ ImageList, IMAGE_LIST_SMALL, Menu, MenuItem, NewId, ITEM_CHECK, Frame, \ EVT_MENU class VirtualList(ListCtrl): def __init__(self, parent, datasource = None, style = LC_REPORT | LC_VIRTUAL | LC_HRULES | LC_VRULES): ListCtrl.__init__(self, parent, style = style) self.columns = [] self.il = ImageList(16, 16) self.Bind(EVT_LIST_CACHE_HINT, self.CheckCache) self.Bind(EVT_LIST_COL_CLICK, self.OnSort) if datasource is not None: self.datasource = datasource self.Bind(EVT_LIST_COL_RIGHT_CLICK, self.ShowAvailableColumns) self.datasource.list = self self.Populate() def SetDatasource(self, datasource): self.datasource = datasource def CheckCache(self, event): self.datasource.UpdateCache(event.GetCacheFrom(), event.GetCacheTo()) def OnGetItemText(self, item, col): return self.datasource.GetItem(item, self.columns[col]) def OnGetItemImage(self, item): return self.datasource.GetImg(item) def OnSort(self, event): self.datasource.SortByColumn(self.columns[event.Column]) self.Refresh() def UpdateCount(self): self.SetItemCount(self.datasource.GetCount()) def Populate(self): self.UpdateCount() self.datasource.MakeImgList(self.il) self.SetImageList(self.il, IMAGE_LIST_SMALL) self.ShowColumns() def ShowColumns(self): for col, (text, visible) in enumerate(self.datasource.GetColumnHeaders()): if visible: self.columns.append(text) self.InsertColumn(col, text, width = -2) def Filter(self, filter): self.datasource.Filter(filter) self.UpdateCount() self.Refresh() def ShowAvailableColumns(self, evt): colMenu = Menu() self.id2item = {} for idx, (text, visible) in enumerate(self.datasource.columns): id = NewId() self.id2item[id] = (idx, visible, text) item = MenuItem(colMenu, id, text, kind = ITEM_CHECK) colMenu.AppendItem(item) EVT_MENU(colMenu, id, self.ColumnToggle) item.Check(visible) Frame(self, -1).PopupMenu(colMenu) colMenu.Destroy() def ColumnToggle(self, evt): toggled = self.id2item[evt.GetId()] if toggled[1]: idx = self.columns.index(toggled[2]) self.datasource.columns[toggled[0]] = (self.datasource.columns[toggled[0]][0], False) self.DeleteColumn(idx) self.columns.pop(idx) else: self.datasource.columns[toggled[0]] = (self.datasource.columns[toggled[0]][0], True) idx = self.datasource.GetColumnHeaders().index((toggled[2], True)) self.columns.insert(idx, toggled[2]) self.InsertColumn(idx, toggled[2], width = -2) self.datasource.SaveColumns() I've added functions that allow for Column Toggling which facilitate my description of the issue I'm encountering. On the 3rd instance of this class in my application the Column at Index 1 will not display String values. Integer values are displayed properly. If I add print statements to my OnGetItemText method the values show up in my console properly. This behavior is not present in the first two instances of this class, and my class does not contain any type checking code with respect to value display. It was suggested by someone on the wxPython users' group that I create a standalone sample that demonstrates this issue if I can. I'm working on that, but have not yet had time to create a sample that does not rely on database access. Any suggestions or advice would be most appreciated. I'm tearing my hair out on this one.

    Read the article

  • How to add image in ListView android

    - by Wawan Den Frastøtende
    i would like to add images on my list view, and i have this code package com.wilis.appmysql; import android.app.ListActivity; import android.content.Intent; import android.os.Bundle; //import android.util.Log; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; public class menulayanan extends ListActivity { /** Called when the activity is first created. */ public void onCreate(Bundle icicle) { super.onCreate(icicle); // Create an array of Strings, that will be put to our ListActivity String[] menulayanan = new String[] { "Berita Terbaru", "Info Item", "Customer Service", "Help","Exit"}; //Menset nilai array ke dalam list adapater sehingga data pada array akan dimunculkan dalam list this.setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,menulayanan)); } @Override /**method ini akan mengoveride method onListItemClick yang ada pada class List Activity * method ini akan dipanggil apabilai ada salah satu item dari list menu yang dipilih */ protected void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); // Get the item that was clicked // Menangkap nilai text yang dklik Object o = this.getListAdapter().getItem(position); String pilihan = o.toString(); // Menampilkan hasil pilihan menu dalam bentuk Toast tampilkanPilihan(pilihan); } /** * Tampilkan Activity sesuai dengan menu yang dipilih * */ protected void tampilkanPilihan(String pilihan) { try { //Intent digunakan untuk sebagai pengenal suatu activity Intent i = null; if (pilihan.equals("Berita Terbaru")) { i = new Intent(this, PraBayar.class); } else if (pilihan.equals("Info Item")) { i = new Intent(this, PascaBayar.class); } else if (pilihan.equals("Customer Service")) { i = new Intent(this, CustomerService.class); } else if (pilihan.equals("Help")) { i = new Intent(this, Help.class); } else if (pilihan.equals("Exit")) { finish(); } else { Toast.makeText(this,"Anda Memilih: " + pilihan + " , Actionnya belum dibuat", Toast.LENGTH_LONG).show(); } startActivity(i); } catch (Exception e) { e.printStackTrace(); } } } and i want to add different image per list, so i mean is i want to add a.png to "Berita Terbaru", b.png to "Info Item", c.png "Customer Service" , so how to do it? i was very confused about this, thanks before...

    Read the article

  • asp.net custom templated datalist - throws argument out of range (index) on button press

    - by MrTortoise
    I have a class BaseTemplate public abstract class BaseTemplate : ITemplate This adds the controls, and provides abstract methods to implement in the inheriting class. The inheriting class then adds its html according to its data source and manages the data binding. this all works fine - I get the control appearing with properly parsed html. the problem is that the base class adds controls into the template that have their own CommandName arguments ... the idea is that the class that implements the custom templated dataList will provide the logic of setting the Selected and Edit Indexes. This class also manages the data binding etc. It sets all of the templates ont he datalist in the Init method (which was another cause of this exception). the exception gets throw when i hit one of these buttons .. but after the ItemCommand event is being processed. The stack trace does not include any references to my methods or objects which is why i am so stuck. The Exception Details Exception Details: System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values. Parameter name: index The Stack Trace: [ArgumentOutOfRangeException: Specified argument was out of the range of valid values. Parameter name: index] System.Web.UI.ControlCollection.get_Item(Int32 index) +8665582 System.Web.UI.WebControls.DataList.GetItem(ListItemType itemType, Int32 repeatIndex) +8667655 System.Web.UI.WebControls.DataList.System.Web.UI.WebControls.IRepeatInfoUser.GetItemStyle(ListItemType itemType, Int32 repeatIndex) +11 System.Web.UI.WebControls.RepeatInfo.RenderVerticalRepeater(HtmlTextWriter writer, IRepeatInfoUser user, Style controlStyle, WebControl baseControl) +8640873 System.Web.UI.WebControls.RepeatInfo.RenderRepeater(HtmlTextWriter writer, IRepeatInfoUser user, Style controlStyle, WebControl baseControl) +27 System.Web.UI.WebControls.DataList.RenderContents(HtmlTextWriter writer) +208 System.Web.UI.WebControls.BaseDataList.Render(HtmlTextWriter writer) +30 System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +27 System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +99 System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +25 System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +134 System.Web.UI.Control.RenderChildren(HtmlTextWriter writer) +19 System.Web.UI.HtmlControls.HtmlForm.RenderChildren(HtmlTextWriter writer) +163 System.Web.UI.HtmlControls.HtmlContainerControl.Render(HtmlTextWriter writer) +32 System.Web.UI.HtmlControls.HtmlForm.Render(HtmlTextWriter output) +51 System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +27 System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +99 System.Web.UI.HtmlControls.HtmlForm.RenderControl(HtmlTextWriter writer) +40 System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +134 System.Web.UI.Control.RenderChildren(HtmlTextWriter writer) +19 System.Web.UI.Page.Render(HtmlTextWriter writer) +29 System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +27 System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +99 System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +25 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1266 This is driving me absolutley stark raving bonkers ... im talking cthulu style.

    Read the article

  • Android GridView - How to change a bitmap dynamically?

    - by Alborz
    Hello I have a gridView which I use to show some pictures on (small thumb of diffrent levels). When the user finishes one level, I would like to change the thumb for that level. (Somehow show that it has been completed). I created two thumbs for each level. One is the original and one that shows that the level is completed. But how can i change the source of the images? The code which I use to draw the images looks like this. The main activity: /** Called when the activity is first created. */ public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.maps); GridView gridview = (GridView) findViewById(R.id.gridview); gridview.setAdapter(new ImageAdapter(this)); gridview.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View v, int position, long id) { //Open the map which was clicked on, if there is one if(position+1 > 1){ Toast.makeText(maps.this, "Level " + (position+1) + " is not yet available!", Toast.LENGTH_SHORT).show(); }else{ Toast.makeText(maps.this, "Opening Level " + (position+1), Toast.LENGTH_SHORT).show(); Intent myIntent = new Intent(v.getContext(), Tutorial2D.class); startActivity(myIntent); } } }); } The ImageAdapter Class: public class ImageAdapter extends BaseAdapter { private Context mContext; public ImageAdapter(Context c) { mContext = c; } public int getCount() { return mThumbIds.length; } public Object getItem(int position) { return null; } public long getItemId(int position) { return 0; } // create a new ImageView for each item referenced by the Adapter public View getView(int position, View convertView, ViewGroup parent) { ImageView imageView; if (convertView == null) { // if it's not recycled, initialize some attributes imageView = new ImageView(mContext); imageView.setLayoutParams(new GridView.LayoutParams(85, 85)); imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); imageView.setPadding(8, 8, 8, 8); } else { imageView = (ImageView) convertView; } //Changing imageView.setImageResource(mThumbIds[position]); return imageView; } // references to our images private Integer[] mThumbIds = { R.drawable.map1, R.drawable.map2, R.drawable.map3, R.drawable.map4, R.drawable.map5, R.drawable.map6, R.drawable.map7, R.drawable.map8, R.drawable.map9, R.drawable.map10, R.drawable.map11, R.drawable.map12, R.drawable.map13, R.drawable.map14, R.drawable.map15, R.drawable.map16, R.drawable.map17, R.drawable.map18, R.drawable.map19 }; }

    Read the article

  • One intent is working, second is giving me a crash

    - by user1480742
    ok, so both intents receiver sides are on the same activite and they are sending from different ones....second one is not working, first one does, dont know why...all 3 activites are ok in manifest and all that //second intent on senders side public void onItemSelected(AdapterView<?> arg0, View users, int i, long l) { FILENAME = (adapter.getItem(i)).toString(); Bundle viewBag2 = new Bundle(); viewBag2.putString("profile_name", FILENAME); Intent b = new Intent(OptionsMenu.this, CoreActivity.class); b.putExtras(viewBag2); startActivity(b); } //second intent on receiver side private void Data_transfer() { Bundle gotbasket2 = getIntent().getExtras(); profileName = gotbasket2.getString("profile_name"); } //first (working intent) on senders side public void onClick(View v) { Bundle viewBag = new Bundle(); viewBag.putString("spinner_result", s); a.putExtras(viewBag); } //first (working intent) on receiver side private void Data_transfer() { // TODO Auto-generated method stub Bundle gotbasket = getIntent().getExtras(); x = gotbasket.getString("spinner_result"); } 06-26 20:22:09.787: D/AndroidRuntime(1802): Shutting down VM 06-26 20:22:09.787: W/dalvikvm(1802): threadid=1: thread exiting with uncaught exception (group=0x40015560) 06-26 20:22:09.847: E/AndroidRuntime(1802): FATAL EXCEPTION: main 06-26 20:22:09.847: E/AndroidRuntime(1802): java.lang.RuntimeException: Unable to start activity ComponentInfo{mioc.diver/mioc.diver.CoreActivity}: java.lang.NullPointerException 06-26 20:22:09.847: E/AndroidRuntime(1802): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647) 06-26 20:22:09.847: E/AndroidRuntime(1802): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663) 06-26 20:22:09.847: E/AndroidRuntime(1802): at android.app.ActivityThread.access$1500(ActivityThread.java:117) 06-26 20:22:09.847: E/AndroidRuntime(1802): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931) 06-26 20:22:09.847: E/AndroidRuntime(1802): at android.os.Handler.dispatchMessage(Handler.java:99) 06-26 20:22:09.847: E/AndroidRuntime(1802): at android.os.Looper.loop(Looper.java:123) 06-26 20:22:09.847: E/AndroidRuntime(1802): at android.app.ActivityThread.main(ActivityThread.java:3683) 06-26 20:22:09.847: E/AndroidRuntime(1802): at java.lang.reflect.Method.invokeNative(Native Method) 06-26 20:22:09.847: E/AndroidRuntime(1802): at java.lang.reflect.Method.invoke(Method.java:507) 06-26 20:22:09.847: E/AndroidRuntime(1802): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839) 06-26 20:22:09.847: E/AndroidRuntime(1802): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597) 06-26 20:22:09.847: E/AndroidRuntime(1802): at dalvik.system.NativeStart.main(Native Method) 06-26 20:22:09.847: E/AndroidRuntime(1802): Caused by: java.lang.NullPointerException 06-26 20:22:09.847: E/AndroidRuntime(1802): at mioc.diver.CoreActivity.Data_transfer(CoreActivity.java:189) 06-26 20:22:09.847: E/AndroidRuntime(1802): at mioc.diver.CoreActivity.onCreate(CoreActivity.java:88) 06-26 20:22:09.847: E/AndroidRuntime(1802): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047) 06-26 20:22:09.847: E/AndroidRuntime(1802): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611) 06-26 20:22:09.847: E/AndroidRuntime(1802): ... 11 more

    Read the article

  • How to refresh a fragment in a viewpager?

    - by aut_silvia
    I know there are already some questions to this problem. But I am really new in Android and ecspecially to Fragments and Viewpager. Pls have passion with me. I didn't found a answer which fits to my code. I dont know how to refresh a fragment or reload it when it's "active" again. TabsPagerAdapter.java: public class TabsPagerAdapter extends FragmentPagerAdapter{ public TabsPagerAdapter(FragmentManager fm){ super(fm); } @Override public Fragment getItem(int index) { switch (index) { case 0: return new KFZFragment(); case 1: return new LogFragment(); case 2: return new TrackFragment(); } return null; } @Override public int getCount() { // get item count - equal to number of tabs return 3; } } I have this 3 Fragments (KFZFragment,LogFragment,TrackFragment) and on the TrackFragment I calculate some data and this data should be display in a ListView in LogFragment. But when I change to LogFragment it's not the latest data. So it doesnt refresh. Now how should I modify my code to refresh the fragments when it's "active"? MainActivityFragment.java: public class MainActivityFragment extends FragmentActivity implements ActionBar.TabListener{ private ViewPager viewPager; private TabsPagerAdapter mAdapter; private ActionBar actionBar; List<Fragment> fragments; private String[] tabs = { "KFZ", "Fahrten Log", "Kosten Track" }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main_fragment); // Initilization viewPager = (ViewPager) findViewById(R.id.pager); actionBar = getActionBar(); mAdapter = new TabsPagerAdapter(getSupportFragmentManager()); fragments = new Vector<Fragment>(); fragments.add(Fragment.instantiate(this, KFZFragment.class.getName(),savedInstanceState)); fragments.add(Fragment.instantiate(this, LogFragment.class.getName(),savedInstanceState)); viewPager.setAdapter(mAdapter); actionBar.setHomeButtonEnabled(false); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); // Adding Tabs for (String tab_name : tabs) { actionBar.addTab(actionBar.newTab().setText(tab_name) .setTabListener(this)); } viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageSelected(int position) { // on changing the page // make respected tab selected actionBar.setSelectedNavigationItem(position); } @Override public void onPageScrolled(int arg0, float arg1, int arg2) { } @Override public void onPageScrollStateChanged(int arg0) { } }); } @Override public void onTabReselected(Tab tab, FragmentTransaction ft) { // TODO Auto-generated method stub } @Override public void onTabSelected(Tab tab, FragmentTransaction ft) { viewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabUnselected(Tab tab, FragmentTransaction ft) { // TODO Auto-generated method stub } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { } return super.onKeyDown(keyCode, event); } } Pls help me out.

    Read the article

  • [Android] Show default selection color for custom listview

    - by Diego
    Hello, I have a listview with a custom BaseAdapter. Each row of the listview has a TextView and a CheckBox. The problem is when I click (or touch) any row, the textview foreground becomes gray, instead of the default behavior (background - green, textview foreground - white). Here is the code: row.xml: <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" style="@style/layout"> <TextView android:id="@+id/main_lv_item_textView" style="@style/textViewBig" android:layout_alignParentLeft="true"/> <CheckBox android:id="@+id/main_lv_item_checkBox" style="@style/checkBox" android:layout_width="wrap_content" android:layout_alignParentRight="true"/> </RelativeLayout> Custom Adapter: public class CustomAdapter extends BaseAdapter { private List<Profile> profiles; private LayoutInflater inflater; private TextView tvName; private CheckBox cbEnabled; public CustomAdapter(List<Profile> profiles) { this.profiles = profiles; inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } public int getCount() { return profiles.size(); } public Object getItem(int position) { return profiles.get(position); } public long getItemId(int position) { return position; } public View getView(final int position, View convertView, ViewGroup parent) { View row = inflater.inflate(R.layout.main_lv_item, null); final Profile profile = profiles.get(position); tvName = (TextView) row.findViewById(R.id.main_lv_item_textView); registerForContextMenu(tvName); cbEnabled = (CheckBox) row.findViewById(R.id.main_lv_item_checkBox); tvName.setText(profile.getName()); if (profile.isEnabled()) { cbEnabled.setChecked(true); } tvName.setOnClickListener(new OnClickListener() { public void onClick(View v) { Bundle bundle = new Bundle(); bundle.putString(PROFILE_NAME_KEY, profile.getName()); Intent intent = new Intent(context, GuiProfile.class); intent.putExtras(bundle); startActivity(intent); } }); tvName.setOnLongClickListener(new OnLongClickListener() { public boolean onLongClick(View v) { selectedProfileName = ((TextView) v).getText().toString(); return false; } }); cbEnabled.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (!profile.isEnabled()) { for (Profile profile : profiles) { if (profile.isEnabled()) { profile.setEnabled(false); Database.getInstance().storeProfile(profile); } } } profile.setEnabled(isChecked); Database.getInstance().storeProfile(profile); updateListView(); } }); return row; } } Any help would be appreciated.

    Read the article

  • ImageView place at center on click in gallery view

    - by TGMCians
    i used gallery view in which i place multiple imageview dynamically but on click imageview place at center and second question how to start first imageview from left of screen. I do not want to change the place until user scroll horizontally by finger . Is there any way to achieve this. Please help for this.. private class ImageAdapter extends BaseAdapter{ public ImageAdapter() { //To set blank at bottom and make visible TextView textView = (TextView)findViewById(R.id.textView2); textView.setVisibility(View.VISIBLE); //To set the visibility visible of gallery myGallery.setVisibility(View.VISIBLE); } public int getCount() { return ProductItemArray.Image_URL.length; } public Object getItem(int position) { return null; } public long getItemId(int position) { return 0; } public View getView(int position, View arg1, ViewGroup arg2) { ImageView bottomImageView = new ImageView(context); if(Helper.isTablet(context)) bottomImageView.setLayoutParams(new Gallery.LayoutParams(VirtualMirrorActivity.convertDpToPixel(100, context), VirtualMirrorActivity.convertDpToPixel(100, context))); else bottomImageView.setLayoutParams(new Gallery.LayoutParams(VirtualMirrorActivity.convertDpToPixel(80, context), VirtualMirrorActivity.convertDpToPixel(80, context))); UrlImageViewHelper.setUrlDrawable(bottomImageView, ProductItemArray.Image_URL[position]); bottomImageView.setBackgroundResource(R.layout.border); return bottomImageView; } } myGallery.setAdapter(new ImageAdapter()); myGallery.setSelection(1); myGallery.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, final int position, long arg3) { linearLayout.removeView(frameImageView); Thread newThread = new Thread(new Runnable() { public void run() { URL url_1 = null; try { isAlreadyExistInWishlist = false; VMProductListPaging.productUrl = ProductItemArray.Image_small_URL[position]; VMProductListPaging.productId = ProductItemArray.productId[position]; VMProductListPaging.productName = ProductItemArray.product_Name[position]; url_1 = new URL(ProductItemArray.Image_small_URL[position]); bmp = BitmapFactory.decodeStream(url_1.openConnection().getInputStream()); isExecuted = true; bitmapHandler.sendMessage(bitmapHandler.obtainMessage()); } catch (Exception e) { //Toast.makeText(context,"Sorry!! This link appears to be broken",Toast.LENGTH_LONG).show(); } } }); newThread.start(); } }); Layout.xml <Gallery android:id="@+id/galleryView" android:layout_width="fill_parent" android:layout_height="wrap_content" android:spacing="5dp" android:layout_below="@+id/sendPhoto" android:layout_marginTop="10dp" android:visibility="gone"/>

    Read the article

  • Android - Create a custom multi-line ListView bound to an ArrayList

    - by Bill Osuch
    The Android HelloListView tutorial shows how to bind a ListView to an array of string objects, but you'll probably outgrow that pretty quickly. This post will show you how to bind the ListView to an ArrayList of custom objects, as well as create a multi-line ListView. Let's say you have some sort of search functionality that returns a list of people, along with addresses and phone numbers. We're going to display that data in three formatted lines for each result, and make it clickable. First, create your new Android project, and create two layout files. Main.xml will probably already be created by default, so paste this in: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  android:orientation="vertical"  android:layout_width="fill_parent"   android:layout_height="fill_parent">  <TextView   android:layout_height="wrap_content"   android:text="Custom ListView Contents"   android:gravity="center_vertical|center_horizontal"   android:layout_width="fill_parent" />   <ListView    android:id="@+id/ListView01"    android:layout_height="wrap_content"    android:layout_width="fill_parent"/> </LinearLayout> Next, create a layout file called custom_row_view.xml. This layout will be the template for each individual row in the ListView. You can use pretty much any type of layout - Relative, Table, etc., but for this we'll just use Linear: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  android:orientation="vertical"  android:layout_width="fill_parent"   android:layout_height="fill_parent">   <TextView android:id="@+id/name"   android:textSize="14sp"   android:textStyle="bold"   android:textColor="#FFFF00"   android:layout_width="wrap_content"   android:layout_height="wrap_content"/>  <TextView android:id="@+id/cityState"   android:layout_width="wrap_content"   android:layout_height="wrap_content"/>  <TextView android:id="@+id/phone"   android:layout_width="wrap_content"   android:layout_height="wrap_content"/> </LinearLayout> Now, add an object called SearchResults. Paste this code in: public class SearchResults {  private String name = "";  private String cityState = "";  private String phone = "";  public void setName(String name) {   this.name = name;  }  public String getName() {   return name;  }  public void setCityState(String cityState) {   this.cityState = cityState;  }  public String getCityState() {   return cityState;  }  public void setPhone(String phone) {   this.phone = phone;  }  public String getPhone() {   return phone;  } } This is the class that we'll be filling with our data, and loading into an ArrayList. Next, you'll need a custom adapter. This one just extends the BaseAdapter, but you could extend the ArrayAdapter if you prefer. public class MyCustomBaseAdapter extends BaseAdapter {  private static ArrayList<SearchResults> searchArrayList;    private LayoutInflater mInflater;  public MyCustomBaseAdapter(Context context, ArrayList<SearchResults> results) {   searchArrayList = results;   mInflater = LayoutInflater.from(context);  }  public int getCount() {   return searchArrayList.size();  }  public Object getItem(int position) {   return searchArrayList.get(position);  }  public long getItemId(int position) {   return position;  }  public View getView(int position, View convertView, ViewGroup parent) {   ViewHolder holder;   if (convertView == null) {    convertView = mInflater.inflate(R.layout.custom_row_view, null);    holder = new ViewHolder();    holder.txtName = (TextView) convertView.findViewById(R.id.name);    holder.txtCityState = (TextView) convertView.findViewById(R.id.cityState);    holder.txtPhone = (TextView) convertView.findViewById(R.id.phone);    convertView.setTag(holder);   } else {    holder = (ViewHolder) convertView.getTag();   }      holder.txtName.setText(searchArrayList.get(position).getName());   holder.txtCityState.setText(searchArrayList.get(position).getCityState());   holder.txtPhone.setText(searchArrayList.get(position).getPhone());   return convertView;  }  static class ViewHolder {   TextView txtName;   TextView txtCityState;   TextView txtPhone;  } } (This is basically the same as the List14.java API demo) Finally, we'll wire it all up in the main class file: public class CustomListView extends Activity {     @Override     public void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.main);                 ArrayList<SearchResults> searchResults = GetSearchResults();                 final ListView lv1 = (ListView) findViewById(R.id.ListView01);         lv1.setAdapter(new MyCustomBaseAdapter(this, searchResults));                 lv1.setOnItemClickListener(new OnItemClickListener() {          @Override          public void onItemClick(AdapterView<?> a, View v, int position, long id) {           Object o = lv1.getItemAtPosition(position);           SearchResults fullObject = (SearchResults)o;           Toast.makeText(ListViewBlogPost.this, "You have chosen: " + " " + fullObject.getName(), Toast.LENGTH_LONG).show();          }          });     }         private ArrayList<SearchResults> GetSearchResults(){      ArrayList<SearchResults> results = new ArrayList<SearchResults>();            SearchResults sr1 = new SearchResults();      sr1.setName("John Smith");      sr1.setCityState("Dallas, TX");      sr1.setPhone("214-555-1234");      results.add(sr1);            sr1 = new SearchResults();      sr1.setName("Jane Doe");      sr1.setCityState("Atlanta, GA");      sr1.setPhone("469-555-2587");      results.add(sr1);            sr1 = new SearchResults();      sr1.setName("Steve Young");      sr1.setCityState("Miami, FL");      sr1.setPhone("305-555-7895");      results.add(sr1);            sr1 = new SearchResults();      sr1.setName("Fred Jones");      sr1.setCityState("Las Vegas, NV");      sr1.setPhone("612-555-8214");      results.add(sr1);            return results;     } } Notice that we first get an ArrayList of SearchResults objects (normally this would be from an external data source...), pass it to the custom adapter, then set up a click listener. The listener gets the item that was clicked, converts it back to a SearchResults object, and does whatever it needs to do. Fire it up in the emulator, and you should wind up with something like this:

    Read the article

  • Package management fails in update-manager with gzip problems and compilation errors. U12.04LTS

    - by HarveyP
    Similar to but not the same as Package management system corrupted. Cannot install or remove packages. U12.04LTS (an earlier problem) with package management system. Followed all of L. D. James suggestions in his answer to no avail. This time as well as the gzip error I am also getting compilation errors. The difference may be due to a lack of compilation in my earlier problem so it may be the same error. The packages concerned are enumerated in the output from update-manager below. Also included below that is the output from apt-get -f install apt-get autoremove gives same output. Tried update without SSL updates - 9 to install and got "Unhandled Error in aptdaemon". Output number 3 below. One at a time - output 4 - is for firefox, first in the list of packages. Falls over at libssl1.0.0 despite deselection of it from update ... Tried apt-get install --reinstall dpkg which succeeded, apt-get install --reinstall tar and apt-get install --reinstall gzip both of which failed at libssl1.0.0 as ever. (as suggested by Subv3rsion elsewhere in this forum) Now cannot apt-get update with complete success even after changing server and apt-get clean - output number 5 below ... 1). Output from update-manager The following packages will be upgraded:<> firefox firefox-globalmenu firefox-locale-en libavcodec-extra-53 libavformat53 libavutil-extra-51 libjson0 libpostproc52 libssl1.0.0 libswscale2 openssl 11 to upgrade, 0 to newly install, 0 to remove and 0 not to upgrade.<br> Need to get 0 B/46.5 MB of archives. After this operation, 1,416 kB of additional disk space will be used.<br> Do you want to continue [Y/n]? y debconf: Perl may be unconfigured (Bareword "gensym" not allowed while "strict subs" in use at /usr/lib/perl/5.14/IO/Handle.pm line 67. BEGIN not safe after errors--compilation aborted at /usr/lib/perl/5.14/IO/Handle.pm line 366. Compilation failed in require at /usr/lib/perl/5.14/IO/Seekable.pm line 9. BEGIN failed--compilation aborted at /usr/lib/perl/5.14/IO/Seekable.pm line 9. Compilation failed in require at /usr/lib/perl/5.14/IO/File.pm line 11. BEGIN failed--compilation aborted at /usr/lib/perl/5.14/IO/File.pm line 11. Compilation failed in require at /usr/share/perl/5.14/FileHandle.pm line 9. Compilation failed in require at (eval 1) line 3. BEGIN failed--compilation aborted at (eval 1) line 3. ) -- aborting (Reading database ... 160575 files and directories currently installed.) Preparing to replace libssl1.0.0 1.0.1-4ubuntu5.14 (using .../libssl1.0.0_1.0.1-4ubuntu5.15_i386.deb) ... Unpacking replacement libssl1.0.0 ... dpkg-deb (subprocess): data: internal gzip read error: '<fd:4>: data error' dpkg-deb: error: subprocess <decompress> returned error exit status 2 dpkg: error processing /var/cache/apt/archives/libssl1.0.0_1.0.1-4ubuntu5.15_i386.deb (--unpack):<br> subprocess dpkg-deb --fsys-tarfile returned error exit status 2 No apport report written because MaxReports has already been reached Bareword "gensym" not allowed while "strict subs" in use at /usr/lib/perl/5.14/IO/Handle.pm line 67. BEGIN not safe after errors--compilation aborted at /usr/lib/perl/5.14/IO/Handle.pm line 366. Compilation failed in require at /usr/lib/perl/5.14/IO/Seekable.pm line 9. BEGIN failed--compilation aborted at /usr/lib/perl/5.14/IO/Seekable.pm line 9. Compilation failed in require at /usr/lib/perl/5.14/IO/File.pm line 11. BEGIN failed--compilation aborted at /usr/lib/perl/5.14/IO/File.pm line 11. Compilation failed in require at /usr/share/perl/5.14/FileHandle.pm line 9. Compilation failed in require at /usr/share/perl5/Debconf/Template.pm line 8. BEGIN failed--compilation aborted at /usr/share/perl5/Debconf/Template.pm line 8. Compilation failed in require at /usr/share/perl5/Debconf/Question.pm line 8. BEGIN failed--compilation aborted at /usr/share/perl5/Debconf/Question.pm line 8. Compilation failed in require at /usr/share/perl5/Debconf/Config.pm line 7. BEGIN failed--compilation aborted at /usr/share/perl5/Debconf/Config.pm line 7. Compilation failed in require at /usr/share/perl5/Debconf/Log.pm line 10. Compilation failed in require at /usr/share/perl5/Debconf/Db.pm line 7. BEGIN failed--compilation aborted at /usr/share/perl5/Debconf/Db.pm line 7. Compilation failed in require at /usr/share/debconf/frontend line 6. BEGIN failed--compilation aborted at /usr/share/debconf/frontend line 6. dpkg: error whale cleanang up: subprgcess installed post-installation script returned error exit status 2 Errors were encountered while processing: /var/cache/apt/archives/libssl1.0.0_1.0.1-4ubuntu5.15_i386.deb E: Sub-process /usr/bin/dpkg returned an error code (1) 2). Output from install -f harveyp@harveyp:~$ sudo apt-get -f install [sudo] password for harveyp: Reading package lists... Done Building dependency tree Reading state information... Done 0 to upgrade, 0 to newly install, 0 to remove and 11 not to upgrade. 1 not fully installed or removed.<br> After this operation, 0 B of additional disk space will be used. E: Internal Error, No file name for libssl1.0.0 3). Unhandled error from aptdaemon Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/aptdaemon/worker.py", line 1045, in _simulate trans.unauthenticated = self.__simulate(trans) File "/usr/lib/python2.7/dist-packages/aptdaemon/worker.py", line 1160, in __simulate unauthenticated = self._get_unauthenticated() File "/usr/lib/python2.7/dist-packages/aptdaemon/worker.py", line 347, in _get_unauthenticated for pkg in self._iterate_packages(): File "/usr/lib/python2.7/dist-packages/aptdaemon/worker.py", line 1356, in _iterate_packages for enum, pkg in enumerate(self._cache): File "/usr/lib/python2.7/dist-packages/apt/cache.py", line 216, in __iter__ yield self[pkgname] File "/usr/lib/python2.7/dist-packages/apt/cache.py", line 201, in __getitem__ pkg = self._weakref[key] = Package(self, self._cache[key]) KeyError: 'librqrcode-rubq-doc 4). output from update of firefox installArchives() failed: Error in function: < Setting up libssl1.0.0 (1.0.1-4ubuntu5.14) ... Bareword "gensym" not allowed while "strict subs" in use at /usr/lib/perl/5.14/IO/Handle.pm line 67. BEGIN not safe after errors--compilation aborted at /usr/lib/perl/5.14/IO/Handle.pm line 366. Compilation failed in require at /usr/lib/perl/5.14/IO/Seekable.pm line 9. BEGIN failed--compilation aborted at /usr/lib/perl/5.14/IO/Seekable.pm line 9. Compilation failed in require at /usr/lib/perl/5.14/IO/File.pm line 11. BEGIN failed--compilation aborted at /usr/lib/perl/5.14/IO/File.pm line 11. Compilation failed in require at /usr/share/perl/5.14/FileHandle.pm line 9. Compilation failed in require at /usr/share/perl5/Debconf/Template.pm line 8. BEGIN failed--compilation aborted at /usr/share/perl5/Debconf/Template.pm line 8. Compilation failed in require at /usr/share/perl5/Debconf/Question.pm line 8. BEGIN failed--compilation aborted at /usr/share/perl5/Debconf/Question.pm line 8. Compilation failed in require at /usr/share/perl5/Debconf/Config.pm line 7. BEGIN failed--compilation aborted at /usr/share/perl5/Debconf/Config.pm line 7. Compilation failed in require at /usr/share/perl5/Debconf/Log.pm line 10. 5. output from apt-get update ...snip ... Hit http://ubuntu-archive.mirrors.free.org precise-security/multiverse Translation-en Hit http://ubuntu-archive.mirrors.free.org precise-security/restricted Translation-en Hit http://ubuntu-archive.mirrors.free.org precise-security/universe Translation-en Fetched 368 kB in 6s (59.5 kB/s) W: Failed to fetch gzip:/var/lib/apt/lists/partial/ubuntu-archive.mirrors.free.org_ubuntu_dists_precise_universe_source_Sources Hash Sum mismatch E: Some index files failed to download. They have been ignored, or old ones used instead.

    Read the article

  • EWS - How to search for items [message] between dates ?

    - by SomFred
    Hi, I am trying to search for message items between two dates from the inbox folder. I use the following restrictionType but it throws this error: firmt.RootFolder = null What am I doing wrong? There is some messages between the mentionned dates ;-) Thanks for your suggestions. using (ExchangeServiceBinding esb = new ExchangeServiceBinding()) { esb.Url = ConfigurationManager.AppSettings["ExchangeWebServicesURL"].ToString(); esb.RequestServerVersionValue = new RequestServerVersion(); esb.RequestServerVersionValue.Version = ExchangeVersionType.Exchange2007_SP1; esb.PreAuthenticate = true; esb.Credentials = new NetworkCredential(email, password); FindItemType findItemRequest = new FindItemType(); // paging IndexedPageViewType ipvt = new IndexedPageViewType(); ipvt.BasePoint = IndexBasePointType.Beginning; ipvt.MaxEntriesReturned = nombreMessage; ipvt.MaxEntriesReturnedSpecified = true; ipvt.Offset = offset; findItemRequest.Item = ipvt; // filter by dates AndType andType = new AndType(); List<SearchExpressionType> searchExps = new List<SearchExpressionType>(); RestrictionType restriction = new RestrictionType(); PathToUnindexedFieldType pteft = new PathToUnindexedFieldType { FieldURI = UnindexedFieldURIType.itemDateTimeSent }; IsGreaterThanOrEqualToType IsGreaterThanOrEqualTo = new IsGreaterThanOrEqualToType { Item = pteft, FieldURIOrConstant = new FieldURIOrConstantType { Item = new ConstantValueType { Value = DateTime.Today.AddDays(-6d).ToString() } } }; searchExps.Add(IsGreaterThanOrEqualTo); IsLessThanOrEqualToType IsLessThanOrEqualTo = new IsLessThanOrEqualToType { Item = pteft, FieldURIOrConstant = new FieldURIOrConstantType { Item = new ConstantValueType { Value = DateTime.Today.AddDays(1d).ToString() } } }; searchExps.Add(IsLessThanOrEqualTo); andType.Items = searchExps.ToArray(); restriction.Item = andType; findItemRequest.Restriction = restriction; //// Define the sort order of items. FieldOrderType[] fieldsOrder = new FieldOrderType[1]; fieldsOrder[0] = new FieldOrderType(); PathToUnindexedFieldType dateOrder = new PathToUnindexedFieldType { FieldURI = UnindexedFieldURIType.itemDateTimeReceived }; fieldsOrder[0].Item = dateOrder; fieldsOrder[0].Order = SortDirectionType.Descending; findItemRequest.SortOrder = fieldsOrder; findItemRequest.Traversal = ItemQueryTraversalType.Shallow; // define which item properties are returned in the response findItemRequest.ItemShape = new ItemResponseShapeType { BaseShape = DefaultShapeNamesType.IdOnly }; // identify which folder to search DistinguishedFolderIdType[] folderIDArray = new DistinguishedFolderIdType[1]; folderIDArray[0] = new DistinguishedFolderIdType { Id = DistinguishedFolderIdNameType.inbox }; // add folders to request findItemRequest.ParentFolderIds = folderIDArray; // find the messages FindItemResponseType findItemResponse = esb.FindItem(findItemRequest); //------------- ArrayOfResponseMessagesType responseMessages = findItemResponse.ResponseMessages; ResponseMessageType responseMessage = responseMessages.Items[0]; if (responseMessage is FindItemResponseMessageType) { FindItemResponseMessageType firmt = (responseMessage as FindItemResponseMessageType); *******FindItemParentType fipt = firmt.RootFolder;******** object obj = fipt.Item; // FindItem contains an array of items. ArrayOfRealItemsType realitems = (obj as ArrayOfRealItemsType); ItemType[] items = realitems.Items; // if no messages were found, then return null -- we're done if (items == null || items.Count() <= 0) return null; // FindItem never gets "all" the properties, so now that we've found them all, we need to get them all. BaseItemIdType[] itemIds = new BaseItemIdType[items.Count()]; for (int i = 0; i < items.Count(); i++) itemIds[i] = items[i].ItemId; GetItemType getItemType = new GetItemType { ItemIds = itemIds, ItemShape = new ItemResponseShapeType { BaseShape = DefaultShapeNamesType.AllProperties, BodyType = BodyTypeResponseType.Text, BodyTypeSpecified = true, AdditionalProperties = new BasePathToElementType[] { new PathToUnindexedFieldType { FieldURI = UnindexedFieldURIType.itemDateTimeSent }, new PathToUnindexedFieldType { FieldURI = UnindexedFieldURIType.messageFrom }, new PathToUnindexedFieldType { FieldURI = UnindexedFieldURIType.messageIsRead }, new PathToUnindexedFieldType { FieldURI = UnindexedFieldURIType.messageSender }, new PathToUnindexedFieldType { FieldURI = UnindexedFieldURIType.messageToRecipients }, new PathToUnindexedFieldType { FieldURI = UnindexedFieldURIType.messageCcRecipients }, new PathToUnindexedFieldType { FieldURI = UnindexedFieldURIType.messageBccRecipients } } } }; GetItemResponseType getItemResponse = esb.GetItem(getItemType); messages = ReadItems(getItemResponse, items.Count()); }

    Read the article

  • Class Issue (The type XXX is already defined )

    - by Android Stack
    I have listview app exploring cities each row point to diffrent city , in each city activity include button when clicked open new activity which is infinite gallery contains pics of that city , i add infinite gallery to first city and work fine , when i want to add it to the second city , it gave me red mark error in the class as follow : 1- The type InfiniteGalleryAdapter is already defined. 2-The type InfiniteGallery is already defined. i tried to change class name with the same result ,i delete R.jave and eclipse rebuild it with same result also i uncheck the java builder from project properties ,get same red mark error. please any help and advice will be appreciated thanks My Code : public class SecondCity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Boolean customTitleSupported = requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); // Set the layout to use setContentView(R.layout.main); if (customTitleSupported) { getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,R.layout.custom_title); TextView tv = (TextView) findViewById(R.id.tv); Typeface face=Typeface.createFromAsset(getAssets(),"BFantezy.ttf"); tv.setTypeface(face); tv.setText("MY PICTURES"); } InfiniteGallery galleryOne = (InfiniteGallery) findViewById(R.id.galleryOne); galleryOne.setAdapter(new InfiniteGalleryAdapter(this)); } } class InfiniteGalleryAdapter extends BaseAdapter { **//red mark here (InfiniteGalleryAdapter)** private Context mContext; public InfiniteGalleryAdapter(Context c, int[] imageIds) { this.mContext = c; } public int getCount() { return Integer.MAX_VALUE; } public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } private LayoutInflater inflater=null; public InfiniteGalleryAdapter(Context a) { this.mContext = a; inflater = (LayoutInflater)mContext.getSystemService ( Context.LAYOUT_INFLATER_SERVICE); } public class ViewHolder{ public TextView text; public ImageView image; } private int[] images = { R.drawable.pic_1, R.drawable.pic_2, R.drawable.pic_3, R.drawable.pic_4, R.drawable.pic_5 }; private String[] name = { "This is first picture (1) " , "This is second picture (2)", "This is third picture (3)", "This is fourth picture (4)", " This is fifth picture (5)", }; public View getView(int position, View convertView, ViewGroup parent) { ImageView i = getImageView(); int itemPos = (position % images.length); try { i.setImageResource(images[itemPos]); ((BitmapDrawable) i.getDrawable()). setAntiAlias (true); } catch (OutOfMemoryError e) { Log.e("InfiniteGalleryAdapter", "Out of memory creating imageview. Using empty view.", e); } View vi=convertView; ViewHolder holder; if(convertView==null){ vi = inflater.inflate(R.layout.gallery_items, null); holder=new ViewHolder(); holder.text=(TextView)vi.findViewById(R.id.textView1); holder.image=(ImageView)vi.findViewById(R.id.image); vi.setTag(holder); } else holder=(ViewHolder)vi.getTag(); holder.text.setText(name[itemPos]); final int stub_id=images[itemPos]; holder.image.setImageResource(stub_id); return vi; } private ImageView getImageView() { ImageView i = new ImageView(mContext); return i; } } class InfiniteGallery extends Gallery { **//red mark here (InfiniteGallery)** public InfiniteGallery(Context context) { super(context); init(); } public InfiniteGallery(Context context, AttributeSet attrs) { super(context, attrs); init(); } public InfiniteGallery(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(); } private void init(){ // These are just to make it look pretty setSpacing(25); setHorizontalFadingEdgeEnabled(false); } public void setResourceImages(int[] name){ setAdapter(new InfiniteGalleryAdapter(getContext(), name)); setSelection((getCount() / 2)); } }

    Read the article

  • Android - Custom Adapter Problem

    - by Ryan
    Hello, I seem to be having a problem with my Custom Adapter view. When I display the list, it only displays a white screen. Here is how it works: 1.) I send a JSON request 2.) populate the ArrayList with the returned results 3.) create a custom adapter 4.) then bind the adapter. Here is steps 2-4 private void updateUI() { ListView myList = (ListView) findViewById(android.R.id.list); itemList = new ArrayList(); Iterator it = data.entrySet().iterator(); while (it.hasNext()) { //Get the key name and value for it Map.Entry pair = (Map.Entry)it.next(); String keyName = (String) pair.getKey(); String value = pair.getValue().toString(); if (value != null) { ListItem li = new ListItem(keyName, value, false); itemList.add(li); } } CustomAdapter mAdapter = new CustomAdapter( mContext, itemList); myList.setAdapter(mAdapter); //Bind the adapter to the list //Tell the dialog it's cool now. dismissDialog(0); //Show next screen flipper.setInAnimation(inFromRightAnimation()); flipper.setOutAnimation(outToRightAnimation()); flipper.showNext(); } And here is my CustomAdapter class: import java.util.List; import android.R.color; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; class MyAdapterView extends RelativeLayout { public MyAdapterView(Context c, ListItem li) { super( c ); RelativeLayout rL = new RelativeLayout(c); RelativeLayout.LayoutParams containerParams = new RelativeLayout.LayoutParams( ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT); rL.setLayoutParams(containerParams); rL.setBackgroundColor(color.white); ImageView img = new ImageView (c); img.setImageResource(li.getImage()); img.setPadding(5, 5, 10, 5); rL.addView(img, 48, 48); TextView top = new TextView(c); top.setText(li.getTopText()); top.setTextColor(color.black); top.setTextSize(20); top.setPadding(0, 20, 0, 0); rL.addView(top,ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); TextView bot = new TextView( c ); bot.setText(li.getBottomText()); bot.setTextColor(color.black); bot.setTextSize(12); bot.setPadding(0, 0, 0, 10); bot.setAutoLinkMask(1); rL.addView(bot,ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); } } public class CustomAdapter extends BaseAdapter { private Context context; private List itemList; public CustomAdapter(Context c, List itemL ) { this.context = c; this.itemList = itemL; } public int getCount() { return itemList.size(); } public Object getItem(int position) { return itemList.get(position); } public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ListItem li = itemList.get(position); return new MyAdapterView(this.context, li); } } Does anyone have any idea why this displays a white screen upon completion?? Thanks in advance!

    Read the article

  • How can i make a gallery with web images from my website?

    - by ronhdoge
    I currently have two codes that i am trying to figure out how to mix or write a new code to have a gallery with image doing fill_parent but i can slide sideways to see the other url linked images from my site. here are both parts of code i have: package com.mandarich.gallerygrid; import java.io.InputStream; import java.net.URL; import android.app.Activity; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.widget.ImageView; public class Gallery extends Activity { /** Called when the activity is first created. */ public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); ImageView imgView =(ImageView)findViewById(R.id.ImageView01); Drawable drawable = LoadImageFromWebOperations("http://www.mandarichmodels.com/hot-pics/"); imgView.setImageDrawable(drawable); } private Drawable LoadImageFromWebOperations(String url) { try { InputStream is = (InputStream) new URL(url).getContent(); Drawable d = Drawable.createFromStream(is, "src name"); return d; }catch (Exception e) { System.out.println("Exc="+e); return null; } } } and here is my gallery code package com.mandarich.Grid; import android.app.Activity; import android.content.Context; import android.content.res.TypedArray; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.Gallery; import android.widget.ImageView; import android.widget.Toast; import android.widget.AdapterView.OnItemClickListener; public class gridfinal extends Activity { private Gallery gallery; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); gallery = (Gallery) findViewById(R.id.examplegallery); gallery.setAdapter(new AddImgAdp(this)); gallery.setOnItemClickListener(new OnItemClickListener() { @SuppressWarnings("unchecked") public void onItemClick(AdapterView parent, View v, int position, long id) { // Displaying the position when the gallery item in clicked Toast.makeText(gridfinal.this, "Position=" + position, Toast.LENGTH_SHORT).show(); } }); } public class AddImgAdp extends BaseAdapter { int GalItemBg; private Context cont; // Adding images. private Integer[] Imgid = { R.drawable.cindy, R.drawable.clinton, R.drawable.colin, R.drawable.cybil, R.drawable.david, R.drawable.demi, R.drawable.drew }; public AddImgAdp(Context c) { cont = c; TypedArray typArray = obtainStyledAttributes(R.styleable.GalleryTheme); GalItemBg = typArray.getResourceId(R.styleable.GalleryTheme_android_galleryItemBackground, 0); typArray.recycle(); } public int getCount() { return Imgid.length; } public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { ImageView imgView = new ImageView(cont); imgView.setImageResource(Imgid[position]); // Fixing width & height for image to display imgView.setLayoutParams(new Gallery.LayoutParams(430, 370)); imgView.setScaleType(ImageView.ScaleType.FIT_XY); imgView.setBackgroundResource(GalItemBg); return imgView; } } }

    Read the article

  • How do I load an image from sd card into coverview

    - by Jolene
    I am doing an application which consists of a cover flow. Currently I am trying to make the cover flow images be obtained from the sd card. But I am not exactly sure how should I display the image. this is the image adapter: public class ImageAdapter extends BaseAdapter { int mGalleryItemBackground; private Context mContext; private FileInputStream fis; private Integer[] mImageIds = { //Instead of using r.drawable, i need to load the images from my sd card instead R.drawable.futsing, R.drawable.futsing2 }; private ImageView[] mImages; public ImageAdapter(Context c) { mContext = c; mImages = new ImageView[mImageIds.length]; } public int getCount() { return mImageIds.length; } public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } @TargetApi(8) public View getView(int position, View convertView, ViewGroup parent) { int screenSize = getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK; ImageView i = new ImageView(mContext); i.setImageResource(mImageIds[position]); switch(screenSize) { case Configuration.SCREENLAYOUT_SIZE_XLARGE: //Toast.makeText(this, "Small screen",Toast.LENGTH_LONG).show(); Display display4 = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); int rotation4 = display4.getRotation(); Log.d("XLarge:",String.valueOf(rotation4)); /** LANDSCAPE **/ if(rotation4 == 0 || rotation4 == 2) { i.setLayoutParams(new CoverFlow.LayoutParams(300, 300)); i.setScaleType(ImageView.ScaleType.CENTER_INSIDE); BitmapDrawable drawable = (BitmapDrawable) i.getDrawable(); drawable.setAntiAlias(true); return i; } /** PORTRAIT **/ else if (rotation4 == 1 || rotation4 == 3) { i.setLayoutParams(new CoverFlow.LayoutParams(650, 650)); i.setScaleType(ImageView.ScaleType.CENTER_INSIDE); BitmapDrawable drawable = (BitmapDrawable) i.getDrawable(); drawable.setAntiAlias(true); return i; } break; default: } return null; } /** Returns the size (0.0f to 1.0f) of the views * depending on the 'offset' to the center. */ public float getScale(boolean focused, int offset) { /* Formula: 1 / (2 ^ offset) */ return Math.max(0, 1.0f / (float)Math.pow(2, Math.abs(offset))); } } and this is how i download and save the file. I need to use the image saved and upload it into my coverflow // IF METHOD TO DOWNLOAD IMAGE void downloadFile() { new Thread(new Runnable(){ // RUN IN BACKGROUND THREAD TO AVOID FREEZING OF UI public void run(){ Bitmap bmImg; URL myFileUrl = null; try { //for (int i = 0; i < urlList.size(); i ++) //{ //url = urlList.get(i); myFileUrl = new URL("http://static.adzerk.net/Advertisers/d18eea9d28f3490b8dcbfa9e38f8336e.jpg"); // RETRIEVE IMAGE URL //} } catch (MalformedURLException e) { e.printStackTrace(); } try { HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection(); conn.setDoInput(true); conn.connect(); InputStream in = conn.getInputStream(); Log.i("im connected", "Download"); bmImg = BitmapFactory.decodeStream(in); saveFile(bmImg); } catch (IOException e) { e.printStackTrace(); }} }).start(); // START THREAD } // SAVE THE IMAGE AS JPG FILE private void saveFile(Bitmap bmImg) { File filename; try { // GET EXTERNAL STORAGE, SAVE FILE THERE File storagePath = new File(Environment.getExternalStorageDirectory(),"Covers"); storagePath.mkdirs(); filename = new File(storagePath + "/image.jpg"); FileOutputStream out = new FileOutputStream(filename); bmImg.compress(Bitmap.CompressFormat.JPEG, 90, out); out.flush(); out.close(); MediaStore.Images.Media.insertImage(getContentResolver(),filename.getAbsolutePath(), filename.getName(), filename.getName()); // ONCE THE DOWNLOAD FINISHES, CLOSE DIALOG Toast.makeText(getApplicationContext(), "Image Saved!", Toast.LENGTH_SHORT).show(); } catch (Exception e) { e.printStackTrace(); } }

    Read the article

  • StaleDataException: access closed cursor

    - by Aurora
    In my application, after enough clicking around, I get this error: 06-08 19:47:59.967: ERROR/AndroidRuntime(2429): java.lang.RuntimeException: Unable to pause activity {com.MYAPP.app/com.MYAPP.app.MainActivity}: android.database.StaleDataException: Access closed cursor What I have is a Tab Activity (my MainActivity), which has a ListActivity as the contents for each tab. Inside the onCreate for each ListActivity I get a cursor that represents the data to be displayed in that list. The onListItemClick for each list also creates another activity, so clicking on an item in the list will show more information about that item in a new screen. It's inconsistent, but after enough clicking into these new activities, or going back to the ListView from a new activity, the program crashes. In searching around for a solution to my problem, I did stumble upon registerDataSetObserver, but it doesn't seem to be the whole answer. I am also having trouble finding documentation on it, so I'm not sure I fully understand it. I have a custom ListAdapter that both my ListViews use and have called registerDataSetObservers on the cursors there. I have attached the relevant code from one of my ListActivities and from my custom ListAdapter class. The ListActivity. I have two of these, almost identical, except they both have different cursors created from different database queries: import com.MYAPP.app.listmanager.DeviceListAdapter; public class AllSensorsActivity extends ListActivity{ private DeviceListAdapter AllList; private DbManager db; protected Cursor AllCur; protected Cursor AllSensors; private static final String TAG = "AllSensorsActivity"; @Override public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); Log.e(TAG, "Calling All onCreate"); db = new DbManager(this); db.open(); AllCur = db.fetchAllDevices(); startManagingCursor(AllCur); AllSensors = db.fetchAllSensors(); startManagingCursor(AllSensors); AllList = new DeviceListAdapter(this, AllCur, AllSensors); setListAdapter(AllList); } @Override protected void onListItemClick(ListView l, View v, int position, long id){ String device_name = (String) ((DeviceListAdapter)getListAdapter()).getItem(position); String sensor_string = ((DeviceListAdapter)getListAdapter()).getSensors(id); Intent i = new Intent(this, SensorActivity.class); Bundle bundle = new Bundle(); bundle.putString("NAME", device_name); i.putExtras(bundle); bundle.putString("SENSORS", sensor_string); i.putExtras(bundle); this.startActivity(i); } The custom ListAdapter: public class DeviceListAdapter extends BaseAdapter { private static final String TAG = "DeviceListAdapter"; private Context mContext; private Cursor mSensors; private Cursor mDevices; protected MyDataSetObserver sensors_observer; protected MyDataSetObserver devices_observer; public DeviceListAdapter(Context context, Cursor devices, Cursor sensors){ mContext = context; mDevices = devices; mSensors = sensors; sensors_observer = new MyDataSetObserver(); mSensors.registerDataSetObserver(sensors_observer); devices_observer = new MyDataSetObserver(); mDevices.registerDataSetObserver(devices_observer); } // ... more functions and stuff that are not relevant go down here... } private class MyDataSetObserver extends DataSetObserver { public void onChanged(){ Log.e(TAG, "CHANGED CURSOR!"); } public void onInvalidated(){ Log.e(TAG, "INVALIDATED CURSOR!"); } } Should I just have MyDataSetObserver catch the exception and move on? I'd like a more robust solution than that if possible. Or is there some other way I could rearrange my program so that the staleDataException doesn't occur (as often)? I believe that it is happening because I am launching the new activity in my onListItemClick.

    Read the article

  • How do you set Android ViewPager to encompass only one View or Layout?

    - by Kyle
    I am struggling with the concepts needed to properly implement a view pager. By following some tutorials and referencing developer.android.com, I am able to get a view pager almost fully functional. The pager will flip through several text views that have been setup to say "My Message 0" through "My Message 9". The problem is that the view pager also flips the button on the bottom of the activity and the red block that is right above the button. I would like to have the view pager only cycle through the text. Would you please help me understand what I'm doing wrong? I have an activity that represents a dashboard: public class DashBoard extends FragmentActivity { private static final int NUMBER_OF_PAGES = 10; private ViewPager mViewPager; private MyFragmentPagerAdapter mMyFragmentPagerAdapter; public void onCreate(Bundle icicle){ super.onCreate(icicle); setContentView(R.layout.dashboard); mViewPager = (ViewPager) findViewById(R.id.viewpager); mMyFragmentPagerAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager()); mViewPager.setAdapter(mMyFragmentPagerAdapter); } private static class MyFragmentPagerAdapter extends FragmentPagerAdapter{ public MyFragmentPagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int index) { return PageFragment.newInstance("My Message " + index); } @Override public int getCount(){ return NUMBER_OF_PAGES; } } and a class for the page fragment: public class PageFragment extends Fragment { public static PageFragment newInstance(String title){ PageFragment pageFragment = new PageFragment(); Bundle bundle = new Bundle(); bundle.putString("title", title); pageFragment.setArguments(bundle); return pageFragment; } @Override public void onCreate(Bundle icicle){ super.onCreate(icicle); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle icicle){ View view = inflater.inflate(R.layout.dashboard, container, false); TextView textView = (TextView) view.findViewById(R.id.textViewPage); textView.setText(getArguments().getString("title")); return view; } } and finally, my xml for the dashboard: <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/dashbaordLabel" android:layout_width="match_parent" android:layout_height="wrap_content" > <android.support.v4.view.ViewPager android:id="@+id/viewpager" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_alignParentLeft="true" /> <TextView android:id="@+id/textViewPage" android:layout_width = "match_parent" android:layout_height= "wrap_content" /> <Button android:id="@+id/newGoalButton" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/stringNewGoal" android:layout_alignParentBottom="true" android:layout_alignParentLeft="true" android:onClick="createNewGoal" /> <RelativeLayout android:id="@+id/SpaceBottom" android:layout_width="match_parent" android:layout_height="75dp" android:layout_above="@id/newGoalButton" android:background="@color/red" > </RelativeLayout> </RelativeLayout> A note about my xml, I tried wrapping the text view in some view pager tags eg: <android.support.v4.view.ViewPager android:id="@+id/viewpager" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_alignParentLeft="true" > <TextView android:id="@+id/textViewPage" android:layout_width = "match_parent" android:layout_height= "wrap_content" /> </android.support.v4.view.ViewPager> But all that did was make the text view disappear from the screen, while the button and red block still cycled as in the original issue.

    Read the article

  • How do I add a namespace attribute to an element in JAXB when marshalling?

    - by Ryan Elkins
    I'm working with eBay's LMS (Large Merchant Services) and kept running into the error: org.xml.sax.SAXException: SimpleDeserializer encountered a child element, which is NOT expected, in something it was trying to deserialize. After alot of trial and error I traced the problem down. It turns out this works: <?xml version="1.0" encoding="UTF-8"?> <BulkDataExchangeRequests xmlns="urn:ebay:apis:eBLBaseComponents"> <Header> <Version>583</Version> <SiteID>0</SiteID> </Header> <AddFixedPriceItemRequest xmlns="urn:ebay:apis:eBLBaseComponents"> while this (what I've been sending) doesn't: <?xml version="1.0" encoding="UTF-8"?> <BulkDataExchangeRequests xmlns="urn:ebay:apis:eBLBaseComponents"> <Header> <Version>583</Version> <SiteID>0</SiteID> </Header> <AddFixedPriceItemRequest> The difference is the xml namespace attribute on the AddFixedPriceItemRequest . All of my XML is currently being marshalled via JAXB and I'm not sure what is the best way to go about adding a second xmlns attribute to a different element in my file. So that's the question. How do I add an xmlns attribute to another element in JAXB? UPDATE: package ebay.apis.eblbasecomponents; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "AddFixedPriceItemRequestType", propOrder = { "item" }) public class AddFixedPriceItemRequestType extends AbstractRequestType { @XmlElement(name = "Item") protected ItemType item; public ItemType getItem() { return item; } public void setItem(ItemType value) { this.item = value; } } Added class definition by request. UPDATE 2: Edited the above class like so to no effect: @XmlAccessorType(XmlAccessType.FIELD) @XmlType(namespace = "urn:ebay:apis:eBLBaseComponents", name = "AddFixedPriceItemRequestType", propOrder = { "item" }) public class AddFixedPriceItemRequestType UPDATE 3: Here is a snippet of the BulkDataExchangeRequestsType class. I tried throwing a namespace="urn:ebay:apis:eBLBaseComponents" into the @XmlElement for AddFixedPriceItemRequest but it didn't do anything. @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "BulkDataExchangeRequestsType", propOrder = { "header", "addFixedPriceItemRequest" }) public class BulkDataExchangeRequestsType { @XmlElement(name = "Header") protected MerchantDataRequestHeaderType header; @XmlElement(name = "AddFixedPriceItemRequest") protected List<AddFixedPriceItemRequestType> addFixedPriceItemRequest; UPDATE 4: Here's the hideous chunk of code that is updating the xml after marshalling for me. This is currently working although I'm not particulary proud of it. DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.newDocument(); marshaller.marshal(request, doc); NodeList nodes = doc.getChildNodes(); nodes = nodes.item(0).getChildNodes(); for(int i = 0; i < nodes.getLength(); i++){ Node node = nodes.item(i); if (!node.getNodeName().equals("Header")){ ((Element)node).setAttribute("xmlns", "urn:ebay:apis:eBLBaseComponents"); } } Update 5: For anyone else that runs into this problem with eBay and wonders why - The reasoning behind this most likely has to do with how eBay is handling these requests. The BulkDataExchange probably takes the XML payload, breaks it up, and send the pieces out to the Merchant or Trading API. The inner pieces of the payload then do not have the namespace and the get the error. This is a guess on my part but I wouldn't be surprised if this is what was going on behind the scenes. Thanks for all the help everyone.

    Read the article

  • Android AlertDialog wait for result in calling activity

    - by insanesam
    I am trying to use an AlertDialog in my app to select the quantity of an item. The problem is that the activity that calls the AlertDialog doesn't wait for it to update the item before it adds it to the SQLite Database and change intents. At the moment, the QuantitySelector (AlertDialog) appears, then disappears straight away and changes the MealActivity class (which is just a ListView that reads from the database) through the intent change with an update to the database with quantity 0. I need the Activity to wait for the AlertDialog to close before it updates the database. What would be the correct way of implementing this? Here is some code for you: QuantitySelector (which runs the alertdialog): public class QuantitySelector{ protected static final int RESULT_OK = 0; private Context _context; private DatabaseHandler db; private HashMap<String, Double> measures; private Item item; private View v; private EditText quan; private NumberPicker pick; private int value; private Quantity quantity; /** * Function calls the quantity selector AlertDialog * @param _c: The application context * @param item: The item to be added to consumption * @return The quantity that is consumed */ public void select(Context _c, Item item, Quantity quantity){ this._context = _c; this.item = item; this.quantity = quantity; db = new DatabaseHandler(_context); //Get the measures to display createData(); //Set up the custom view LayoutInflater inflater = LayoutInflater.from(_context); v = inflater.inflate(R.layout.quantity_selector, null); //Set up the input fields quan = (EditText) v.findViewById(R.id.quantityNumber); pick = (NumberPicker) v.findViewById(R.id.numberPicker1); //Set up the custom measures into pick pick.setMaxValue(measures.size()-1); pick.setDisplayedValues(measures.keySet().toArray(new String[0])); //Start the alert dialog runDialog(); } public void createData(){ measures = new HashMap<String, Double>(); //Get the measurements from the database if(item!=null){ measures.putAll(db.getMeasures(item)); } //Add grams as the default measurement if(!measures.keySet().contains("grams")){ //Add grams as a standard measure measures.put("grams", 1.0); } } public void runDialog(){ AlertDialog dialog = new AlertDialog.Builder(_context).setTitle("Select Quantity") .setView(v) .setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { //Change the consumption to the new quantity if(!quan.getText().toString().matches("")){ value = Integer.parseInt(quan.getText().toString()); //Check if conversion from other units is needed String s[] = pick.getDisplayedValues(); String a = s[pick.getValue()]; //Convert the chosen measure back to grams if(!a.equals("grams")){ for(String m : measures.keySet()){ if(m==a){ value = (int) (value * measures.get(m)); } } } } quantity.setQuantity(value); dialog.dismiss(); } }) .setNegativeButton("Cancel", null).create(); dialog.show(); } } The method from favouritesAdapter (which calls the alertdialog): add.setOnClickListener(new OnClickListener(){ public void onClick(View arg0) { QuantitySelector q = new QuantitySelector(); Quantity quan = new Quantity(); q.select(_context, db.getItem(p.getID()), quan); db.addConsumption(p.getID(), p.getFavouriteShortName(), quan.getQuantity(), "FAVOURITE"); Intent intent = new Intent(_context,MealActivity.class); _context.startActivity(intent); } }); All help is appreciated :)

    Read the article

  • Select Multiple Images Using GalleryView

    - by hwrdprkns
    Hi guys, I was just wondering if Android had built in code so that I could select multiple images in a gallery-view and then have those images exported as filenames in a string array(ex /sdcard/~f1.jpg, /sdcard/~f2.jpg,...). I have the gallery code here, but I'm not sure what modifications need to be made. Any help is appreciated. Thanks! // take_picture = (Button)findViewById(R.id.take_picture); // Here we set up a string array of the thumbnail ID column we want to // get back String[] proj = { MediaStore.Images.Thumbnails._ID }; if(proj.length == 0) { nopic.setVisibility(View.VISIBLE); } // Now we create the cursor pointing to the external thumbnail store cursor = managedQuery( MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, proj, // Which // columns // to // return null, // WHERE clause; which rows to return (all rows) null, // WHERE clause selection arguments (none) null); // Order-by clause (ascending by name) /* take_picture.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent i = new Intent(GalleryActivity.this, CameraActivity.class); startActivity(i); } }); */ // We now get the column index of the thumbnail id column_index = cursor .getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID); // Reference the Gallery view g = (Gallery) findViewById(R.id.gallery); if(proj.length == 0) { nopic.setVisibility(View.VISIBLE); g.setVisibility(View.GONE); } // Set the adapter to our custom adapter (below) g.setAdapter(new ImageAdapter(this)); // Set a item click listener, and just Toast the clicked position g.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView parent, View v, int position, long id) { // Now we want to actually get the data location of the file String[] proj = { MediaStore.Images.Media.DATA }; // We request our cursor again cursor = managedQuery( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, proj, // Which // columns // to // return null, // WHERE clause; which rows to return (all rows) null, // WHERE clause selection arguments (none) null); // Order-by clause (ascending by name) // We want to get the column index for the data uri column_index = cursor .getColumnIndexOrThrow(MediaStore.Images.Media.DATA); // Lets move to the selected item in the cursor cursor.moveToPosition((int) g.getSelectedItemId()); // And here we get the filename String filename = cursor.getString(column_index); Log.v("GalleryActivity", filename); Toast.makeText(GalleryActivity.this, filename, Toast.LENGTH_SHORT).show(); setPrefs(filename); Intent i = new Intent(GalleryActivity.this, OtherClass.class); startActivity(i); } }); } And the ImageAdapter code here: public class ImageAdapter extends BaseAdapter { int mGalleryItemBackground; public ImageAdapter(Context c) { mContext = c; // See res/values/attrs.xml for the that defines // Gallery1. TypedArray a = obtainStyledAttributes(R.styleable.Gallery); mGalleryItemBackground = a.getResourceId( R.styleable.Gallery_android_galleryItemBackground, 0); a.recycle(); } public int getCount() { return cursor.getCount(); } public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { ImageView i = new ImageView(mContext); if (convertView == null) { cursor.moveToPosition(position); int id = cursor.getInt(column_index); i.setImageURI(Uri.withAppendedPath( MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, "" + id)); i.setScaleType(ImageView.ScaleType.FIT_XY); i.setLayoutParams(new Gallery.LayoutParams(200, 200)); // The preferred Gallery item background i.setBackgroundResource(mGalleryItemBackground); } return i; } } Again any help is appreciateds! Just to let you guys know, the gallery works fine (for one image) as in it exports the filename correctly. Just need to know if there is an easy way to select multiples and export them. Thanks again!

    Read the article

  • add an image in listview

    - by danish
    Hi I would like to add more images in my list view as this code below only displays image 1 and 2 continuously in each row. What I want to do is display a different image for each different row. Here is mycode below; Thanks for any help. I am not good at java please change the code where necessary and I can then refer to it. public class starters extends ListActivity { private static class EfficientAdapter extends BaseAdapter { private LayoutInflater mInflater; private Bitmap mIcon1; private Bitmap mIcon2; private Bitmap mIcon3; private Bitmap mIcon4; private Bitmap mIcon5; private Bitmap mIcon6; private Bitmap mIcon7; private Bitmap mIcon8; private Bitmap mIcon9; private Bitmap mIcon10; public EfficientAdapter(Context context) { // Cache the LayoutInflate to avoid asking for a new one each time. mInflater = LayoutInflater.from(context); // Icons bound to the rows. mIcon1 = BitmapFactory.decodeResource(context.getResources(), R.drawable.starters1); mIcon2 = BitmapFactory.decodeResource(context.getResources(), R.drawable.starters2); mIcon3 = BitmapFactory.decodeResource(context.getResources(), R.drawable.starters3); mIcon4 = BitmapFactory.decodeResource(context.getResources(), R.drawable.starters4); mIcon5 = BitmapFactory.decodeResource(context.getResources(), R.drawable.starters5); mIcon6 = BitmapFactory.decodeResource(context.getResources(), R.drawable.starters6); mIcon7 = BitmapFactory.decodeResource(context.getResources(), R.drawable.starters7); mIcon8 = BitmapFactory.decodeResource(context.getResources(), R.drawable.starters8); mIcon9 = BitmapFactory.decodeResource(context.getResources(), R.drawable.starters9); mIcon10 = BitmapFactory.decodeResource(context.getResources(), R.drawable.starters10); } public int getCount() { return DATA.length; } public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { // A ViewHolder keeps references to children views to avoid unneccessary calls // to findViewById() on each row. ViewHolder holder; // When convertView is not null, we can reuse it directly, there is no need // to reinflate it. We only inflate a new View when the convertView supplied // by ListView is null. if (convertView == null) { convertView = mInflater.inflate(R.layout.starters, null); // Creates a ViewHolder and store references to the two children views // we want to bind data to. holder = new ViewHolder(); holder.text = (TextView) convertView.findViewById(R.id.text01); holder.text = (TextView) convertView.findViewById(R.id.secondLine); holder.icon = (ImageView) convertView.findViewById(R.id.icon01); convertView.setTag(holder); } else { // Get the ViewHolder back to get fast access to the TextView // and the ImageView. holder = (ViewHolder) convertView.getTag(); } // Bind the data efficiently with the holder. holder.text.setText(DATA[position]); holder.icon.setImageBitmap((position & 1) ==1 ? mIcon1 : mIcon2); return convertView; } static class ViewHolder { TextView text; ImageView icon; } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setListAdapter(new EfficientAdapter(this)); } private static final String[] DATA = { "Original nachos", "Toasted chicken and cheese quesadillas", "Chicken, lime and coriander nachos", "Spicy bean and cheese quesadillas", "Tuna and corn quesadillas", "Cheesy bean and sweetcorn nachos", "Crispy chicken, avocado and lime salad", "Beef and baby corn tostada", "Spicy mexican rice with chicken and prawns", "Chilli potato boats"}; }

    Read the article

  • Session state provider and global.asax not interacting properly?

    - by yodaj007
    I'm experimenting with creating a crude, proof-of-concept session state store provider in ASP.Net. But I've got a problem and I'm not sure what to do about it. The website works properly when using the InProc provider. The Session_Start in global.asax is called on session creation as it should. But not if I implement my own provider. The Session_Start method from global.asax isn't being called at all if a new session is being created (that is, I delete the session state file). Am I missing something important here? public class TestSessionProvider : SessionStateStoreProviderBase { private const string ROOT = "c:\\projects\\sessions\\"; private const int TIMEOUT_MINUTES = 30; public string ApplicationName { get { return HostingEnvironment.ApplicationVirtualPath; } } private string GetFilename(string id) { string filename = String.Format("{0}_{1}.session", ApplicationName, id); char[] invalids = Path.GetInvalidPathChars(); for (int i = 0; i < invalids.Length; i++) { filename = filename.Replace(invalids[i], '_'); } return Path.Combine(ROOT, Path.GetFileName(filename)); } public override void Initialize(string name, NameValueCollection config) { if (config == null) throw new ArgumentNullException("config"); if (String.IsNullOrEmpty(name)) name = "Sporkalicious"; base.Initialize(name, config); } public override SessionStateStoreData CreateNewStoreData(HttpContext context, int timeout) { SessionStateItemCollection items = new SessionStateItemCollection(); HttpStaticObjectsCollection objects = SessionStateUtility.GetSessionStaticObjects(context); return new SessionStateStoreData(items, objects, TIMEOUT_MINUTES); } /// <summary> /// The CreateUninitializedItem method is used with cookieless sessions when the regenerateExpiredSessionId /// attribute is set to true, which causes SessionStateModule to generate a new SessionID value when an /// expired session ID is encountered. /// </summary> /// <param name="context"></param> /// <param name="id"></param> /// <param name="timeout"></param> public override void CreateUninitializedItem(HttpContext context, string id, int timeout) { FileStream fs = File.Open(GetFilename(id), FileMode.CreateNew, FileAccess.Write, FileShare.None); BinaryWriter writer = new BinaryWriter(fs); SessionStateItemCollection coll = new SessionStateItemCollection(); coll.Serialize(writer); fs.Flush(); fs.Close(); } public override SessionStateStoreData GetItem(HttpContext context, string id, out bool locked, out TimeSpan lockAge, out object lockId, out SessionStateActions actions) { return GetItemExclusive(context, id, out locked, out lockAge, out lockId, out actions); } public override SessionStateStoreData GetItemExclusive(HttpContext context, string id, out bool locked, out TimeSpan lockAge, out object lockId, out SessionStateActions actions) { locked = false; lockAge = TimeSpan.FromDays(1); lockId = 0; actions = SessionStateActions.None; if (!File.Exists(GetFilename(id))) { return null; } FileStream fs = File.Open(GetFilename(id), FileMode.Open, FileAccess.ReadWrite, FileShare.Read); BinaryReader reader = new BinaryReader(fs); SessionStateItemCollection coll = SessionStateItemCollection.Deserialize(reader); fs.Close(); return new SessionStateStoreData(coll, new HttpStaticObjectsCollection(), TIMEOUT_MINUTES); } public override void ReleaseItemExclusive(HttpContext context, string id, object lockId) { } public override void RemoveItem(HttpContext context, string id, object lockId, SessionStateStoreData item) { File.Delete(GetFilename(id)); } public override void ResetItemTimeout(HttpContext context, string id) { } public override void SetAndReleaseItemExclusive(HttpContext context, string id, SessionStateStoreData item, object lockId, bool newItem) { if (!File.Exists(GetFilename(id))) { CreateUninitializedItem(context, id, 10); } FileStream fs = File.Open(GetFilename(id), FileMode.Truncate, FileAccess.Write, FileShare.None); BinaryWriter writer = new BinaryWriter(fs); SessionStateItemCollection coll = (SessionStateItemCollection)item.Items; coll.Serialize(writer); fs.Flush(); fs.Close(); } public override bool SetItemExpireCallback(SessionStateItemExpireCallback expireCallback) { return false; } public override void InitializeRequest(HttpContext context){} public override void EndRequest(HttpContext context){} public override void Dispose(){} }

    Read the article

< Previous Page | 2 3 4 5 6 7 8  | Next Page >