Rectangle 27 40

In your view, you have to cast it back to the original type. Without the cast, it's just an object.

<td>@((ViewBag.data as ICollection<Person>).First().FirstName)</td>

ViewBag is a C# 4 dynamic type. Entities returned from it are also dynamic unless cast. However, extension methods like .First() and all the other Linq ones do not work with dynamics.

If you want to display the whole list, it's as simple as this:

foreach (var person in ViewBag.data)
{
    <li>@person.FirstName</li>
}

Extension methods like .First() won't work, but this will.

hey thanx i got the value but can u tell me how can i fetch all the values assigned in the list?

asp.net mvc - How to display a list using ViewBag - Stack Overflow

asp.net-mvc asp.net-mvc-3 model-view-controller viewbag
Rectangle 27 4

package studRecords.one;

 import java.util.List;
 import java.util.Vector;

 import android.app.Activity;
 import android.app.ListActivity;
 import android.content.Context;
 import android.content.Intent;
 import android.net.ParseException;
 import android.os.Bundle;
 import android.view.LayoutInflater;
 import android.view.View;
 import android.view.ViewGroup;
 import android.widget.ArrayAdapter;
 import android.widget.ImageView;
 import android.widget.ListView;
 import android.widget.TextView;



public class studRecords extends ListActivity 
{
static String listName = "";
static String listUsn = "";
static Integer images;
private LayoutInflater layoutx;
private Vector<RowData> listValue;
RowData rd;

static final String[] names = new String[]
{
      "Name (Stud1)", "Name (Stud2)",   
      "Name (Stud3)","Name (Stud4)" 
};

static final String[] usn = new String[]
{
      "1PI08CS016","1PI08CS007","1PI08CS017","1PI08CS047"
};

private Integer[] imgid = 
{
  R.drawable.stud1,R.drawable.stud2,R.drawable.stud3,
  R.drawable.stud4
};

public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.mainlist);

    layoutx = (LayoutInflater) getSystemService(
    Activity.LAYOUT_INFLATER_SERVICE);
    listValue = new Vector<RowData>();
    for(int i=0;i<names.length;i++)
    {
        try
        {
            rd = new RowData(names[i],usn[i],i);
        } 
        catch (ParseException e) 
        {
            e.printStackTrace();
        }
        listValue.add(rd);
    }


   CustomAdapter adapter = new CustomAdapter(this, R.layout.list,
                                     R.id.detail, listValue);
   setListAdapter(adapter);
   getListView().setTextFilterEnabled(true);
}
   public void onListItemClick(ListView parent, View v, int position,long id)
   {            


       listName = names[position];
       listUsn = usn[position];
       images = imgid[position];




       Intent myIntent = new Intent();
       Intent setClassName = myIntent.setClassName("studRecords.one","studRecords.one.nextList");
       startActivity(myIntent);

   }
   private class RowData
   {

       protected String mNames;
       protected String mUsn;
       protected int mId;
       RowData(String title,String detail,int id){
       mId=id;
       mNames = title;
       mUsn = detail;
    }
       @Override
    public String toString()
       {
               return mNames+" "+mUsn+" "+mId;
       }
  }

              private class CustomAdapter extends ArrayAdapter<RowData> 
          {
      public CustomAdapter(Context context, int resource,
      int textViewResourceId, List<RowData> objects)
      {               
            super(context, resource, textViewResourceId, objects);
      }
      @Override
      public View getView(int position, View convertView, ViewGroup parent)
      {   
           ViewHolder holder = null;
           TextView title = null;
           TextView detail = null;
           ImageView i11=null;
           RowData rowData= getItem(position);
           if(null == convertView)
           {
                convertView = layoutx.inflate(R.layout.list, null);
                holder = new ViewHolder(convertView);
                convertView.setTag(holder);
           }
         holder = (ViewHolder) convertView.getTag();
         i11=holder.getImage();
         i11.setImageResource(imgid[rowData.mId]);
         title = holder.gettitle();
         title.setText(rowData.mNames);
         detail = holder.getdetail();
         detail.setText(rowData.mUsn);                                                     

         return convertView;
      }

        private class ViewHolder 
        {
            private View mRow;
            private TextView title = null;
            private TextView detail = null;
            private ImageView i11=null; 
            public ViewHolder(View row)
            {
                    mRow = row;
            }
            public TextView gettitle()
            {
                 if(null == title)
                 {
                     title = (TextView) mRow.findViewById(R.id.title);
                 }
                 return title;
            }     
            public TextView getdetail()
            {
                if(null == detail)
                {
                    detail = (TextView) mRow.findViewById(R.id.detail);
                }
                return detail;
            }
            public ImageView getImage()
            {
                    if(null == i11)
                    {
                        i11 = (ImageView) mRow.findViewById(R.id.img);
                    }
                    return i11;
            }   
        }
   } 
 }
<?xml version="1.0" encoding="utf-8"?>
             <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                 android:orientation="horizontal"
                 android:layout_width="fill_parent"
                 android:layout_height="fill_parent"
             >
             <ListView
                 android:id="@android:id/list"
                 android:layout_width="fill_parent"
                 android:layout_height="wrap_content"
              />
             </LinearLayout>

How to display a list of images in a ListView in Android? - Stack Over...

android
Rectangle 27 2

Here's how I load and cache images in a ListView that creates a contact list for the user. So imagine profile picture on the left, some text views on the right (which sounds close to the problem you're dealing with. Ignore the ugly debug tags and probably poor formatting (sorry). I guess this is kind of like LazyList but here's a detailed explanation in case anyone was confused.

private LruCache<String, Bitmap> memoryCache;
private HashMap<String, String> idPairs = new HashMap<String, String>();

In my approach I use an LruCache and a HashMap to track which user's images I've downloaded. You'll see how its implemented later but the idea is to avoid downloading stuff from the server unless you have to. Then in your onCreate() or some related method, initialize your cache.

final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
    final int cacheSize = maxMemory / 8;
    memoryCache = new LruCache<String, Bitmap>(cacheSize)  {
        @Override 
        protected int sizeOf(String key, Bitmap bitmap){
            return (bitmap.getRowBytes() * bitmap.getHeight()) / 1024; //don't use getByteCount for API < 12
        }
    };

My next step is to add the default "empty image" bitmap to the cache in case I reach an entry that does not have a picture associated with it. That way I only have to process and add this bitmap once

Bitmap defaultPicture = BitmapFactory.decodeResource(getResources(), R.drawable.default_user_picture);
    addBitmapToMemoryCache("default", defaultPicture);

Then its time to get the data you need for the list!

private class GetPeopleData extends AsyncTask<JSONArray, Void, Void> {

    @Override
    protected Void doInBackground(JSONArray...lists) {
        HttpClient httpClient = new DefaultHttpClient(); 
        HttpPost httpPost = new HttpPost();
        ResponseHandler <String> responseHandler = new BasicResponseHandler();
        if(DEBUG) Log.d("GET PEOPLE DATA TASK", lists[0].length() + " users");
        getUsers(lists[0], httpClient, httpPost, responseHandler);
        return null;
    }

    @Override
    protected void onPostExecute(Void result){
        updateUserListView();
    }

}

Here's a borring AsyncTask that takes a JSONArray of user data as an argument. I left out that part because it's pretty much just a basic HTTP download that doesn't need explanation. The getUsers method is where I start to put together what will be added to my ListView. What I do next is process the JSON downloaded from the server to create user objects that will be added it to a list of users that will be displayed.

private void getUsers(JSONArray userArray, HttpClient httpClient, HttpPost httpPost, ResponseHandler<String> responseHandler){
    if(DEBUG) Log.d("USERS ARRAY", userArray.length() + " users");
    try{

        users = new ArrayList<User>();
        if(DEBUG) Log.d("User Array -START", "" + users.size());
        //Go through userArray and get information needed for list
        for(int i = 0; i < userArray.length(); i++){
            User u = new User();
            if(DEBUG) Log.d("User Array - ADD USER", "" + users.size());
            String profileId = userArray.getJSONObject(i).getString("profileid");
            u.setId(userArray.getJSONObject(i).getString("id"));
            u.setDisplayName(userArray.getJSONObject(i).getString("displayname"));
            u.setStatus(userArray.getJSONObject(i).getString("status"));

            //check HashMap for sender/profileid pair
            if(idPairs.containsKey(profileId)){
                if(DEBUG) Log.d("idPairs", "User in HashMap");
                profileId = idPairs.get(profileId);
            } else {
                if(DEBUG) Log.d("idPairs", "User not in HashMap. Add profileId");
                idPairs.put("profileId", profileId);
            }
            u.setProfilePicture(getProfilePictureFromCache(profileId, httpClient, httpPost, responseHandler)); //check cache for image
            users.add(u);
            if(DEBUG) Log.d("User info", u.toString());
        }
    } catch (Exception e) {
        Log.e("BACKGROUND_PROC", e.getMessage());
    }
}

I associate the picture with the user object that will eventually be displayed. I figure this isn't a total waste of time since the image is pulled from the bitmap cache

private Bitmap getProfilePictureFromCache(String profileId, HttpClient httpClient, HttpPost httpPost, ResponseHandler<String> responseHandler){
    Bitmap defaultPicture = getBitmapFromMemCache("default");
    Bitmap profilePicture = getBitmapFromMemCache(profileId);
    if(profilePicture != null){
        return profilePicture;
    } else {        
        String pictureString = getProfilePic(profileId, httpClient, httpPost, responseHandler);
        if(!pictureString.isEmpty()){       
            byte[] decodedString = Base64.decode(pictureString, Base64.DEFAULT);
            profilePicture = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
            addBitmapToMemoryCache(profileId, profilePicture);
            if(DEBUG) Log.d("MEMCACHE", "Download and store picture for " + profileId);
            return profilePicture;
        } else if (defaultPicture != null && pictureString.equals(null)) {
            if(DEBUG) Log.d("MEMCACHE", "Load default picture");
            return defaultPicture;
        }
    }
    return defaultPicture;
}

If a picture exists in the cache it is returned, if not it is downloaded. For me, displaying users, each picture is cached according to userid so even if someone were to appear more than once in the list, there would only be one picture stored in the cache for that user.

ImageView profile_picture = (ImageView) v.findViewById(R.id.profile_picture);
if(profile_picture != null){
                profile_picture.setImageBitmap(u.getProfilePicture());
            }

The only thing left to do is find the ImageView in your adapter and set that view to the picture you associated with the object in your list.

android - Caching images and displaying - Stack Overflow

android json imageview universal-image-loader lazylist
Rectangle 27 1

You don't need a custom model binder. When your IntervieweeSelectLists is returned in the controller action, your lists will be empty as the data passed back from a post will not contain that information. So you have a object that has the answers you need with empty lists. Now lets say something doesn't validate and you need to display all the lists again. Well the controllers actions knows when this model is going to be displayed so the lists only need to be populated before the model is passed into a view. If you don't need to pass the model into a view, and just store the results, as there is no need to populate the lists.

Well, the reason I was considering a custom model binder is that, when I tried putting the above class in the parameter list of the Action, all the fields came back null (or default value), even though Model.IsValid was true. It just seemed like the default model binder couldn't figure it out. But it could be that I haven't followed the correct naming convention for the fields.

OK, when I tried changing the HTML field names to match what's in the class, I am getting values back (progress!). However, some of the fields returned are buried in lower levels of the class -- i.e., the selected district property is within the districtFilterLists object. It's not picking that up at all -- districtFilterLists is null. So I think I do need a custom model builder -- or drastically change my ViewModel class. But thanks, I feel I am finally getting somewhere. I have no colleagues -- I am the entire IT dept. -- so I needed someone to bounce ideas off of.

Sounds like you are writing your HTML manually. You should use the DisplayFor and EditFor html helpers to create the html for you. They will automatically create the names for you. I would highly recommend checking out the ASP.Net MVC demos on asp.net. (Also Model.IsValid is only validating, if you don't have validation data annotations, then the property is valid by default)

Usually I do use HTML helpers (though not the "For" ones), but I have discovered you can't use HTML helpers when you want to set the value of a control programmatically -- e.g. I have an "add note" textbox with submit button. When a note is added, it shows up in a table underneath. At that point I want the add note textbox to go blank, but whatever the user entered remains there if it's a helper. I don't feel that's user-friendly (it's not the expected behavior to most users) so I avoid HTML helpers in those cases. Thanks for the links though; I will check them out.

BTW, I did end up writing a custom model binder for my notes list, as I could not figure out a way to get the default model binder to bind it -- it's a list where each one has an edit and delete button (similar to a datagrid) and the buttons do not have identical names -- the note ID is appended to the name. My custom binder works great and I am much more knowledgable than yesterday. :) Thanks for getting me pointed in the right direction.

asp.net mvc - MVC Model Binding Confusion - Stack Overflow

asp.net-mvc binding
Rectangle 27 0

You can use this {% for i in a %} IF you are passing a list in the template from the views. Like the query items=models.products.objects.filter(pk=request.session["a"]) will provide a list of the object over which you can iterate and display attributes. You can use a dictionary for this if you want to store multiple items. request.session['a']['value1'] = 'value1'

You can access the dictionary in templates by using

{% for key, val in dict.items %}
    <td>{{ key }}</td>
    <td>{{ val }}</td>
{%  endfor  %}

OR you can use for loop counter to differentiate between values while stroing like this

count=0 

for i in val: 
  count+=1   
  request.session[a+str(count)]=i

Then you can access it like request.session["a1"] and so on for other values Hope that helps

python - A few basic django questions - Stack Overflow

python django django-views django-sessions
Rectangle 27 0

First of all: Don't do this kind of work in a view layer. You should write an object that will hold values that you need to display in JSP, iterate both of your lists creating new instance of this view object with needed values and putting it to some list. Then in JSP you can iterate that list of the view objects.

That being said... moving forward to the hackish and not a best practice solution. I will demonstrate it on list which consist of String-s and Integer-s, if it is Integer than we want to call intValue() method, in case of String toUpperCase() method will be called. Because, by default, calling not existing property doesn't produce value that we can compare, we will abuse #attr to evaluate calls to the instance properties.

Note this won't work if you have null values in your properties.

And again don't do it in the view

java - How to show 2 merged Arraylists merged using s:merge in same s:...

java jsp struts2 ognl
Rectangle 27 0

If you have an List with different object that can be of different kinds and need different views to display. Do it that way:

Let the object define the view by themselves. Implement an interface ViewProvider on every object. This interface should provide the method getView() which then can be called in the adapter.

The adapter has now only to get the element out of the list full of ViewProviders and call the method getView to get the view.

You will not have to worry about the recycling off the views as the views are stored in every ViewProvider and will be created only once. The update of the fields (if any) can then also be made on the Object side and not in the adapter. But you have to notify the adapter about the data change by calling notifyDataSetChanged()

Thanks for the reply. I like the idea but I am still unsure of doing it this way. Can you provide a code sample? Thanks :)

java - Generic ListView Adapter - Stack Overflow

java android android-layout android-listview android-adapter
Rectangle 27 0

/*
 * Copyright (C) 2007 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package android.app;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ComponentInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PaintFlagsDrawFilter;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.PaintDrawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ListView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


/**
 * Displays a list of all activities which can be performed
 * for a given intent. Launches when clicked.
 *
 */
public abstract class LauncherActivity extends ListActivity {
    Intent mIntent;
    PackageManager mPackageManager;
    IconResizer mIconResizer;

    /**
     * An item in the list
     */
    public static class ListItem {
        public ResolveInfo resolveInfo;
        public CharSequence label;
        public Drawable icon;
        public String packageName;
        public String className;
        public Bundle extras;

        ListItem(PackageManager pm, ResolveInfo resolveInfo, IconResizer resizer) {
            this.resolveInfo = resolveInfo;
            label = resolveInfo.loadLabel(pm);
            ComponentInfo ci = resolveInfo.activityInfo;
            if (ci == null) ci = resolveInfo.serviceInfo;
            if (label == null && ci != null) {
                label = resolveInfo.activityInfo.name;
            }

            if (resizer != null) {
                icon = resizer.createIconThumbnail(resolveInfo.loadIcon(pm));
            }
            packageName = ci.applicationInfo.packageName;
            className = ci.name;
        }

        public ListItem() {
        }
    }

    /**
     * Adapter which shows the set of activities that can be performed for a given intent.
     */
    private class ActivityAdapter extends BaseAdapter implements Filterable {
        private final Object lock = new Object();
        private ArrayList<ListItem> mOriginalValues;

        protected final IconResizer mIconResizer;
        protected final LayoutInflater mInflater;

        protected List<ListItem> mActivitiesList;

        private Filter mFilter;

        public ActivityAdapter(IconResizer resizer) {
            mIconResizer = resizer;
            mInflater = (LayoutInflater) LauncherActivity.this.getSystemService(
                    Context.LAYOUT_INFLATER_SERVICE);
            mActivitiesList = makeListItems();
        }

        public Intent intentForPosition(int position) {
            if (mActivitiesList == null) {
                return null;
            }

            Intent intent = new Intent(mIntent);
            ListItem item = mActivitiesList.get(position);
            intent.setClassName(item.packageName, item.className);
            if (item.extras != null) {
                intent.putExtras(item.extras);
            }
            return intent;
        }

        public ListItem itemForPosition(int position) {
            if (mActivitiesList == null) {
                return null;
            }

            return mActivitiesList.get(position);
        }

        public int getCount() {
            return mActivitiesList != null ? mActivitiesList.size() : 0;
        }

        public Object getItem(int position) {
            return position;
        }

        public long getItemId(int position) {
            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            View view;
            if (convertView == null) {
                view = mInflater.inflate(
                        com.android.internal.R.layout.activity_list_item_2, parent, false);
            } else {
                view = convertView;
            }
            bindView(view, mActivitiesList.get(position));
            return view;
        }

        private void bindView(View view, ListItem item) {
            TextView text = (TextView) view;
            text.setText(item.label);
            if (item.icon == null) {
                item.icon = mIconResizer.createIconThumbnail(
                        item.resolveInfo.loadIcon(getPackageManager()));
            }
            text.setCompoundDrawablesWithIntrinsicBounds(item.icon, null, null, null);
        }

        public Filter getFilter() {
            if (mFilter == null) {
                mFilter = new ArrayFilter();
            }
            return mFilter;
        }

        /**
         * An array filters constrains the content of the array adapter with a prefix. Each
         * item that does not start with the supplied prefix is removed from the list.
         */
        private class ArrayFilter extends Filter {
            @Override
            protected FilterResults performFiltering(CharSequence prefix) {
                FilterResults results = new FilterResults();

                if (mOriginalValues == null) {
                    synchronized (lock) {
                        mOriginalValues = new ArrayList<ListItem>(mActivitiesList);
                    }
                }

                if (prefix == null || prefix.length() == 0) {
                    synchronized (lock) {
                        ArrayList<ListItem> list = new ArrayList(mOriginalValues);
                        results.values = list;
                        results.count = list.size();
                    }
                } else {
                    final String prefixString = prefix.toString().toLowerCase();

                    ArrayList<ListItem> values = mOriginalValues;
                    int count = values.size();

                    ArrayList<ListItem> newValues = new ArrayList(count);

                    for (int i = 0; i < count; i++) {
                        ListItem item = values.get(i);

                        String[] words = item.label.toString().toLowerCase().split(" ");
                        int wordCount = words.length;

                        for (int k = 0; k < wordCount; k++) {
                            final String word = words[k];

                            if (word.startsWith(prefixString)) {
                                newValues.add(item);
                                break;
                            }
                        }
                    }

                    results.values = newValues;
                    results.count = newValues.size();
                }

                return results;
            }

            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {
                //noinspection unchecked
                mActivitiesList = (List<ListItem>) results.values;
                if (results.count > 0) {
                    notifyDataSetChanged();
                } else {
                    notifyDataSetInvalidated();
                }
            }
        }
    }

    /**
     * Utility class to resize icons to match default icon size.  
     */
    public class IconResizer {
        // Code is borrowed from com.android.launcher.Utilities. 
        private int mIconWidth = -1;
        private int mIconHeight = -1;

        private final Rect mOldBounds = new Rect();
        private Canvas mCanvas = new Canvas();

        public IconResizer() {
            mCanvas.setDrawFilter(new PaintFlagsDrawFilter(Paint.DITHER_FLAG,
                    Paint.FILTER_BITMAP_FLAG));

            final Resources resources = LauncherActivity.this.getResources();
            mIconWidth = mIconHeight = (int) resources.getDimension(
                    android.R.dimen.app_icon_size);
        }

        /**
         * Returns a Drawable representing the thumbnail of the specified Drawable.
         * The size of the thumbnail is defined by the dimension
         * android.R.dimen.launcher_application_icon_size.
         *
         * This method is not thread-safe and should be invoked on the UI thread only.
         *
         * @param icon The icon to get a thumbnail of.
         *
         * @return A thumbnail for the specified icon or the icon itself if the
         *         thumbnail could not be created. 
         */
        public Drawable createIconThumbnail(Drawable icon) {
            int width = mIconWidth;
            int height = mIconHeight;

            final int iconWidth = icon.getIntrinsicWidth();
            final int iconHeight = icon.getIntrinsicHeight();

            if (icon instanceof PaintDrawable) {
                PaintDrawable painter = (PaintDrawable) icon;
                painter.setIntrinsicWidth(width);
                painter.setIntrinsicHeight(height);
            }

            if (width > 0 && height > 0) {
                if (width < iconWidth || height < iconHeight) {
                    final float ratio = (float) iconWidth / iconHeight;

                    if (iconWidth > iconHeight) {
                        height = (int) (width / ratio);
                    } else if (iconHeight > iconWidth) {
                        width = (int) (height * ratio);
                    }

                    final Bitmap.Config c = icon.getOpacity() != PixelFormat.OPAQUE ?
                                Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
                    final Bitmap thumb = Bitmap.createBitmap(mIconWidth, mIconHeight, c);
                    final Canvas canvas = mCanvas;
                    canvas.setBitmap(thumb);
                    // Copy the old bounds to restore them later
                    // If we were to do oldBounds = icon.getBounds(),
                    // the call to setBounds() that follows would
                    // change the same instance and we would lose the
                    // old bounds
                    mOldBounds.set(icon.getBounds());
                    final int x = (mIconWidth - width) / 2;
                    final int y = (mIconHeight - height) / 2;
                    icon.setBounds(x, y, x + width, y + height);
                    icon.draw(canvas);
                    icon.setBounds(mOldBounds);
                    icon = new BitmapDrawable(getResources(), thumb);
                } else if (iconWidth < width && iconHeight < height) {
                    final Bitmap.Config c = Bitmap.Config.ARGB_8888;
                    final Bitmap thumb = Bitmap.createBitmap(mIconWidth, mIconHeight, c);
                    final Canvas canvas = mCanvas;
                    canvas.setBitmap(thumb);
                    mOldBounds.set(icon.getBounds());
                    final int x = (width - iconWidth) / 2;
                    final int y = (height - iconHeight) / 2;
                    icon.setBounds(x, y, x + iconWidth, y + iconHeight);
                    icon.draw(canvas);
                    icon.setBounds(mOldBounds);
                    icon = new BitmapDrawable(getResources(), thumb);
                }
            }

            return icon;
        }
    }

    @Override
    protected void onCreate(Bundle icicle) {
        super.onCreate(icicle);

        mPackageManager = getPackageManager();

        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
        setProgressBarIndeterminateVisibility(true);
        onSetContentView();

        mIconResizer = new IconResizer();

        mIntent = new Intent(getTargetIntent());
        mIntent.setComponent(null);
        mAdapter = new ActivityAdapter(mIconResizer);

        setListAdapter(mAdapter);
        getListView().setTextFilterEnabled(true);

        setProgressBarIndeterminateVisibility(false);
    }

    /**
     * Override to call setContentView() with your own content view to
     * customize the list layout.
     */
    protected void onSetContentView() {
        setContentView(com.android.internal.R.layout.activity_list);
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        Intent intent = intentForPosition(position);
        startActivity(intent);
    }

    /**
     * Return the actual Intent for a specific position in our
     * {@link android.widget.ListView}.
     * @param position The item whose Intent to return
     */
    protected Intent intentForPosition(int position) {
        ActivityAdapter adapter = (ActivityAdapter) mAdapter;
        return adapter.intentForPosition(position);
    }

    /**
     * Return the {@link ListItem} for a specific position in our
     * {@link android.widget.ListView}.
     * @param position The item to return
     */
    protected ListItem itemForPosition(int position) {
        ActivityAdapter adapter = (ActivityAdapter) mAdapter;
        return adapter.itemForPosition(position);
    }

    /**
     * Get the base intent to use when running
     * {@link PackageManager#queryIntentActivities(Intent, int)}.
     */
    protected Intent getTargetIntent() {
        return new Intent();
    }

    /**
     * Perform query on package manager for list items.  The default
     * implementation queries for activities.
     */
    protected List<ResolveInfo> onQueryPackageManager(Intent queryIntent) {
        return mPackageManager.queryIntentActivities(queryIntent, /* no flags */ 0);
    }

    /**
     * Perform the query to determine which results to show and return a list of them.
     */
    public List<ListItem> makeListItems() {
        // Load all matching activities and sort correctly
        List<ResolveInfo> list = onQueryPackageManager(mIntent);
        Collections.sort(list, new ResolveInfo.DisplayNameComparator(mPackageManager));

        ArrayList<ListItem> result = new ArrayList(list.size());
        int listSize = list.size();
        for (int i = 0; i < listSize; i++) {
            ResolveInfo resolveInfo = list.get(i);
            result.add(new ListItem(mPackageManager, resolveInfo, null));
        }

        return result;
    }
}

android - List Filter Custom Adapter dont give result - Stack Overflow

android
Rectangle 27 0

public class LoadImagesFromSDCardActivity extends Activity implements
OnItemClickListener {

    /**
     * Grid view holding the images.
     */
    private GridView sdcardImages;
    /**
     * Image adapter for the grid view.
     */
    private ImageAdapter imageAdapter;
    /**
     * Display used for getting the width of the screen. 
     */
    private Display display;

    /**
     * Creates the content view, sets up the grid, the adapter, and the click listener.
     * 
     * @see android.app.Activity#onCreate(android.os.Bundle)
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);        
        // Request progress bar
        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
        setContentView(R.layout.sdcard);

        display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();

        setupViews();
        setProgressBarIndeterminateVisibility(true); 
        loadImages();
    }

    /**
     * Free up bitmap related resources.
     */
    protected void onDestroy() {
        super.onDestroy();
        final GridView grid = sdcardImages;
        final int count = grid.getChildCount();
        ImageView v = null;
        for (int i = 0; i < count; i++) {
            v = (ImageView) grid.getChildAt(i);
            ((BitmapDrawable) v.getDrawable()).setCallback(null);
        }
    }
    /**
     * Setup the grid view.
     */
    private void setupViews() {
        sdcardImages = (GridView) findViewById(R.id.sdcard);
        sdcardImages.setNumColumns(display.getWidth()/95);
        sdcardImages.setClipToPadding(false);
        sdcardImages.setOnItemClickListener(LoadImagesFromSDCardActivity.this);
        imageAdapter = new ImageAdapter(getApplicationContext()); 
        sdcardImages.setAdapter(imageAdapter);
    }
    /**
     * Load images.
     */
    private void loadImages() {
        final Object data = getLastNonConfigurationInstance();
        if (data == null) {
            new LoadImagesFromSDCard().execute();
        } else {
            final LoadedImage[] photos = (LoadedImage[]) data;
            if (photos.length == 0) {
                new LoadImagesFromSDCard().execute();
            }
            for (LoadedImage photo : photos) {
                addImage(photo);
            }
        }
    }
    /**
     * Add image(s) to the grid view adapter.
     * 
     * @param value Array of LoadedImages references
     */
    private void addImage(LoadedImage... value) {
        for (LoadedImage image : value) {
            imageAdapter.addPhoto(image);
            imageAdapter.notifyDataSetChanged();
        }
    }

    /**
     * Save bitmap images into a list and return that list. 
     * 
     * @see android.app.Activity#onRetainNonConfigurationInstance()
     */
    @Override
    public Object onRetainNonConfigurationInstance() {
        final GridView grid = sdcardImages;
        final int count = grid.getChildCount();
        final LoadedImage[] list = new LoadedImage[count];

        for (int i = 0; i < count; i++) {
            final ImageView v = (ImageView) grid.getChildAt(i);
            list[i] = new LoadedImage(((BitmapDrawable) v.getDrawable()).getBitmap());
        }

        return list;
    }
    /**
     * Async task for loading the images from the SD card. 
     * 
     * @author Mihai Fonoage
     *
     */
    class LoadImagesFromSDCard extends AsyncTask<Object, LoadedImage, Object> {

        /**
         * Load images from SD Card in the background, and display each image on the screen. 
         *  
         * @see android.os.AsyncTask#doInBackground(Params[])
         */
        @Override
        protected Object doInBackground(Object... params) {
            //setProgressBarIndeterminateVisibility(true); 
            Bitmap bitmap = null;
            Bitmap newBitmap = null;
            Uri uri = null;            

            // Set up an array of the Thumbnail Image ID column we want
            String[] projection = {MediaStore.Images.Thumbnails._ID};
            // Create the cursor pointing to the SDCard
            Cursor cursor = managedQuery( MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
                    projection, // Which columns to return
                    null,       // Return all rows
                    null,       
                    null); 
            int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID);
            int size = cursor.getCount();
            // If size is 0, there are no images on the SD Card.
            if (size == 0) {
                //No Images available, post some message to the user
            }
            int imageID = 0;
            for (int i = 0; i < size; i++) {
                cursor.moveToPosition(i);
                imageID = cursor.getInt(columnIndex);
                uri = Uri.withAppendedPath(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, "" + imageID);
                try {
                    bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
                    if (bitmap != null) {
                        newBitmap = Bitmap.createScaledBitmap(bitmap, 70, 70, true);
                        bitmap.recycle();
                        if (newBitmap != null) {
                            publishProgress(new LoadedImage(newBitmap));
                        }
                    }
                } catch (IOException e) {
                    //Error fetching image, try to recover
                }
            }
            cursor.close();
            return null;
        }
        /**
         * Add a new LoadedImage in the images grid.
         *
         * @param value The image.
         */
        @Override
        public void onProgressUpdate(LoadedImage... value) {
            addImage(value);
        }
        /**
         * Set the visibility of the progress bar to false.
         * 
         * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
         */
        @Override
        protected void onPostExecute(Object result) {
            setProgressBarIndeterminateVisibility(false);
        }
    }

    /**
     * Adapter for our image files. 
     * 
     * @author Mihai Fonoage
     *
     */
    class ImageAdapter extends BaseAdapter {

        private Context mContext; 
        private ArrayList<LoadedImage> photos = new ArrayList<LoadedImage>();

        public ImageAdapter(Context context) { 
            mContext = context; 
        } 

        public void addPhoto(LoadedImage photo) { 
            photos.add(photo); 
        } 

        public int getCount() { 
            return photos.size(); 
        } 

        public Object getItem(int position) { 
            return photos.get(position); 
        } 

        public long getItemId(int position) { 
            return position; 
        } 

        public View getView(int position, View convertView, ViewGroup parent) { 
            final ImageView imageView; 
            if (convertView == null) { 
                imageView = new ImageView(mContext); 
            } else { 
                imageView = (ImageView) convertView; 
            } 
            imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
            imageView.setPadding(8, 8, 8, 8);
            imageView.setImageBitmap(photos.get(position).getBitmap());
            return imageView; 
        } 
    }

    /**
     * A LoadedImage contains the Bitmap loaded for the image.
     */
    private static class LoadedImage {
        Bitmap mBitmap;

        LoadedImage(Bitmap bitmap) {
            mBitmap = bitmap;
        }

        public Bitmap getBitmap() {
            return mBitmap;
        }
    }
    /**
     * When an image is clicked, load that image as a puzzle. 
     */
    public void onItemClick(AdapterView<?> parent, View v, int position, long id) {        
        int columnIndex = 0;
        String[] projection = {MediaStore.Images.Media.DATA};
        Cursor cursor = managedQuery( MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
                projection,
                null, 
                null, 
                null);
        if (cursor != null) {
            columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToPosition(position);
            String imagePath = cursor.getString(columnIndex); 

            FileInputStream is = null;
            BufferedInputStream bis = null;
            try {
                is = new FileInputStream(new File(imagePath));
                bis = new BufferedInputStream(is);
                Bitmap bitmap = BitmapFactory.decodeStream(bis);
                Bitmap useThisBitmap = Bitmap.createScaledBitmap(bitmap, parent.getWidth(), parent.getHeight(), true);
                bitmap.recycle();
                //Display bitmap (useThisBitmap)
            } 
            catch (Exception e) {
                //Try to recover
            }
            finally {
                try {
                    if (bis != null) {
                        bis.close();
                    }
                    if (is != null) {
                        is.close();
                    }
                    cursor.close();
                    projection = null;
                } catch (Exception e) {
                }
            }
        }
    }

}
<GridView  
    android:id="@+id/sdcard"
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"
    android:verticalSpacing="10dp"
    android:horizontalSpacing="10dp" 
    android:stretchMode="columnWidth"
    android:gravity="center" />

android - Set an image to wallpaper - Stack Overflow

android image onclick wallpaper
Rectangle 27 0

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.ArrayList;
import java.util.zip.GZIPInputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ListActivity;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class Courses extends Activity {

    ArrayList<String> items = new ArrayList<String>();

    //URL requestUrl = new URL(url);
    JSONArray courses = null;
    //private static final String TAG_COURSES = "Courses";
    static JSONObject jObj = null;
    static String json = "";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.courses);
        new MyTask().execute("http://redsox.tcs.auckland.ac.nz/734A/CSService.svc/courses");

    }


    private class MyTask extends AsyncTask<String, Void, JSONObject> {

        @Override
        protected JSONObject doInBackground(String... urls) {
           // return loadJSON(url);
            String url = new String(urls[0]);
            try {

                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                //HttpPost httpPost = new HttpPost(url);
                HttpGet httpGet = new HttpGet(url);
                HttpResponse httpResponse = httpClient.execute(httpGet);

                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();

            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
          try {
            /*BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "UTF-8"), 8);*/
            InputStream inputStream = is;
            GZIPInputStream input = new GZIPInputStream(inputStream);
            InputStreamReader reader = new InputStreamReader(input);
            BufferedReader in = new BufferedReader(reader);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = in.readLine()) != null) {
                sb.append(line);
                //System.out.println(line);
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object

        try {

            JSONArray courses = new JSONArray(json);
            //JSONArray people = new JSONArray(json);
            for (int i = 0; i < courses.length(); i++) {
                //System.out.println(courses.getJSONObject(i).toString());
                JSONObject c = courses.getJSONObject(i);

                // Storing each json item in variable
                String course_id = c.getString("codeField");
                String course_name = c.getString("titleField");
                String course_semester = c.getString("semesterField");

                items.add(course_id +"\n"+course_name+"\t"+course_semester);

                /*Log.v("--", "Course:" + course_id + "\n Course Title: " + course_name
                        + "\n Semesters offered: " + course_semester);*/
            }


            //jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        } 


        // return JSON String
        return jObj;
        }

        @SuppressWarnings("unchecked")
        protected void onPostExecute(JSONObject json) {
            ListView myListView = (ListView)findViewById(R.id.coursesList);
            myListView.setAdapter(new ArrayAdapter(getApplicationContext(), android.R.layout.simple_list_item_1, items));

    }
    }




}

android - How can I parse a JSON object and display it in a list view?...

android json android-layout android-asynctask
Rectangle 27 0

Background (you probably know this, but just in case): An adapter contains a collection of objects and uses info from these objects to populate Views (each view is a line item in the list). The list view is in charge of displaying those views. For performance reasons the ListView will recycle views that are no longer visible because they scrolled off the top or the bottom of the list. Here's how it does it:

When the ListView needs a new view to display it calls the Adapter's getView with an integer argument "position" to indicate which object in the Adapter's collection it wants to see (position is just a number from 1 to N -1) where N is the count of objects in the adapter.

If it has any views that are no longer visible, it will pass one of them in to the Adapter, too, as "convertView" This says "reuse this old view rather than creating a new one". A big performance win.

The code in the article attaches a ViewHolder object to each view it creates that, among other things, contains the position of the object requested by the ListView. In the article's code, this position is stashed away inside the ViewHolder along with a pointer to the field within the view that will contain the image. The ViewHolder is attached to the View as a tag (a separate topic).

If the view gets recycled to hold a different object (at a different position) then ListView will call Adapter.getView(newPosition, oldView...) The code in the article will store new position into the ViewHolder attached to the oldView. {make sense so far?) and start loading this new image to put into the view.

Now in the article, it is starting an AsyncTask to retrieve data that should go into the view) This task has the position (from the getView call) and the holder (from the oldView). The position tells it what data was requested. The holder tells it what data should currently be diplayed in this view and where to put it once it shows up.

If the view gets recycled again while the AsyncTask is still running, the position in the holder will have been changed so these numbers won't match and the AsyncTask knows it's data is no longer needed.

As far as the uniqueness of position goes, if the collection of objects contained in the Adapter is unchanged, then each position number will refer a particular object in the Adapter. Even if the view scrolled off, then scrolled back and by accident was asked to contain the same position, it would be the same object so the AsyncTask can safely populate the view. If, on the other hand, the collection of data changes there might be issues to address. That, too is a solvable problem but beyond the scope of the article you referenced.

I get it now. I forgot that the Holder was actually being changed outside of the AsyncTask. And it kinda makes sense that position doesn't get reset. I'll accept your answer cause you were first even though Marcins answer was simpler.

In my implementation, I used a uid so @Dale Wilson concerns do not affect it.

android - Async image loading, check if an image is recycled - Stack O...

android android-listview android-asynctask
Rectangle 27 0

The reason your TextViews are displaying information like com.example.gpstest1.SavedLocation@41eb8128 is that you haven't overriden the toString() method in your SavedLocation class.

The ArrayAdapter class has no idea how to convert your Java objects into a readable format. It can't read your mind and determine what a valid textual representation of a SavedLocation might be. The best it can do is call toString() on your object and hope for the best.

According to the Object.toString() documentation, the default implementation of toString() does this:

The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of: getClass().getName() + '@' + Integer.toHexString(hashCode())

You have a few options. The easiest is to just override toString() in your SavedLocation and have it output what you want. This will work well if you really just want a single TextView to represent each entry.

If you want a more complicated layout, you will want to create your own ArrayAdapter subclass that overrides getView() to generate the appropriate View for each row in the ListView.

android - how to display objects in a list view - Stack Overflow

android sqlite listview listadapter
Rectangle 27 0

Creating custom class can give you additional benefits. You can use DisplayAttribute to set column headers and order. Then you can create view (or template to use with DisplayFor) that takes list of objects of any type and uses reflection to read annotations and display view nicely.

class Report {
    [Display(Name="Account",Order=1)]
    public string Account {get; set;}

    [Display(Name="Next payment",Order=2)]
    public Date NextPayment {get; set;}
}

It looks also clean. You will be able to use this annotations not only for grid, but also for excel exports or other data operations.

c# 4.0 - Binding pivot query to view in ASP.Net MVC - Stack Overflow

asp.net-mvc c#-4.0 viewmodel
Rectangle 27 0

The 'view' is actually the top-most display object container (it's just given as a property to my Main class). And neither does it work if I use view.stage.loaderInfo.uncaughtErrorEvents.addEventListener...

Hmm any other ideas why the (new) above code wouldn't work?

actionscript 3 - Global Error Handler for Flash Player 10.1 not workin...

actionscript-3 flash error-handling global
Rectangle 27 0

public class LoadImagesFromSDCardActivity extends Activity implements
OnItemClickListener {

/**
 * Grid view holding the images.
 **/

private GridView sdcardImages;
/**
 * Image adapter for the grid view.
 **/
private ImageAdapter imageAdapter;
/**
 * Display used for getting the width of the screen. 
 **/
private Display display;
ImageView imgView;

/**
 * Creates the content view, sets up the grid, the adapter, and the click listener.
 * 
 * @see android.app.Activity#onCreate(android.os.Bundle)
 **/
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);        
    // Request progress bar
    requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
    setContentView(R.layout.main);

    display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
    imgView=(ImageView)findViewById(R.id.imgView);
    setupViews();
    setProgressBarIndeterminateVisibility(true); 
    loadImages();
}

/**
 * Free up bitmap related resources.
 **/
protected void onDestroy() {
    super.onDestroy();
    final GridView grid = sdcardImages;
    final int count = grid.getChildCount();
    ImageView v = null;
    for (int i = 0; i < count; i++) {
        v = (ImageView) grid.getChildAt(i);
        ((BitmapDrawable) v.getDrawable()).setCallback(null);
    }
}
/**
 * Setup the grid view.
 **/
private void setupViews() {
    sdcardImages = (GridView) findViewById(R.id.sdcard);
    sdcardImages.setNumColumns(display.getWidth()/95);
    sdcardImages.setClipToPadding(false);
    sdcardImages.setOnItemClickListener(LoadImagesFromSDCardActivity.this);
    imageAdapter = new ImageAdapter(getApplicationContext()); 
    sdcardImages.setAdapter(imageAdapter);
}
/**
 * Load images.
 */
private void loadImages() {
    final Object data = getLastNonConfigurationInstance();
    if (data == null) {
        new LoadImagesFromSDCard().execute();
    } else {
        final LoadedImage[] photos = (LoadedImage[]) data;
        if (photos.length == 0) {
            new LoadImagesFromSDCard().execute();
        }
        for (LoadedImage photo : photos) {
            addImage(photo);
        }
    }
}
/**
 * Add image(s) to the grid view adapter.
 * 
 * @param value Array of LoadedImages references
 */
private void addImage(LoadedImage... value) {
    for (LoadedImage image : value) {
        imageAdapter.addPhoto(image);
        imageAdapter.notifyDataSetChanged();
    }
}

/**
 * Save bitmap images into a list and return that list. 
 * 
 * @see android.app.Activity#onRetainNonConfigurationInstance()
 */
@Override
public Object onRetainNonConfigurationInstance() {
    final GridView grid = sdcardImages;
    final int count = grid.getChildCount();
    final LoadedImage[] list = new LoadedImage[count];

    for (int i = 0; i < count; i++) {
        final ImageView v = (ImageView) grid.getChildAt(i);
        list[i] = new LoadedImage(((BitmapDrawable) v.getDrawable()).getBitmap());
    }

    return list;
}
/**
 * Async task for loading the images from the SD card. 
 * 
 * @author Mihai Fonoage
 *
 */
class LoadImagesFromSDCard extends AsyncTask<Object, LoadedImage, Object> {

    /**
     * Load images from SD Card in the background, and display each image on the screen. 
     *  
     * @see android.os.AsyncTask#doInBackground(Params[])
     */
    @Override
    protected Object doInBackground(Object... params) {
        //setProgressBarIndeterminateVisibility(true); 
        Bitmap bitmap = null;
        Bitmap newBitmap = null;
        Uri uri = null;            

        // Set up an array of the Thumbnail Image ID column we want
        String[] projection = {MediaStore.Images.Thumbnails._ID};
        // Create the cursor pointing to the SDCard
        Cursor cursor = managedQuery( MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
                projection, // Which columns to return
                null,       // Return all rows
                null,       
                null); 
        int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID);
        int size = cursor.getCount();
        // If size is 0, there are no images on the SD Card.
        if (size == 0) {
            //No Images available, post some message to the user
        }
        int imageID = 0;
        for (int i = 0; i < size; i++) {
            cursor.moveToPosition(i);
            imageID = cursor.getInt(columnIndex);
            uri = Uri.withAppendedPath(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, "" + imageID);
            try {
                bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
                if (bitmap != null) {
                    newBitmap = Bitmap.createScaledBitmap(bitmap, 70, 70, true);
                    bitmap.recycle();
                    if (newBitmap != null) {
                        publishProgress(new LoadedImage(newBitmap));
                    }
                }
            } catch (IOException e) {
                //Error fetching image, try to recover
            }
        }
        cursor.close();
        return null;
    }
    /**
     * Add a new LoadedImage in the images grid.
     *
     * @param value The image.
     */
    @Override
    public void onProgressUpdate(LoadedImage... value) {
        addImage(value);
    }
    /**
     * Set the visibility of the progress bar to false.
     * 
     * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
     */
    @Override
    protected void onPostExecute(Object result) {
        setProgressBarIndeterminateVisibility(false);
    }
}

/**
 * Adapter for our image files. 
 * 
 * @author Mihai Fonoage
 *
 */
class ImageAdapter extends BaseAdapter {

    private Context mContext; 
    private ArrayList<LoadedImage> photos = new ArrayList<LoadedImage>();

    public ImageAdapter(Context context) { 
        mContext = context; 
    } 

    public void addPhoto(LoadedImage photo) { 
        photos.add(photo); 
    } 

    public int getCount() { 
        return photos.size(); 
    } 

    public Object getItem(int position) { 
        return photos.get(position); 
    } 

    public long getItemId(int position) { 
        return position; 
    } 

    public View getView(int position, View convertView, ViewGroup parent) { 
        final ImageView imageView; 
        if (convertView == null) { 
            imageView = new ImageView(mContext); 
        } else { 
            imageView = (ImageView) convertView; 
        } 
        imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
        imageView.setPadding(8, 8, 8, 8);
        imageView.setImageBitmap(photos.get(position).getBitmap());
        return imageView; 
    } 
}

/**
 * A LoadedImage contains the Bitmap loaded for the image.
 */
private static class LoadedImage {
    Bitmap mBitmap;

    LoadedImage(Bitmap bitmap) {
        mBitmap = bitmap;
    }

    public Bitmap getBitmap() {
        return mBitmap;
    }
}
/**
 * When an image is clicked, load that image as a puzzle. 
 */
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {        
    int columnIndex = 0;
    String[] projection = {MediaStore.Images.Media.DATA};
    Cursor cursor = managedQuery( MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
            projection,
            null, 
            null, 
            null);
    if (cursor != null) {
        columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToPosition(position);
        String imagePath = cursor.getString(columnIndex); 

        FileInputStream is = null;
        BufferedInputStream bis = null;
        try {
            is = new FileInputStream(new File(imagePath));
            bis = new BufferedInputStream(is);
            Bitmap bitmap = BitmapFactory.decodeStream(bis);
            Bitmap useThisBitmap = Bitmap.createScaledBitmap(bitmap, 200, 200, true);
            Log.i("called","called");
            imgView.setImageBitmap(useThisBitmap);
            bitmap.recycle();
            //Display bitmap (useThisBitmap)
        } 
        catch (Exception e) {
            //Try to recover
        }
        finally {
            try {
                if (bis != null) {
                    bis.close();
                }
                if (is != null) {
                    is.close();
                }
                cursor.close();
                projection = null;
            } catch (Exception e) {
            }
        }
    }
  }

}
<GridView  
    android:id="@+id/sdcard"
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content"
    android:verticalSpacing="10dp"
    android:horizontalSpacing="10dp" 
    android:stretchMode="columnWidth"
    android:gravity="center" />
    <ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/imgView"
    ></ImageView>
</LinearLayout>

I'm confused, is this a solution or another question?

imageCursor.moveToFirst()
cursor.getCount()
if (!cursor.moveToFirst()) {             //No Images available, post some message to the user         }

android - managedQuery(Media.EXTERNAL_CONTENT_URI, projection,null,nul...

android mediastore
Rectangle 27 0

have a great tutural for you and how to insert objects in a custom listview layout using an adapter. Its not as much code as it looks like. I've used this code and it was a breeze. In the list view adapter class you specify which textview to show the part on the object you want.

java - Use CustomAdapter to change how ListView is displayed - Stack O...

java android android-listview custom-adapter
Rectangle 27 0

public class Display extends Activity implements OnItemClickListener{

    List<String> name1 = new ArrayList<String>();
    List<String> phno1 = new ArrayList<String>();
    MyAdapter ma ;
    Button select;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.display);

        getAllContacts(this.getContentResolver());
        ListView lv= (ListView) findViewById(R.id.lv);
            ma = new MyAdapter();
            lv.setAdapter(ma);
            lv.setOnItemClickListener(this); 
            lv.setItemsCanFocus(false);
            lv.setTextFilterEnabled(true);
            // adding
           select = (Button) findViewById(R.id.button1);
        select.setOnClickListener(new OnClickListener()
        {

            @Override
            public void onClick(View v) {
                    StringBuilder checkedcontacts= new StringBuilder();

                for(int i = 0; i < name1.size(); i++)

                    {
                    if(ma.mCheckStates.get(i)==true)
                    {
                         checkedcontacts.append(name1.get(i).toString());
                         checkedcontacts.append("\n");

                    }
                    else
                    {

                    }


                }

                Toast.makeText(Display.this, checkedcontacts,1000).show();
            }       
        });


    }
    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        // TODO Auto-generated method stub
         ma.toggle(arg2);
    }

    public  void getAllContacts(ContentResolver cr) {

        Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
        while (phones.moveToNext())
        {
          String name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
          String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
          name1.add(name);
          phno1.add(phoneNumber);
        }

        phones.close();
     }
    class MyAdapter extends BaseAdapter implements CompoundButton.OnCheckedChangeListener
    {  private SparseBooleanArray mCheckStates;
       LayoutInflater mInflater;
        TextView tv1,tv;
        CheckBox cb;
        MyAdapter()
        {
            mCheckStates = new SparseBooleanArray(name1.size());
            mInflater = (LayoutInflater)Display.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return name1.size();
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub

            return 0;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub
            View vi=convertView;
            if(convertView==null)
             vi = mInflater.inflate(R.layout.row, null); 
             tv= (TextView) vi.findViewById(R.id.textView1);
             tv1= (TextView) vi.findViewById(R.id.textView2);
             cb = (CheckBox) vi.findViewById(R.id.checkBox1);
             tv.setText("Name :"+ name1.get(position));
             tv1.setText("Phone No :"+ phno1.get(position));
             cb.setTag(position);
             cb.setChecked(mCheckStates.get(position, false));
             cb.setOnCheckedChangeListener(this);

            return vi;
        }
         public boolean isChecked(int position) {
                return mCheckStates.get(position, false);
            }

            public void setChecked(int position, boolean isChecked) {
                mCheckStates.put(position, isChecked);
            }

            public void toggle(int position) {
                setChecked(position, !isChecked(position));
            }
        @Override
        public void onCheckedChanged(CompoundButton buttonView,
                boolean isChecked) {
            // TODO Auto-generated method stub

             mCheckStates.put((Integer) buttonView.getTag(), isChecked);         
        }   
    }   
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

   <ListView
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_above="@+id/button1"

       android:id="@+id/lv"/>

     <Button
         android:id="@+id/button1"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_alignParentBottom="true"
         android:layout_centerHorizontal="true"
         android:text="Select" />

</RelativeLayout>
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="15dp"
        android:layout_marginTop="34dp"
        android:text="TextView" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/checkBox1"
        android:layout_alignLeft="@+id/textView1"
        android:text="TextView" />

    <CheckBox
        android:id="@+id/checkBox1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/textView1"
        android:layout_marginRight="22dp"
        android:layout_marginTop="23dp" />

</RelativeLayout>

The above uses a Custom Adapter. A custom layout row.xml with 2 textviews and one checkbox is inflated for each row. getAllContacts() will get all contacts from the contacts list and you store them in a list.

Custom Adapter displays the items in a custom layout inflated for each row.

When you check the check box and click display displays a toast with selected contacts name.

Use a view holder for smooth scrolling and performance. I have not used a view holder.

@user2691782 you are welcome and glad to help

Great job! Could you extend it to save checked items? (when activity starts, previously selected items should remain checked)

done :) - now I am trying to add an AlphabetIndexer to the list, but it is not working. Could you check it if I send the code? (where should I post my code? A new question?) Thanks in advance.

android - how to create custom contact list with checkbox - Stack Over...

android android-contacts
Rectangle 27 0

One way to do is to write a converter which will take list of your entities and convert it to the custome entity and return that object. another way is to use inheritance(hibernate inheritance) and then fire the same query but I think in your case its not required so I would go with the first approach. I am guessing here is that you need to display this custom object on view. If this is the reason you are doing it, then you should use DTO and write a converter which will convert your actual entities in to custom ones.

Then this might be the answer you are looking for :) :) :) check out the Transfer Object Pattern.

java - Returning a custom entity after JPA query - Stack Overflow

java spring hibernate jpa
Rectangle 27 0

ASP.NET Core Identity library uses claims-based approach to Authorization. It means that a logged in user (the one you can access via User object in your views) has some list of claims (name-value pairs) associated with it. By default, that list contains two claims: for ID and username. However, it's easy to add to that list any other claim you need (first/last name, the name of the company, current user's balance, etc.). You will just need to create your own implementation of IUserClaimsPrincipalFactory interface and register it in DI to override the default one.

Here is the article with a step-by-step description how to do it.

You can skip the first part ("zero" part to be more exact) "Preparations" if you already have the additional properties (like FirstName/LastName) in your ApplicationUser class.

How do you display a users full name in the login partial view in ASP....

asp.net-core
Rectangle 27 0

package studRecords.one;

 import java.util.List;
 import java.util.Vector;

 import android.app.Activity;
 import android.app.ListActivity;
 import android.content.Context;
 import android.content.Intent;
 import android.net.ParseException;
 import android.os.Bundle;
 import android.view.LayoutInflater;
 import android.view.View;
 import android.view.ViewGroup;
 import android.widget.ArrayAdapter;
 import android.widget.ImageView;
 import android.widget.ListView;
 import android.widget.TextView;



public class studRecords extends ListActivity 
{
static String listName = "";
static String listUsn = "";
static Integer images;
private LayoutInflater layoutx;
private Vector<RowData> listValue;
RowData rd;

static final String[] names = new String[]
{
      "Name (Stud1)", "Name (Stud2)",   
      "Name (Stud3)","Name (Stud4)" 
};

static final String[] usn = new String[]
{
      "1PI08CS016","1PI08CS007","1PI08CS017","1PI08CS047"
};

private Integer[] imgid = 
{
  R.drawable.stud1,R.drawable.stud2,R.drawable.stud3,
  R.drawable.stud4
};

public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.mainlist);

    layoutx = (LayoutInflater) getSystemService(
    Activity.LAYOUT_INFLATER_SERVICE);
    listValue = new Vector<RowData>();
    for(int i=0;i<names.length;i++)
    {
        try
        {
            rd = new RowData(names[i],usn[i],i);
        } 
        catch (ParseException e) 
        {
            e.printStackTrace();
        }
        listValue.add(rd);
    }


   CustomAdapter adapter = new CustomAdapter(this, R.layout.list,
                                     R.id.detail, listValue);
   setListAdapter(adapter);
   getListView().setTextFilterEnabled(true);
}
   public void onListItemClick(ListView parent, View v, int position,long id)
   {            


       listName = names[position];
       listUsn = usn[position];
       images = imgid[position];




       Intent myIntent = new Intent();
       Intent setClassName = myIntent.setClassName("studRecords.one","studRecords.one.nextList");
       startActivity(myIntent);

   }
   private class RowData
   {

       protected String mNames;
       protected String mUsn;
       protected int mId;
       RowData(String title,String detail,int id){
       mId=id;
       mNames = title;
       mUsn = detail;
    }
       @Override
    public String toString()
       {
               return mNames+" "+mUsn+" "+mId;
       }
  }

              private class CustomAdapter extends ArrayAdapter<RowData> 
          {
      public CustomAdapter(Context context, int resource,
      int textViewResourceId, List<RowData> objects)
      {               
            super(context, resource, textViewResourceId, objects);
      }
      @Override
      public View getView(int position, View convertView, ViewGroup parent)
      {   
           ViewHolder holder = null;
           TextView title = null;
           TextView detail = null;
           ImageView i11=null;
           RowData rowData= getItem(position);
           if(null == convertView)
           {
                convertView = layoutx.inflate(R.layout.list, null);
                holder = new ViewHolder(convertView);
                convertView.setTag(holder);
           }
         holder = (ViewHolder) convertView.getTag();
         i11=holder.getImage();
         i11.setImageResource(imgid[rowData.mId]);
         title = holder.gettitle();
         title.setText(rowData.mNames);
         detail = holder.getdetail();
         detail.setText(rowData.mUsn);                                                     

         return convertView;
      }

        private class ViewHolder 
        {
            private View mRow;
            private TextView title = null;
            private TextView detail = null;
            private ImageView i11=null; 
            public ViewHolder(View row)
            {
                    mRow = row;
            }
            public TextView gettitle()
            {
                 if(null == title)
                 {
                     title = (TextView) mRow.findViewById(R.id.title);
                 }
                 return title;
            }     
            public TextView getdetail()
            {
                if(null == detail)
                {
                    detail = (TextView) mRow.findViewById(R.id.detail);
                }
                return detail;
            }
            public ImageView getImage()
            {
                    if(null == i11)
                    {
                        i11 = (ImageView) mRow.findViewById(R.id.img);
                    }
                    return i11;
            }   
        }
   } 
 }
<?xml version="1.0" encoding="utf-8"?>
             <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                 android:orientation="horizontal"
                 android:layout_width="fill_parent"
                 android:layout_height="fill_parent"
             >
             <ListView
                 android:id="@android:id/list"
                 android:layout_width="fill_parent"
                 android:layout_height="wrap_content"
              />
             </LinearLayout>

How to display a list of images in a ListView in Android? - Stack Over...

android listview android-image