PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label listview. Show all posts
Showing posts with label listview. Show all posts

Friday, November 18, 2022

[FIXED] How to center widgets vertically when orientation is horizontal for an Android LinearLayout?

 November 18, 2022     android, android-linearlayout, listview, listviewitem, vertical-alignment     No comments   

Issue

I have several different item view types in an Android ListView, each with its own LinearLayout. I am trying to center all of their widgets vertically in addition to their being placed horizontally relative to each other. See the the very first item in the ListView in the attached pic. It looks fine except that the widgets are pushed up near the top of the ListView item.

The light blue and light green backgrounds for the TextView and ImageViews are intended to help view the effects of the xml on placement. Immediately below the image is my layout for that topmost item in the ListView. How can I make the TextView as well as the circular images (ImageView) to be centered vertically?

enter image description here

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:paddingBottom="5dp">

        <TextView
            android:id="@+id/ques_num"
            android:layout_width="30dp"
            android:layout_height="wrap_content"
            android:layout_marginLeft="2dp"
            android:layout_marginRight="2dp"
            android:layout_marginTop="2dp"
            android:layout_marginBottom="2dp"
            android:background="@color/LightBlue"
            android:text="0."
            android:textSize="22sp" />

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:layout_gravity="center_vertical"
            android:background="@color/LightGreen"
            android:adjustViewBounds="true"
            android:id="@+id/question_id_0" />
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:layout_gravity="center_vertical"
            android:background="@color/LightGreen"
            android:adjustViewBounds="true"
            android:id="@+id/question_id_1" />
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:layout_gravity="center_vertical"
            android:background="@color/LightGreen"
            android:adjustViewBounds="true"
            android:id="@+id/question_id_2" />
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:layout_gravity="center_vertical"
            android:background="@color/LightGreen"
            android:adjustViewBounds="true"
            android:id="@+id/question_id_3" />
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:layout_gravity="center_vertical"
            android:background="@color/LightGreen"
            android:adjustViewBounds="true"
            android:id="@+id/question_id_4" />


</LinearLayout>

UPDATE:

I tried simply adding to the LinearLayout:

android:gravity="center_horizontal"

and afterwards tried changing it to:

android:gravity="center_horizontal|center_vertical"

In both cases it resulted in moving the widgets into the horizontal center of the ListView item, but had no effect on the vertical positioning. See the results here in the image:

enter image description here


Solution

The entire problem was a combination of this line in the LinearLayout:

android:paddingBottom="5dp"

and the fact that, given the size of the content in the TextView and ImageView objects, the upper and lower boundaries of the ListView items were already pressing in as much as they could. There was no room for centering adjustments to take place even though it looked like there was, because of the paddingBottom attribute.



Answered By - Alyoshak
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, November 16, 2022

[FIXED] How to display list items as columns?

 November 16, 2022     css, list, listview, vertical-alignment     No comments   

Issue

I'm trying to build my first responsive layout. I want to display list items in a vertical line, depending on width.

<div style="height:800px;">
    <ul>
       <li>1</li>
       <li>2</li>
       <li>3</li>
       <li>4</li>
       <li>5</li>
       <li>6</li>
       <li>7</li>
    </ul>
</div>
1   5
2   6
3   7
4

If the browser gets resized, I want it to become

1  4  7
2  5
3  6

Can someone help me? I've been trying for hours and I can't get anything. I've tried using tables but I can't do it like that either.


Solution

This can be done using CSS3 columns quite easily. Here's an example, HTML:

#limheight {
    height: 300px; /*your fixed height*/
    -webkit-column-count: 3;
       -moz-column-count: 3;
            column-count: 3; /*3 in those rules is just placeholder -- can be anything*/
}

#limheight li {
    display: inline-block; /*necessary*/
}
<ul id = "limheight">
 <li><a href="">Glee is awesome 1</a></li>
 <li><a href="">Glee is awesome 2</a></li>
 <li><a href="">Glee is awesome 3</a></li>
 <li><a href="">Glee is awesome 4</a></li>    
 <li><a href="">Glee is awesome 5</a></li>
 <li><a href="">Glee is awesome 6</a></li>
 <li><a href="">Glee is awesome 7</a></li>
 <li><a href="">Glee is awesome 8</a></li>
 <li><a href="">Glee is awesome 9</a></li>
 <li><a href="">Glee is awesome 10</a></li>
 <li><a href="">Glee is awesome 11</a></li>
 <li><a href="">Glee is awesome 12</a></li>    
 <li><a href="">Glee is awesome 13</a></li>
 <li><a href="">Glee is awesome 14</a></li>
 <li><a href="">Glee is awesome 15</a></li>
 <li><a href="">Glee is awesome 16</a></li>
 <li><a href="">Glee is awesome 17</a></li>    
 <li><a href="">Glee is awesome 18</a></li>
 <li><a href="">Glee is awesome 19</a></li>
 <li><a href="">Glee is awesome 20</a></li>
</ul>



Answered By - Chris
Answer Checked By - Marie Seifert (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to align bottom container inside listview?

 November 16, 2022     flutter, listview, vertical-alignment     No comments   

Issue

I wanted to aling a button to the bottom center of the listview.

Scaffold(
  backgroundColor: Colors.white,
  appBar: buildAppBar(context, ''),
  body: ListView(
    physics: ClampingScrollPhysics(),
    children: [
      Column(
        children: [
          Text(
            'check up',
            style: TextStyle(
              fontSize: 35,
              fontWeight: FontWeight.bold,
              color: Colors.black,
            ),
          ),
          SizedBox(height: 12),
          Text(
            'SachsenwaldStr. 3. 12157 Berlin',
            style: TextStyle(
              fontSize: 20,
              color: Colors.black,
            ),
          ),
        ],
      ),
      Spacer(),
      buildNextButton(context),
    ],
  ),

I tried using Align, but it didn't work, and Spacer() didn't too:

  Align(
        alignment: Alignment.bottomCenter,
        child: buildNextButton(context),
      ),

is there any way to align buildNextButton to the bottom?


Solution

 return Scaffold(
    body: Stack(
  children: [
    Positioned(
      bottom: 0,
      width: MediaQuery.of(context).size.width,
      child: Center(
        child: MaterialButton(
          child: Text("My button"),
          onPressed: () {},
          color: Colors.red,
        ),
      ),
    ),
    ListView(
      children: [
        Text(
          'check up',
          style: TextStyle(
            fontSize: 35,
            fontWeight: FontWeight.bold,
            color: Colors.black,
          ),
        ),
        SizedBox(height: 12),
        Text(
          'SachsenwaldStr. 3. 12157 Berlin',
          style: TextStyle(
            fontSize: 20,
            color: Colors.black,
          ),
        ),
      ],
    )
  ],
));

OutPut



Answered By - Vaidarbhi
Answer Checked By - Timothy Miller (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, November 6, 2022

[FIXED] How to Fetch and Display Name and Image of Conversation's Contact?

 November 06, 2022     android, contacts, java, listview, sms     No comments   

Issue

I want to achieve something like in screenshot below, So far I am able to display a list of most recent message with message count, But when I'm trying to get the name of person through "address", I'm getting error " Column address not found". Please help me displaying "contact name with their image".

What I Want to Achieve

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                     Bundle savedInstanceState) {        
    View view = inflater.inflate(R.layout.MyChatFragment, container, false);
    
    // Inflate the layout for this fragment
    
    ListView lv = (ListView) view.findViewById(R.id.listView2);
     
    ArrayList<String> smsList;        
    smsList = new ArrayList<>();
    ArrayAdapter<String> lva = new ArrayAdapter<String>(getActivity(), 
    android.R.layout.simple_list_item_1, smsList);        
    lv.setAdapter(lva);

    Uri inboxUri = Uri.parse("content://sms/conversations/");
    ContentResolver contentResolver = getActivity().getContentResolver();
    Cursor cursor = contentResolver.query(inboxUri, null, null, null, null);

    if (cursor.moveToFirst()) {
            while (cursor.moveToNext()) {

        String number = cursor.getString(cursor.getColumnIndexOrThrow("address"));
        String message_count = cursor.getString(cursor.getColumnIndexOrThrow("msg_count"));
        String body = cursor.getString(cursor.getColumnIndexOrThrow("snippet"));
        smsList.add("Number: " + number + "\n" + "Message: " + body + "\n" + "Number Of Messages" + 
        message_count );

            }
        }
            return view;
     }

Solution

Conversations uri doesn't contain a column like "address". You can simply look all columns in specific uri via looping cursor.getColumnName(index) and print it to logcat. List of columns into specific uri you can also find in docs.
Basicly, Sms ContentProvider doesn't contain informations about contacts, so you need make a second query to ContactsContract uri, and find a specific contact via his phone number. Depending of data that you need, there are many uris. You can simply link a phone number from sms with a specific contact using ContactsContract.PhoneLookup.CONTENT_FILTER_URI. More detailed information about contacts are in sub-uris of ContactsContract ContentProvider. Description about all of them you will find in docs.
Below is simple example. Contact photos isn't stored like photos, but only like a uri to the photo, so you must fetch an image via uri. I didn't test that code too long, so I can't tell you, how it will work e.g. when you have a few contacts with same number.

if (cursor.moveToFirst()) {
        while (cursor.moveToNext()) {
            String number = cursor.getString(cursor.getColumnIndexOrThrow("address"));
            String thread_id = cursor.getString(cursor.getColumnIndexOrThrow("thread_id"));
            String body = cursor.getString(cursor.getColumnIndexOrThrow("body"));
            String name = "";
            String photoUri = "";

            if (number != null) {
                Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, number);
                String[] projection = new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME, ContactsContract.PhoneLookup.PHOTO_URI};
                Cursor contactCursor = getContentResolver().query(uri, projection, null, null, null);
                if (contactCursor != null && contactCursor.getCount() > 0) {
                    if (contactCursor.moveToFirst()) {
                        do {
                            name = contactCursor.getString(contactCursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
                            photoUri = contactCursor.getString(contactCursor.getColumnIndex(ContactsContract.PhoneLookup.PHOTO_URI));
                        } while (contactCursor.moveToNext());
                    }
                    contactCursor.close();
                }
            }
        }
    }
    cursor.close();

Note that you need gain Manifest.permission.READ_CONTACTS permission to read informations about contacts.



Answered By - grabarz121
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, September 29, 2022

[FIXED] How to make a SwiftUI list scrollable in tvOS

 September 29, 2022     listview, scroll, scrollview, swiftui, tvos     No comments   

Issue

I have a List with content and when I build to an Apple Tv I cannot scroll to the bottom of the List.

I tried the focusable on the List rows but I cannot seem to get the list to scroll. I also replaced the List with a ScrollView to no avail.

List(self.someData) { data in
     SomeListRow(data: data)
}
.shadow(radius: 5)
.focusable(true)

List(self.someData) { data in
     SomeListRow(data: data)
      .focusable(true)

}
.shadow(radius: 5)

Solution

SwiftUI on tvOS has a bug where if you set a shadow on something none of the components in it receive user input events such as focus. There's an easy workaround though, just set your shadow on the background layer.

.background(
    Color.white
        .shadow(radius: 5)
)


Answered By - Jeff
Answer Checked By - Cary Denson (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, September 14, 2022

[FIXED] How to delete an Item selected form ListView in Xamarin

 September 14, 2022     button, cross-platform, listview, xamarin.forms, xaml     No comments   

Issue

I'm building a Xamarin CrossPlatform App!

App contains 2 pages : HomePage, DetailGetData

HomePage: This page contains a ListView which is displaying list of data form webapi in cells and whenever I clicked each cell it goes to DetailGetDatapage which shows the detail of that data.

Problem: Now the problem is that I wanted to delete that selected item from DetailGetData page. A DeleteButton is placed and when i press that button that details and selected item should be deleted from the ListView as well. How it is possible ?

ScreenShot DetailGetData :https://i.stack.imgur.com/TXg4G.png

ScreenShot HomePage : https://i.stack.imgur.com/g1Hn1.png

Code:

DetailGetData Xaml:

 <?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="Last_MSPL.Views.DetailGetData">

    <StackLayout HorizontalOptions="Center" VerticalOptions="Center">

        <Label Text="{Binding employee_name}" x:Name="empname" FontSize="Medium" FontAttributes="Bold" />
        <Label Text="{Binding employee_age}" x:Name="age" FontSize="Medium" FontAttributes="Bold" />
        <Label Text="{Binding employee_salary}" x:Name="salary" FontSize="Medium" FontAttributes="Bold" />

        <Button x:Name="DeleteItem" Text="Delete" Clicked="DeleteItem_Clicked"  />
    </StackLayout>

</ContentPage>

HomePage Xaml:

    <?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="Last_MSPL.HomePage">


    <AbsoluteLayout HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
        <ListView x:Name="Demolist" ItemSelected="OnItemSelected" BackgroundColor="White">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell Height="100">
                        <ViewCell.ContextActions>
                            <MenuItem x:Name="OnMore" Clicked="OnMore_Clicked" CommandParameter="{Binding .}"
                                 Text="More" />
                            <MenuItem x:Name="OnDelete" Clicked="OnDelete_Clicked" CommandParameter="{Binding .}"
                                 Text="Delete" IsDestructive="True" />
                        </ViewCell.ContextActions>
                        <StackLayout HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" Padding="30,0">

                            <Label Text="{Binding employee_name}" FontAttributes="bold" FontSize="Small" TextColor="Black" x:Name="en"/>
                            <Label Text="{Binding employee_age}" FontSize="Micro" TextColor="Black" FontAttributes="Italic"/>
                            <Label Text="{Binding id}" IsVisible="False" />


                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>

        <ImageButton Source="fedit.png" 
            BackgroundColor="Transparent"
            AbsoluteLayout.LayoutFlags="PositionProportional"  
            AbsoluteLayout.LayoutBounds=".95,.95,55,55" 
            Clicked="ImageButton_Clicked">
        </ImageButton>

    </AbsoluteLayout>
</ContentPage>

HomePage.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using Newtonsoft.Json;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using Last_MSPL.MenuItems;
using Last_MSPL.Views;
using System.Collections;

namespace Last_MSPL
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class HomePage : ContentPage
    {
        public IEnumerable ObjOrderList { get; private set; }


        public HomePage()
        {
            ((NavigationPage)Application.Current.MainPage).BarBackgroundColor = Color.Black;
            InitializeComponent();
            Get();
        }



        public async void Get()
        {
            HttpClient client = new HttpClient();
            try
            {
                var respone = await client.GetStringAsync("http://dummy.restapiexample.com/api/v1/employees");
                List<GetData> ObjOrderList = JsonConvert.DeserializeObject<List<GetData>>(respone);
                var totalCount = ObjOrderList.Count;
                Demolist.ItemsSource = ObjOrderList.GetRange(0, 40);
            }
            catch (Exception ex)
            {
                throw;
            }
        }


        public async void OnItemSelected(object sender, SelectedItemChangedEventArgs e)
        {
            HttpClient client = new HttpClient();
            if (Demolist.SelectedItem != null)
            {

                var respone = await client.GetStringAsync("http://dummy.restapiexample.com/api/v1/employees");
                List<GetData> ObjOrderList = JsonConvert.DeserializeObject<List<GetData>>(respone);
                var abc = (GetData)e.SelectedItem;

                GetData data = new GetData();
                data = ObjOrderList.ToList().Where(x => x.id == abc.id).FirstOrDefault();

                var detailPage = new DetailGetData(data);
                detailPage.BindingContext = e.SelectedItem as GetData;
                Demolist.SelectedItem = null;
                await Navigation.PushModalAsync(detailPage);

            }
        }

DetailGetData.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using Newtonsoft.Json;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using Last_MSPL.MenuItems;

namespace Last_MSPL.Views
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class DetailGetData : ContentPage
    {
        public DetailGetData(GetData _data)
        {
            InitializeComponent();
            BindingList(_data);

        }



        public void BindingList(GetData data)
        {
            empname.Text = data.employee_name;
            age.Text = data.employee_age;
            salary.Text = data.employee_salary;
        }


        public async void DeleteItem_Clicked(object sender, EventArgs e)
        {





            await Navigation.PopModalAsync();
        }
    }
}

Solution

You can realize the function of deleting the item by adding a static datasouce class. And set the Demolist.ItemsSource = DataSource.collection; When click delete button in DetailGetData page, modify the Demolist.ItemsSource by deleting the item. So the code is like this:

DataSource.cs

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;

namespace App10
{
    public static class DataSource
    {
        public static ObservableCollection<GetData> collection;

        static DataSource()
        {
        }
        public static void persist(List<GetData> collection)
        {
            //do something here
        }

        public static void initializeData(List<GetData> listdata)
        {
            collection = new ObservableCollection<GetData>(listdata);
        }
    }
}

MainPage.xaml.cs

[XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class MainPage : ContentPage
    {
        List<GetData> dataList;
        public MainPage()
        {
            //((NavigationPage)Application.Current.MainPage).BarBackgroundColor = Color.Black;
            InitializeComponent();
            Get();
            //RefreshList();
        }
        public async void Get()
        {
            HttpClient client = new HttpClient();
            try
            {
                var respone = await client.GetStringAsync("http://dummy.restapiexample.com/api/v1/employees");
                List<GetData> ObjOrderList = JsonConvert.DeserializeObject<List<GetData>>(respone);
                var totalCount = ObjOrderList.Count;

                dataList = ObjOrderList.GetRange(0, 40);
                DataSource.initializeData(dataList);
                Demolist.ItemsSource = DataSource.collection;

            }
            catch (Exception ex)
            {
                throw;
            }
        }


        public async void OnItemSelected(object sender, SelectedItemChangedEventArgs e)
        {
            HttpClient client = new HttpClient();
            if (Demolist.SelectedItem != null)
            {

                var respone = await client.GetStringAsync("http://dummy.restapiexample.com/api/v1/employees");
                List<GetData> ObjOrderList = JsonConvert.DeserializeObject<List<GetData>>(respone);
                var abc = (GetData)e.SelectedItem;

                GetData data = new GetData();
                data = ObjOrderList.ToList().Where(x => x.id == abc.id).FirstOrDefault();

                var detailPage = new DetailGetData(data);
                detailPage.BindingContext = e.SelectedItem as GetData;
                Demolist.SelectedItem = null;
                await Navigation.PushModalAsync(detailPage);

            }
        }
}

DetailGetData.xaml.cs

   [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class DetailGetData : ContentPage
    {
        public GetData thisData;

        public DetailGetData(GetData _data)
        {
            InitializeComponent();
            BindingList(_data);
            thisData = _data;

        }


        public void BindingList(GetData data)
        {
            empname.Text = data.employee_name;
            age.Text = data.employee_age;
            salary.Text = data.employee_salary;
        }


        public async void DeleteItem_Clicked(object sender, EventArgs e)
        {

            GetData toberemoveditem = (from item in DataSource.collection
                                       where item.id == thisData.id
                             select item)
                            .FirstOrDefault<GetData>();
            DataSource.collection.Remove(toberemoveditem);


            await Navigation.PopModalAsync();
        }
    }


Answered By - AbbyWang - MSFT
Answer Checked By - David Marino (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, September 13, 2022

[FIXED] How to show all the content of list view row

 September 13, 2022     c#, cross-platform, listview, xamarin.forms, xaml     No comments   

Issue

I am working with Xamarin forms in order to make a crossplatform APP.

I am using a list view but I can't figure how to make a row show it's full content enter image description here

I tried to add HasUnevenRows="True" but didn't do the trick. I also tried to fix RowHeight="100"

Can someone please help me.


Solution

<ListView RowHeight="100" x:Name="ContextDemoList">
  <ListView.ItemTemplate>
    <DataTemplate>
      <ViewCell>
         <StackLayout Padding="5">
              <Label VerticalOptions="CenterAndExpand" Text="{Binding title}" />
         </StackLayout>
      </ViewCell>
         </DataTemplate>
       </ListView.ItemTemplate>
     </ListView>


Answered By - Ufuk Zimmerman
Answer Checked By - Pedro (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, September 12, 2022

[FIXED] How can I make my ListView in flutter scrollable?

 September 12, 2022     android, cross-platform, flutter, ios, listview     No comments   

Issue

I am new to flutter. I am trying to build a card app and I have a ListView for the suites of each card. I just realized that when I flip the screen to landscape mode, I get a overflow error. I figured it would be fine because I have a ListView. But nope. So I flipped it back to portrait and added some HUGE text to see if that would scroll and to my suprise it did not.

I did some research and added physics: const AlwaysScrollableScrollPhysics(), but still not working. All help is appreciated!

ListView(
  scrollDirection: Axis.vertical,
  physics: const AlwaysScrollableScrollPhysics(),
  shrinkWrap: true,
  children: [
    for (var item in suites)
      Text('test', style: TextStyle(fontSize: 100.0),),
    for (var item in suites)
      FlatButton(
        onPressed: () {
          var suiteId = item.suiteId;
          var suite = item.suite;
          var suiteImage = item.suiteImage;
          var suiteColor = item.suiteColor;

          print(suiteColor);

          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => SuiteScreen(
                suiteId: suiteId,
                suite: suite,
                suiteImage: suiteImage,
                suiteColor: suiteColor,
              ),
            ),
          );
        },
        child: ListTile(
          leading: Icon(Icons.deck),
          title: Text(
            item.suite,
            style: TextStyle(
              fontSize: 30.0,
            ),
          ),
        ),
      ),
  ],
);

Solution

just wrap your listview with the SingleChildScrollView widget and it'll work fine after that. You can copy paste the below code.

SingleChildScrollView(
  child: ListView(
  scrollDirection: Axis.vertical,
  physics: const AlwaysScrollableScrollPhysics(),
  shrinkWrap: true,
  children: [
    for (var item in suites)
      Text('test', style: TextStyle(fontSize: 100.0),),
    for (var item in suites)
      FlatButton(
        onPressed: () {
          var suiteId = item.suiteId;
          var suite = item.suite;
          var suiteImage = item.suiteImage;
          var suiteColor = item.suiteColor;

          print(suiteColor);

          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => SuiteScreen(
                suiteId: suiteId,
                suite: suite,
                suiteImage: suiteImage,
                suiteColor: suiteColor,
              ),
            ),
          );
        },
        child: ListTile(
          leading: Icon(Icons.deck),
          title: Text(
            item.suite,
            style: TextStyle(
              fontSize: 30.0,
            ),
          ),
        ),
      ),
    ],
  )
);


Answered By - Avinash
Answer Checked By - David Goodson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, July 29, 2022

[FIXED] When click searchbar it the value below come up

 July 29, 2022     android, image, java, listview, searchbar     No comments   

Issue

its image showing value and search bar

it is the image showing when clicking the search bar it will come up the values in list-view

I want to know why this happen and how to avoid the situation please help me thanks in advance

public class ListItem extends AppCompatActivity
{
    ListView listView1;
    ArrayList<String> listproduct;
    ArrayAdapter<String > adapternew;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.listitem);
        ActionBar actionBar=getSupportActionBar();
        actionBar.setTitle("Please Select the Item");
      SearchView search=(SearchView)findViewById(R.id.Search);
        ScrollView scroll=(ScrollView)findViewById(R.id.Scroll);
        ListView listView1=(ListView)findViewById(R.id.Listview);
        listproduct=new ArrayList<>();
        listproduct.add("Stove Top Stuffing");
        listproduct.add("Campell's Soup");
        listproduct.add("Tide");
        listproduct.add("Pampers");
        listproduct.add("Pepsi Products");
        listproduct.add("Tang");
        listproduct.add("Top Ramen");
        listproduct.add("Knorr");
        listproduct.add("Palmolive");
        listproduct.add("Scotch-Brite");
        listproduct.add("Bounty Paper Towls");
        listproduct.add("Oreo Cookies");
        listproduct.add("Quaker Oats");
        listproduct.add("Lays Potato Chips");
        adapternew = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,listproduct);
        listView1.setAdapter(adapternew);
        SearchManager manager=(SearchManager)getSystemService(Context.SEARCH_SERVICE);
        search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                search.clearFocus();
            if(listproduct.contains(query))
            {
            adapternew.getFilter().filter(query);
            }
                return false;
            }
            @Override
            public boolean onQueryTextChange(String newText) {
                adapternew.getFilter().filter(newText);
                return false;
            }
             });
          listView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int newposition, long id) {
                Toast.makeText(ListItem.this,listproduct.get(newposition)+"",Toast.LENGTH_SHORT).show();
                Intent i=new Intent(ListItem.this,AddOrder.class);
                i.putExtra("position",listproduct.get(newposition));
                //adapternew.notifyDataSetChanged();
                 startActivity(i);
            }
        });



    }
}

here is the code that is to show the list view item and i want to know whether the value in list view come up when clicking the search bar

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">


    <SearchView
        android:id="@+id/Search"

        android:layout_width="match_parent"
        android:layout_height="56dp"
        android:layout_alignParentTop="true"
        android:iconifiedByDefault="false"
        android:queryHint="Search Here"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.00" />


    <ScrollView
        android:id="@+id/Scroll"
        android:layout_width="100dp"
        android:layout_height="150dp"
        tools:layout_editor_absoluteX="-8dp"
        tools:layout_editor_absoluteY="396dp">


        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

        </LinearLayout>
    </ScrollView>

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar2"
        android:layout_width="match_parent"
        android:layout_height="5dp"
        android:background="?attr/colorPrimary"
        android:minHeight="?attr/actionBarSize"
        android:theme="?attr/actionBarTheme"
        tools:layout_editor_absoluteX="9dp"
        tools:layout_editor_absoluteY="2dp" />

    <ListView
        android:id="@+id/Listview"
        android:layout_width="match_parent"
        android:layout_height="300dp"
        android:layout_below="@id/Search"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.100"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.200">

    </ListView>
</androidx.constraintlayout.widget.ConstraintLayout>

and this is the xml file of the listview


Solution

I think this is the code you are wanting.

No need to use scrollview here because ListView itself is scrollable. LinearLayout with Vertical Orientation will solve your issue

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<androidx.appcompat.widget.Toolbar
    android:id="@+id/toolbar2"
    android:layout_width="match_parent"
    android:layout_height="5dp"
    android:background="?attr/colorPrimary"
    android:minHeight="?attr/actionBarSize"
    android:theme="?attr/actionBarTheme"
    tools:layout_editor_absoluteX="9dp"
    tools:layout_editor_absoluteY="2dp" />


<SearchView
    android:id="@+id/Search"
    android:layout_width="match_parent"
    android:layout_height="56dp"
    android:layout_alignParentTop="true"
    android:iconifiedByDefault="false"
    android:queryHint="Search Here"/>

<ListView
    android:id="@+id/Listview"
    android:layout_width="match_parent"
    android:layout_height="300dp"
    android:layout_marginTop="10dp">

</ListView>
</LinearLayout>


Answered By - Usama Altaf
Answer Checked By - David Marino (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, July 13, 2022

[FIXED] How to change the order of the messages from JSON?

 July 13, 2022     android, json, listview, messages, parsing     No comments   

Issue

I have such JSON response with messages from the server:

response: {
count: 74246,
items: [{
  id: 343194,
  body: 'Message 3',
  user_id: 123,
  from_id: 123,
  date: 1436513626,
  read_state: 1,
  out: 0
}, {
  id: 343190,
  body: 'Message 2',
  user_id: 123,
  from_id: 321,
  date: 1436513502,
  read_state: 1,
  out: 1
}, {
  id: 343187,
  body: 'Message 1',
  user_id: 123,
  from_id: 123,
  date: 1436513198,
  read_state: 1,
  out: 0
}]
}

I put it into the listview and I have such order:

  • Message 3
  • Message 2
  • Message 1

But I want to get the next order:

  • Message 1
  • Message 2
  • Message 3

So it means that the newest messages should be from the bottom to top. Probably I should build the listview from the bottom? But how? What should I do to achieve this? And sorry for my English :)


Solution

Set reverse order on ArrayList:

ArrayList<Your_Model> mList = new ArrayList<Your_Model>();

Set data in mList from JSON:

Whenever you want to get List on reverse order, put below code.

Collections.reverse(mList);

Hope it will help you.



Answered By - Hiren Patel
Answer Checked By - David Goodson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, July 11, 2022

[FIXED] Why the window of control coulnd't appear?

 July 11, 2022     listview, message, win32gui, winapi, windows     No comments   

Issue

I saw an article on the Microsoft website MSDN that introduced an advanced way of writing.

I apply it to the extension of the class, and usually I don't have a problem.

But recently I encountered a problem when I tried to write a class. I want to implement a listview class to provide us some convenience when we manipulate the listview control.

template <class DERIVED_TYPE>
class BaseWindow
{
public:
    LPCTSTR className = "myWindows";
    LPCTSTR Caption = "myWindows";
    DWORD Style = WS_OVERLAPPEDWINDOW | WS_VISIBLE;
    UINT classStyle = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
    DWORD ExStyle = 0;
    ...
    other_property
    ...
    static LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
    {
        DERIVED_TYPE *pThis = NULL;
        if (uMsg == WM_NCCREATE)
        {
            CREATESTRUCT* pCreate = (CREATESTRUCT*)lParam;
            pThis = (DERIVED_TYPE*)pCreate->lpCreateParams;
            SetWindowLongPtr(hwnd, GWLP_USERDATA, (LONG_PTR)pThis);

            if (pThis)pThis->m_hwnd = hwnd;

        }else{
            pThis = (DERIVED_TYPE*)GetWindowLongPtr(hwnd, GWLP_USERDATA);
            if(pThis)pThis->m_hwnd = hwnd;
        }

        if (pThis)
        {
            return pThis->HandleMessage(hwnd, uMsg, wParam, lParam);

        }else{
            return DefWindowProc(hwnd, uMsg, wParam, lParam);
        }
    }
    ATOM RegClass()
    {
        WNDCLASS wc = { 0 };
        wc.lpfnWndProc = BaseWindow::WindowProc;
        wc.hInstance = hInst;
        wc.lpszClassName = className;
        wc.style = classStyle;
        wc.hCursor = ::LoadCursor(NULL, IDC_ARROW);
        return RegisterClass(&wc);
    }
    BOOL CreateWinEx(   LPCTSTR className_,LPCTSTR Caption_,
                        DWORD Style_,DWORD ExStyle_,
                        int x_,int y_,int w_,int h_,
                        HWND hWndParent_,HMENU hMenu_,HINSTANCE hInst_)
    {
        m_hwnd = CreateWindowEx(
            ExStyle_, className_, Caption_, Style_,
            x_, y_, w_, h_, 
            hWndParent_, hMenu_, hInst_, this
            );
        return (m_hwnd ? TRUE : FALSE);
    }
    BOOL Create()
    {
        ATOM rst = RegClass();
        if(rst == 0) return FALSE;
        m_hwnd = CreateWindowEx(
            ExStyle, className, Caption, Style,
            x, y, w, h, 
            hWndParent, hMenu, hInst, this
            );
        return (m_hwnd ? TRUE : FALSE);
    }
}

Based on the above, I have derived two classes, one as the main form and the other as the listview class that I am going to design.

class FirstWindow : public BaseWindow<FirstWindow>
{
public:
    FirstWindow(){};
    ...
    some_property
    ...
    LRESULT HandleMessage(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
    LRESULT CALLBACK ButtonProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
public:

};

class listView : public BaseWindow<listView>
    {

    public:
        listView();
        
        int init(LPCTSTR className_,HWND hWndParent_,int x,int y,int w,int h)
        {
             this->className = className_;
             this->hWndParent = hWndParent_;

             this->Style = WS_CHILD| WS_VISIBLE | ~WS_CAPTION;
           
             this->x = x;
             this->y = y;
             this->w = w;
             this->h = h;

             this->Create();

             hWndMsgWindow = m_hwnd;

             CreateListView(hWndMsgWindow);



             ShowWindow(hWndMsgWindow,SW_SHOW);
             ShowWindow(hWndListView,SW_SHOW);

             UpdateWindow(hWndMsgWindow);
             UpdateWindow(hWndListView);

             idebug("listview::init >> hWndMsgWindow:%d,parent:%d, error:%d\n",hWndMsgWindow,GetParent(hWndMsgWindow), GetLastError());
             idebug("listview::init >> hWndListView:%d,parent:%d,error:%d\n",hWndListView,GetParent(hWndListView), GetLastError());
             return 1;

        }
        LRESULT HandleMessage(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);

        
    LRESULT listView::CreateListView(HWND hwndParent_)
    {

        InitCommonControls();

        bool rst = CreateWinEx(WC_LISTVIEW, NULL,
        WS_CHILD | WS_VISIBLE | LVS_REPORT |LVS_EDITLABELS | LVS_NOCOLUMNHEADER | LVS_OWNERDATA |LVS_OWNERDRAWFIXED | WS_BORDER,0,
            x,y,w,h,
            hwndParent_, NULL, GetModuleHandle(NULL));

        if(rst)
            hWndListView = m_hwnd;

        idebug("CreateListView >> rst:%d,hwndlistview:%d,parent:%d,hwndParent_:%d, error:%d\n",rst,hWndListView,GetParent(hWndListView),hwndParent_,    GetLastError());

        return rst;

    }
        LRESULT AddItem();
        LRESULT OnListViewNotify(HWND hwnd, LPARAM lParam);
        void OwnerDraw(LPDRAWITEMSTRUCT lpdis, HDC hdc, HWND hWnd, const TCHAR* szDraw);

        void on_drawItem(HWND hWnd, LPARAM lParwm);
        void on_notify(HWND hWnd, WPARAM wParwm, LPARAM lParam);
        void on_create(HWND hWnd);
        void on_measureItem(LPARAM lParam);

        bool add_item();
        bool add_item_sub();
        ...
        some_property
        ...

    };

fire FirstWindow first


FirstWindow * pFirstWnd;

listView  lv;


int main(int argc, char** argv)
{

    FirstWindow win;
    pFirstWnd = &win;
    win.className = "FirstWindow";
    win.Style |= WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
    win.x = 100;
    win.y = 100;
    win.w = 600;
    win.h = 300;
    bool rst = win.Create();
    if (!rst)
    {
        idebug("getlasterror:%d,line:201\n", GetLastError());
        bug.ShowErr();
    }
    else {
        lv.init("mylistview",pFirstWnd->m_hwnd,20,20,300,200);
        ShowWindow(lv.m_hwnd, SW_SHOW);
    }

    MSG msg = {};
    while (GetMessage(&msg, NULL, 0, 0))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
    return 0;
}

The goal of the listview_class is to be able to receive and process window messages independently. not like this:

LRESULT FirstWindow::HandleMessage(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{

    switch (uMsg)
    {
            case WM_CREATE:
            {
                //lv.init("mylistview2",pFirstWnd->m_hwnd,20,20,300,200);
                //ShowWindow(lv.m_hwnd, SW_SHOW);
                break;
            }
            case WM_NOTIFY:
            {
                lv.on_notify(hWnd,wParam,lParam);
                break;
            }
            ...
            }
            default:
                return DefWindowProc(m_hwnd, uMsg, wParam, lParam);

    }

    return TRUE;
}

Instead, I want to process messages independently within listview class,like this:


LRESULT listView::HandleMessage(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    int wmId, wmEvent;
    PAINTSTRUCT ps;
    static HDC hdc;
    HRESULT lResult;
    switch (uMsg) 
    {
    case WM_CREATE:
    {
        
        idebug("class_listview >> WM_CREATE >> hWnd :%d, className:%s, parent:%d\n",hWnd, className , GetParent(hWnd));
        
        //HWND h = CreateWindowEx(0, WC_LISTVIEW, NULL,
                    WS_CHILD | WS_VISIBLE | LVS_REPORT |LVS_EDITLABELS | LVS_NOCOLUMNHEADER | LVS_OWNERDATA |LVS_OWNERDRAWFIXED | WS_BORDER,
                    20,20,300,200,
                    hWnd,NULL, GetModuleHandle(NULL),NULL);

        //ShowWindow(h,SW_SHOW);
        //UpdateWindow(hWnd);

        //idebug("class_listview >> WM_CREATE >> hwnd:%d,parent:%d,error:%d\n",h,GetParent(h), GetLastError());
 
        //ShowWindow(h,SW_SHOW);
        //UpdateWindow(h);
        break;
    }
    case WM_NOTIFY:
    {
        on_notify(hWnd,wParam,lParam);
        break;
    }
    case WM_MEASUREITEM:     
    {     
        on_measureItem(lParam);
        break;
    }
    case WM_DRAWITEM:
    {
        on_drawItem(hWnd,lParam);
        break;
    }
    case WM_PAINT:
    {
        PAINTSTRUCT ps;
        HDC hdc = BeginPaint(hWnd, &ps);
        FillRect(hdc, &ps.rcPaint, (HBRUSH)(COLOR_WINDOW + 2));
        EndPaint(hWnd, &ps);
        idebug("class_listview >> WM_PAINT->hWnd:%d,id:%d,err:%d\n", hWnd, id, GetLastError());
        break;
    }

    default:
        return DefWindowProc(hWnd, uMsg, wParam, lParam);
    }
    return 0;
}

The problem now is that i can't see other control windows except that FirstWindow can display normally.

update: some message from debug:

class_listview >> WM_CREATE >> hWnd :1443146, className:mylistview, parent:262350,error:0
listView >> WM_SIZE >> hWnd:1443146,parent:262350
CreateListView >> rst:1,hwndlistview:853318,parent:1443146,hwndParent_:1443146, error:5
listview::init >> hWndMsgWindow:1443146,parent:262350, error:5
listview::init >> hWndListView:853318,parent:1443146,error:5

Solution

the key of the problem is the return value of WM_NOTIFY message.

i typed :

case WM_NOTIFY:
    {
        retnrn on_notify(hWnd,wParam,lParam);
    }

the problem was resolved.



Answered By - anti-gravity
Answer Checked By - Terry (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, July 8, 2022

[FIXED] how to make a list of posts titles in django

 July 08, 2022     django, django-queryset, listview, posts, python     No comments   

Issue

I am creating a blog web app with django where i want to make a list which contains only titles of the posts. i wanna make two lists namely

  1. Latest posts
  2. All posts

In Latest posts , i wanna list out titles of the posts created recently.Means post created at last should be in first place of the list. simple

In All Posts , i want to list out titles of all posts in ascending order. i am not sure how to do it.

Here is my code goes.....

views.py

from django.shortcuts import render , redirect
from django.views.generic import TemplateView , ListView , DetailView
from .models import home_blog_model
from .forms import create_post

class home_view(ListView):
    model = home_blog_model
    template_name = "home.html"
    context_object_name = "posts"


def detail_view(request , pk):
    obj = home_blog_model.objects.get(id=pk)
    context = {"obj":obj}

    return render(request , "detail.html" , context)

def create_post_view(request):
    if request.method == "POST":
        form = create_post(request.POST)
        if form.is_valid():
            form.save()

            return redirect("/home/")

    else:
        form = create_post()
    return render(request , "create_post.html" , {"form":form})

home.html

{% extends "base.html" %}
{% load static %}
{% block body %}
    <img src="{% static 'hori.jpg' %}" style="margin-top: 50px;margin-left: 250px;width: 60%">



    <div class="row" style="margin-top: 40px;margin-left: 320px;margin-right: 20px">
        {% for post in posts %}
            <div class="col-sm-6 mb-4">
                <div class="container" style="width: 300px;box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2);transition: 0.3s;width: 100%;padding: 0px;">



                    <div class="card" style="height: 200px;padding: 12px;" onclick="location.href='{% url 'detail' post.id %}'">
                        <h2>{{ post.title }}</h2>
                        <div class="card-body">{{ post.summary }}</div>
                    </div>
                </div>
            </div>
        {% endfor %}
    </div>

{% endblock %}

{% block head %}
<style>
    .card:hover { box-shadow: 0 8px 16px 0 rgba(0,0,0,0.2);}
</style>
{% endblock %}

models.py

from django.db import models

class home_blog_model(models.Model):
    title = models.CharField(max_length=100)
    summary = models.CharField(max_length=300)
    content = models.TextField()
    date = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.title

urls.py

from django.urls import path
from . import views
from django.contrib.auth.views import LoginView , LogoutView
urlpatterns = [

    path("" , views.home_view.as_view() , name="blog-home"),
    path("posts/<int:pk>/" , views.detail_view , name="detail"),
    path("admin/login/" , LoginView.as_view(template_name="admin-login.html") , name="admin-login"),
    path("admin/logout/" , LogoutView.as_view() , name="admin-logout"),
    path("admin/post/create/" , views.create_post_view , name="create_post"),
]

thanks in advance.


Solution

You can use dictsortreversed for latest posts. For example:

# top 5 posts
{% for post in posts|dictsortreversed:"id"|slice:"5" %}
     {{ post.title }}
{% endfor %}

In this way you can have posts in ascending order (like the implementation of your code) and reversed order in same template without adding anything in view. slice was added for slicing the list for 5 objects.



Answered By - ruddra
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, May 5, 2022

[FIXED] How to lazy load images in ListView in Android

 May 05, 2022     android, image, listview, universal-image-loader, url     No comments   

Issue

I am using a ListView to display some images and captions associated with those images. I am getting the images from the Internet. Is there a way to lazy load images so while the text displays, the UI is not blocked and images are displayed as they are downloaded?

The total number of images is not fixed.


Solution

Here's what I created to hold the images that my app is currently displaying. Please note that the "Log" object in use here is my custom wrapper around the final Log class inside Android.

package com.wilson.android.library;

/*
 Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you 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.
*/
import java.io.IOException;

public class DrawableManager {
    private final Map<String, Drawable> drawableMap;

    public DrawableManager() {
        drawableMap = new HashMap<String, Drawable>();
    }

    public Drawable fetchDrawable(String urlString) {
        if (drawableMap.containsKey(urlString)) {
            return drawableMap.get(urlString);
        }

        Log.d(this.getClass().getSimpleName(), "image url:" + urlString);
        try {
            InputStream is = fetch(urlString);
            Drawable drawable = Drawable.createFromStream(is, "src");


            if (drawable != null) {
                drawableMap.put(urlString, drawable);
                Log.d(this.getClass().getSimpleName(), "got a thumbnail drawable: " + drawable.getBounds() + ", "
                        + drawable.getIntrinsicHeight() + "," + drawable.getIntrinsicWidth() + ", "
                        + drawable.getMinimumHeight() + "," + drawable.getMinimumWidth());
            } else {
              Log.w(this.getClass().getSimpleName(), "could not get thumbnail");
            }

            return drawable;
        } catch (MalformedURLException e) {
            Log.e(this.getClass().getSimpleName(), "fetchDrawable failed", e);
            return null;
        } catch (IOException e) {
            Log.e(this.getClass().getSimpleName(), "fetchDrawable failed", e);
            return null;
        }
    }

    public void fetchDrawableOnThread(final String urlString, final ImageView imageView) {
        if (drawableMap.containsKey(urlString)) {
            imageView.setImageDrawable(drawableMap.get(urlString));
        }

        final Handler handler = new Handler(Looper.getMainLooper()) {
            @Override
            public void handleMessage(Message message) {
                imageView.setImageDrawable((Drawable) message.obj);
            }
        };

        Thread thread = new Thread() {
            @Override
            public void run() {
                //TODO : set imageView to a "pending" image
                Drawable drawable = fetchDrawable(urlString);
                Message message = handler.obtainMessage(1, drawable);
                handler.sendMessage(message);
            }
        };
        thread.start();
    }

    private InputStream fetch(String urlString) throws MalformedURLException, IOException {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet request = new HttpGet(urlString);
        HttpResponse response = httpClient.execute(request);
        return response.getEntity().getContent();
    }
}


Answered By - James A Wilson
Answer Checked By - Mary Flores (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing