Android Custom ListView with Images and Text in horizantally - java

first of all sorry for poor communication, i have using custom array adapter and list of images and names are displaying gridview control in my app.The images and names are come from sql server database now showing all images bind and display to gridview, i want to images displaying slide type i.e. first column display 3 images after click the image slide to the next 3 images display.. anybody help me please.
My Code is:
enquiryfrm.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Select Name"/>
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<ScrollView
android:id="#+id/questionListSV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:fillViewport="true">
<GridView
android:id="#+id/gridviewimg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:numColumns="3"
android:horizontalSpacing="10dp"
android:scrollbars="horizontal"
android:scrollbarAlwaysDrawHorizontalTrack="true"
android:scrollbarAlwaysDrawVerticalTrack="true"
android:stretchMode="none"
android:columnWidth="100dp"
android:paddingBottom="60dp"/>
</ScrollView>
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content">
</Spinner>
</LinearLayout>
2.enquiryaimagetemplate.xml
<?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="wrap_content"
android:padding="1dp"
android:orientation="vertical">
<ImageView
android:id="#+id/imageview2"
android:layout_width="120dp"
android:layout_height="120dp"
android:scaleType="fitXY"
android:layout_marginRight="10dp"
android:src="#drawable/not_available" />
<TextView
android:id="#+id/txtitem_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:textSize="15sp" >
</TextView>
<TextView
android:id="#+id/txtregidno"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:textSize="15sp" >
</TextView>
</LinearLayout>
3.enquiryitems.java
public class enquiryItems {
String itemname;
int Reg_id;
Bitmap itemimg;
public enquiryItems(String itemname,Bitmap itemimg,int Reg_id){
this.itemname=itemname;
this.itemimg=itemimg;
this.Reg_id=Reg_id;
}
public String getItemname(){
return itemname;
}
public Bitmap getItemimg(){return itemimg;}
public int getReg_id(){return Reg_id;}
}
4.enquiryarrayadapter
public class EnquiryArrayadapter extends ArrayAdapter<enquiryItems> {
ArrayList<enquiryItems> itemlist = new ArrayList<>();
private Context context;
ConnectionClass connectionClass;
public EnquiryArrayadapter(ArrayList<enquiryItems> objects,Context context) {
super(context,R.layout.enquiryaimagetemplate,objects);
this.itemlist=objects;
this.context=context;
//visitorlist=objects;
}
#Override
public int getCount() {
return super.getCount();
}
#Override
public View getView(final int position, View convertview, ViewGroup parent){
if (convertview == null) { // This a new view we inflate the new layout
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertview = inflater.inflate(R.layout.enquiryaimagetemplate, parent, false);
}
connectionClass = new ConnectionClass();
final TextView txtitem_name=(TextView)convertview.findViewById(R.id.txtitem_name);
final TextView txtregidno = (TextView) convertview.findViewById(R.id.txtregidno);
final ImageView imageview2 = (ImageView) convertview.findViewById(R.id.imageview2);
final enquiryItems objitem=itemlist.get(position);
imageview2.setImageBitmap(objitem.getItemimg());
txtitem_name.setText(objitem.getItemname());
txtregidno.setText(String.valueOf(objitem.getReg_id()));
// txtregidno.setVisibility(View.GONE);
imageview2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//ImageView imageview2 = (ImageView) v;
String idval = txtregidno.getText().toString();
/* int id=Integer.parseInt(String.valueOf(idval));
zoomImageFromThumb(imageview2, id);*/
}
});
return convertview;
}
5.enquiry.java
public class Enquiry extends Fragment {
ProgressDialog pbd;
GridView gridviewimg;
ConnectionClass connectionClass;
int RegIdNo;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.enquiryfrm, container, false);
connectionClass=new ConnectionClass();
gridviewimg=(GridView)rootView.findViewById(R.id.gridviewimg);
Fetch fe=new Fetch();
fe.execute("");
return rootView;
}
public class Fetch extends AsyncTask<String, String, String> {
String z = "";
String ownid;
ArrayList<enquiryItems> visitorList=new ArrayList<>();
#Override
protected void onPreExecute() {
pbd=new ProgressDialog(getActivity());
pbd.setMessage("Please Wait...");
pbd.setCancelable(false);
pbd.show();
}
#Override
protected void onPostExecute(String r) {
// pbbar.setVisibility(View.GONE);
if (pbd.isShowing())
pbd.dismiss();
if(r!="empty"){
Toast.makeText(getActivity(), r, Toast.LENGTH_SHORT).show();
}
EnquiryArrayadapter myAdapter=new EnquiryArrayadapter(visitorList,getActivity());
myAdapter.notifyDataSetChanged();
gridviewimg.setAdapter(myAdapter);
// Toast.makeText(getActivity(), r, Toast.LENGTH_SHORT).show();
}
#Override
protected String doInBackground(String... params) {
try {
Connection con = connectionClass.CONN();
if (con == null) {
z = "Error in connection with SQL server";
} else {//
String query="";
query = "select * from FB_Feedback";
PreparedStatement ps2 = con.prepareStatement(query);
ResultSet rs2 = ps2.executeQuery();
ArrayList data1 = new ArrayList();
while (rs2.next()) {
//Reg_Id=rs.getInt("Id");
RegIdNo = rs2.getInt("id");
String r = rs2.getString("Photo");
//Convertong Images string to bitmap
byte[] decodeString = Base64.decode(r, Base64.DEFAULT);
Bitmap decodebitmap = BitmapFactory.decodeByteArray(decodeString, 0, decodeString.length);
visitorList.add(new enquiryItems("Item Name : "+rs2.getString("Feedback"),decodebitmap,RegIdNo));
// }
// z="Success";
}
if (RegIdNo==0){
z="No Visitor data";
}else {
z="empty";
}
}
} catch (Exception ex) {
z = ex.toString();
}
return z;
}
}
like the below format need enter image description here

Your question is not understandable. As far as I understood, try using horizontal listview.

Related

Android - ArrayAdapter toggle ImageButton src between Play and Pause in ListView

I am still learning android. Here I need help to toggle between Play and Pause source in ImageButton in the ListView.
There should be only one song in Play state at a time. So if clicked other should stop.
SongAdapter.java
public class SongAdapter extends ArrayAdapter<Song> {
public SongAdapter(#NonNull Context context, int resource, #NonNull List<Song> objects) {
super(context, resource, objects);
}
#NonNull
#Override
public View getView(final int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View playlistItemView = convertView;
if (playlistItemView == null) {
playlistItemView = LayoutInflater.from(getContext()).inflate(R.layout.playlist_item, parent, false);
}
Song currentSong = getItem(position);
// get list item elements
ImageView albumCoverThumbnail = playlistItemView.findViewById(R.id.playlist_album_thumbnail);
TextView songTitle = playlistItemView.findViewById(R.id.playlist_song_title);
TextView songAlbumTitle = playlistItemView.findViewById(R.id.playlist_song_album_title);
TextView songArtist = playlistItemView.findViewById(R.id.playlist_song_artist);
final ImageButton songPlayButton = playlistItemView.findViewById(R.id.playlist_play_button);
// set data to the list item
assert currentSong != null;
albumCoverThumbnail.setImageResource(currentSong.getSongAlbumCoverId());
songTitle.setText(currentSong.getSongTitle());
songAlbumTitle.setText(currentSong.getSongAlbumTitle());
songArtist.setText(currentSong.getSongSingers());
// set song button action
songPlayButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
songPlayButton.setImageResource(R.drawable.ic_pause_black_24dp);
Toast.makeText(getContext(), "Button clicked for item " + position, Toast.LENGTH_LONG).show();
}
});
return playlistItemView;
}
}
Song.java
public class Song {
private String songAlbumTitle;
private String songTitle;
private String songSingers;
private int songAlbumCoverId;
public Song(String albumTitle, String title, String singers, int albumCoverId) {
songAlbumTitle = albumTitle;
songTitle = title;
songSingers = singers;
songAlbumCoverId = albumCoverId;
}
public String getSongAlbumTitle() {
return songAlbumTitle;
}
public String getSongTitle() {
return songTitle;
}
public String getSongSingers() {
return songSingers;
}
public int getSongAlbumCoverId() {
return songAlbumCoverId;
}
}
Activity.java
public class DreamVoyage extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dream_voyage);
// get view ids
ImageView albumCoverImage = findViewById(R.id.album_cover);
// get intent extras
Bundle bundle = getIntent().getExtras();
// check if bundle in not null and containing value
if (bundle != null) {
String albumTitle = bundle.getString("album_one_title");
String albumBand = bundle.getString("album_one_band");
int albumCover = bundle.getInt("album_one_cover");
albumCoverImage.setImageResource(albumCover);
TextView albumTitleText = findViewById(R.id.album_title);
TextView albumBandText = findViewById(R.id.album_band);
albumTitleText.setText(albumTitle);
albumBandText.setText(albumBand);
ArrayList<Song> songs = new ArrayList<Song>();
songs.add(new Song(albumTitle, "I do it for you", "Bryn Adams", albumCover));
songs.add(new Song(albumTitle, "Here I am", "Bryn Adams", albumCover));
SongAdapter songAdapter = new SongAdapter(this, 0, songs);
ListView listView = findViewById(R.id.playlist_view);
listView.setAdapter(songAdapter);
}
}
}
playlist_item.xml
<?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="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:paddingTop="8dp"
android:paddingBottom="8dp"
android:background="#drawable/border_bottom"
android:orientation="horizontal">
<ImageView
android:id="#+id/playlist_album_thumbnail"
android:layout_width="32dp"
android:layout_height="32dp"
android:src="#drawable/album_three"
android:scaleType="centerCrop"
android:contentDescription="#string/album_thumbnail_desc"/>
<android.support.constraint.ConstraintLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1">
<TextView
android:id="#+id/playlist_song_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Mon voyage de rĂªve"
android:layout_marginLeft="8dp"
android:textColor="#000000"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"/>
<TextView
android:id="#+id/playlist_song_album_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Dream Voyage"
android:textSize="10sp"
android:textColor="#666666"
app:layout_constraintTop_toBottomOf="#+id/playlist_song_title"
app:layout_constraintStart_toStartOf="#id/playlist_song_title"/>
<TextView
android:id="#+id/playlist_song_credit_separator"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" - "
android:textSize="10sp"
android:textColor="#666666"
app:layout_constraintTop_toBottomOf="#+id/playlist_song_title"
app:layout_constraintStart_toEndOf="#id/playlist_song_album_title"/>
<TextView
android:id="#+id/playlist_song_artist"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" - John Doen, Jane Doe"
android:textSize="10sp"
android:textColor="#666666"
app:layout_constraintTop_toBottomOf="#+id/playlist_song_title"
app:layout_constraintStart_toEndOf="#id/playlist_song_credit_separator"/>
</android.support.constraint.ConstraintLayout>
<ImageButton
android:id="#+id/playlist_play_button"
android:layout_width="24dp"
android:layout_height="24dp"
android:padding="0dp"
android:layout_gravity="center_vertical"
android:background="#00FFFFFF"
android:src="#drawable/ic_play_arrow_black_24dp"
android:scaleType="centerCrop"/>
</LinearLayout>
Use a variable to store current playing items index
SongAdapter {
int playingIndex = -1 //-1 means no song is playing
.
.
.
}
Set play/pause drawable based on playingIndex and set the playingIndex in the songPlayButton.setOnClickListener
public View getView(final int position, ...) {
if(playingIndex == position)
songPlayButton.setImageResource(R.drawable.ic_play_black_24dp);
else
songPlayButton.setImageResource(R.drawable.ic_pause_black_24dp);
songPlayButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(position == playIndex)
playIndex = -1;
else
playIndex = position;
notifyDataSetChanged();
}
});
}
It should get the job done. But it forces a redraw of all rows. In RecyclerView there is the notifyItemChanged method which can force redraw on single item.
You may try using the method here to update single row https://stackoverflow.com/a/3727813/4907678
My suggestion is migrating to RecyclerView and using notifyItemChanged.
cheers!

how to implement onclicklistener on InfoWindow on google map

I am using this GoogleMap.InfoWindowAdapter to show image on ImageView in the InfoWindow but I want to handle sliding events on it to show other images.
Here is my code:
public class MarkerInfoWindowAdapter implements GoogleMap.InfoWindowAdapter
{
public MarkerInfoWindowAdapter(Bitmap pbitMap){}
#Override
public View getInfoWindow(Marker marker)
{
ArrayList<String> lPhotos = new ArrayList();
File file=new File("/sdcard/trip/");
File[] list = file.listFiles();
int count = 0;
String lname = "";
for (File f: list){
lname = f.getName();
if (lname.endsWith(".jpg")){
count++;
lPhotos.add(lname);
}
System.out.println("170 " + count);
}
Bitmap mBitmap = getImageFileFromSDCard(lname);
View v = getLayoutInflater().inflate(R.layout.infowindow_layout, null);
ImageView markerIcon = (ImageView) v.findViewById(R.id.marker_icon);
markerIcon.setImageBitmap(mBitmap);
return v;
}
#Override
public View getInfoContents(Marker marker)
{
View v = getLayoutInflater().inflate(R.layout.infowindow_layout, null);
ImageView markerIcon = (ImageView) v.findViewById(R.id.marker_icon);
return v;
}
}
According to here, you should setImageBitmap in getInfoContents instead of getInfoWindow.
Sample code:
class MyInfoWindowAdapter implements InfoWindowAdapter{
private final View myContentsView;
boolean not_first_time_showing_info_window;
MyInfoWindowAdapter(){
myContentsView = getLayoutInflater().inflate(R.layout.custom_info_contents, null);
}
#Override
public View getInfoContents(Marker marker) {
ImageView imageView = (ImageView)myContentsView.findViewById(R.id.imgView);
TextView tvTitle = ((TextView)myContentsView.findViewById(R.id.title));
tvTitle.setText(marker.getTitle());
TextView tvSnippet = ((TextView)myContentsView.findViewById(R.id.snippet));
tvSnippet.setText(marker.getSnippet());
return myContentsView;
}
custom_info_contents.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:adjustViewBounds="true"
android:src="#drawable/ic_launcher"
android:id="#+id/imgView"/>
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="12dp"
android:textStyle="bold"/>
<TextView
android:id="#+id/snippet"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="10dp"/>
</LinearLayout>
</LinearLayout>
For more details, please refer to here and my project on github here.
EDIT
mMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
}
});

Not being able to fetch more than one image from Parse.com over the network

I created custom listview to display three blocks of textviews and an imageview. All of which are fetched from Parse.com. The string data is fetched properly but only one image is getting fetched in a session. Sometimes, no images are fetched. But the images show up only in the last position of the listview. I am unable to sort it out.
This is the snippet in my main2activity.java which fetches all the data from parse.com.
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("Students");
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> parseObjects, ParseException e) {
if(e==null) {
studentsList= new ArrayList<Students>();
for(ParseObject ob: parseObjects) {
s= new Students();
s.setName(ob.getString("Name").toString());
s.setUSN(ob.getString("USN").toString());
s.setSemester(ob.getString("Semester").toString());
ParseFile file = (ParseFile) ob.getParseFile("Image");
file.getDataInBackground(new GetDataCallback() {
#Override
public void done(byte[] bytes, ParseException e) {
if(e == null) {
Bitmap bmp = BitmapFactory.decodeByteArray( bytes, 0, bytes.length);
s.setPic(bmp);
} else {
Log.e(TAG,"Error while file fetching");
}
}
});
studentsList.add(s);
}
adapter = new CustomAdapter(Main2Activity.this, studentsList);
lv.setAdapter(adapter);
} else {
Toast.makeText(Main2Activity.this,e.getMessage(),Toast.LENGTH_SHORT).show();
}
}
});
This is the custom adapter.
public class CustomAdapter extends BaseAdapter{
private final static String TAG = CustomAdapter.class.getSimpleName();
private Context activity;
private LayoutInflater inflater = null;
private List<Students> student;
int layout;
public CustomAdapter(Context activity, List<Students> Student) {
this.activity = activity;
this.student = Student;
inflater = LayoutInflater.from(activity);
}
#Override
public int getCount() {
return student.size();
}
#Override
public Object getItem(int position) {
return student.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public class ViewHolder {
//ImageView imageView ;
TextView name ;
TextView usn ;
ImageView imageView;
TextView semester ;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
View v =view;
ViewHolder holder = new ViewHolder();
if (view == null) {
LayoutInflater li = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = li.inflate(R.layout.list_item_layout,null);
holder.name = (TextView)v.findViewById(R.id.name);
holder.usn = (TextView)v.findViewById(R.id.usn);
holder.semester = (TextView)v.findViewById(R.id.semester);
holder.imageView = (ImageView)v.findViewById(R.id.imageView);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
Students s = new Students();
s = student.get(position);
String a = s.Name;
Log.d(TAG,a);
holder.name.setText(s.getName());
holder.usn.setText(s.getUSN());
holder.semester.setText(s.getSemester());
holder.imageView.setImageBitmap(s.getPic());
Log.d("CustomAdapter.class", "CustomAdapter");
// imageView.setImageDrawable(s.getPic());
return v;
}
}
And this is list_item_layout.xml.
<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="com.redux.kumardivyarajat.parsedemo.Main2Activity"
android:background="#8003cbff">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/name"
android:textColor="#80000000"
android:textSize="25sp"
android:textStyle="bold"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/usn"
android:textSize="35sp"
android:textColor="#9bffa068"
android:textStyle="bold|italic"
android:layout_alignTop="#+id/imageView"
android:layout_alignRight="#+id/checkBox"
android:layout_alignEnd="#+id/checkBox" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/semester"
android:textSize="15sp"
android:textColor="#c8ff653a"
android:layout_below="#+id/name"
android:layout_toRightOf="#+id/imageView"
android:layout_toEndOf="#+id/imageView" />
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:id="#+id/imageView"
android:layout_below="#+id/semester"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="42dp" />
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Absent"
android:id="#+id/checkBox"
android:textStyle="bold"
android:textSize="20sp"
android:layout_above="#+id/usn"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginRight="42dp"
android:layout_marginEnd="42dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Semester-"
android:id="#+id/textView"
android:layout_below="#+id/name"
android:layout_toLeftOf="#+id/semester"
android:layout_toStartOf="#+id/semester"
android:textSize="15sp" />
</RelativeLayout>
ParseFile file = (ParseFile) ob.getParseFile("Image");
file.getDataInBackground(new GetDataCallback() {
#Override
public void done(byte[] bytes, ParseException e) {
if(e == null) {
Bitmap bmp = BitmapFactory.decodeByteArray( bytes, 0, bytes.length);
s.setPic(bmp);
} else {
Log.e(TAG,"Error while file fetching");
}
}
});
studentsList.add(s);
File is downloading as background job, before it gets download the loop will be finished and the bitmap wont store in student object.so, try to change the code and solve the issue.
May be u can try as follows
In Students class, create a url string.
Don't download the image from ParseFile, just get the file.getUrl() and add to the student object.
In adapter class, Use image caching libraries and finish your job.
libraries like Picasso, Glide, Volley, UIL or your own mechanism.
Hope this will solve your problem.

Fragment and Adapter in Android App Not Displaying Data

I'm really new in Android. I have this problem, I have an Activity (MainActivity) and there is a NavigationDrawer, this switches two fragments - ActivitiesFragment and ReportFragments.
The problem is with ActivitiesFragments, data is not displayed.
I have my adapter ready and my layouts ready and the fragment. When I debugg my app, it actually brings data, but is not shown. This is my code:
ActivitiesAdapter
public class ActivitiesAdapter extends ArrayAdapter<Activities>
{
Context mContext;
int mLayoutResourceId;
public ActivitiesAdapter(Context context, int layoutResourceId)
{
super(context, layoutResourceId);
mContext = context;
mLayoutResourceId = layoutResourceId;
}
public View getView(int position, View convertView, ViewGroup parent)
{
View row = convertView;
final Activities currentItem = getItem(position);
if (row == null)
{
LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
row = inflater.inflate(mLayoutResourceId, parent, false);
}
row.setTag(currentItem);
final TextView tituloview = (TextView) row.findViewById(R.id.tituloAct);
tituloview.setText(currentItem.getTitle());
final TextView descrpview = (TextView) row.findViewById(R.id.descrAct);
descrpview.setText(currentItem.getDescription());
return row;
}
}
This is my fragment ActivitiesFragment
public class ActivitiesFragment extends Fragment
{
protected static final String TAG = "ActivitiesFragmment";
private MobileServiceClient mClient;
private MobileServiceTable<Activities> mActivitiesTable;
private ActivitiesAdapter mAdapter;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.act_listfragment, container, false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
try
{
mClient = new MobileServiceClient("https://site.azure-mobile.net/",
"APPLICATIONKEYAPPLICATIONKEY",
getActivity().getApplicationContext()).withFilter(new ProgressFilter());
mActivitiesTable = mClient.getTable(Activities.class);
}
catch (MalformedURLException e)
{
createAndShowDialog(new Exception("There was an error creating the Mobile Service. Verify the URL"), "Error");
}
mAdapter = new ActivitiesAdapter(getActivity(), R.layout.act_itemlist);
ListView listViewToDo = (ListView) getView().findViewById(R.id.activities_fragment_list);
listViewToDo.setAdapter(mAdapter);
refreshItemsFromTable();
}
private void createAndShowDialog(Exception exception, String title)
{
createAndShowDialog(exception.toString(), title);
}
private void createAndShowDialog(String message, String title)
{
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity().getApplicationContext());
builder.setMessage(message);
builder.setTitle(title);
builder.create().show();
}
private void refreshItemsFromTable()
{
mActivitiesTable.execute(new TableQueryCallback<Activities>()
{
public void onCompleted(List<Activities> result, int count, Exception exception, ServiceFilterResponse response) {
if (exception == null) {
mAdapter.clear();
for (Activities item : result) {
mAdapter.add(item);
Log.i(TAG, "Titulo: " + item.getTitle());
}
} else {
createAndShowDialog(exception, "Error");
}
}
});
}
}
I don't know whats wrong, but I guess this block is not working on the OnActivityCreated method:
mAdapter = new ActivitiesAdapter(getActivity(), R.layout.act_itemlist);
ListView listViewToDo = (ListView) getView().findViewById(R.id.activities_fragment_list);
listViewToDo.setAdapter(mAdapter);
refreshItemsFromTable();
And here are my Layouts:
This is my frgament's layout:
<LinearLayout 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"
android:background="#e1e1e1"
android:orientation="vertical" >
<TextView
android:id="#+id/tvTituloActs"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/all_activities"
android:layout_marginLeft="16dp"
android:layout_marginTop="8dp"
android:textColor="#009ad2"
android:textAppearance="?android:attr/textAppearanceMedium" />
<ListView android:id="#+id/activities_fragment_list"
android:layout_marginTop="8dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF"
android:layout_weight="1"
tools:listitem="#layout/act_itemlist"
android:drawSelectorOnTop="false"/>
<TextView android:id="#id/android:empty"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="No hay datos"/>
</LinearLayout>
This is the layout act_itemlist. The row layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="64dp"
android:orientation="horizontal">
<ImageView
android:id="#+id/icon"
android:layout_width="32dp"
android:layout_height="32dp"
android:layout_marginLeft="8dp"
android:gravity="center_vertical"
android:src="#drawable/done"
android:layout_gravity="center_vertical"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/tvTituloAct"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:layout_marginTop="16dp"
android:textSize="16sp"/>
<TextView
android:id="#+id/tvDescrAct"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:text="Description de la actividad" />
</LinearLayout>
</LinearLayout>
I really need help with this! Please if someone can see something that I'm missing please tell me!
Thanks!!!!
Try to swap these lines:
mAdapter = new ActivitiesAdapter(getActivity(), R.layout.act_itemlist);
ListView listViewToDo = (ListView) getView().findViewById(R.id.activities_fragment_list);
refreshItemsFromTable(); // populate first before attaching your adapter
listViewToDo.setAdapter(mAdapter);
I finally solved my problem. Everything was Ok, the only detail was the layout. It was on the fragments layout.
<TextView android:id="#id/android:empty"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="No hay datos"/>
This textview did not let to show the data so I deleted it and worked.
Thankk you for your help #LazyNinja

ListView and Adapter with a large number of items

I am a newbie of android programming. After some study of ListView and ArrayAdapter, i decided to write a simple demo program just for practicing.
I want to display my custom view style ListView, so I override ArrayAdapter's getView() function. I know that for preventing memory leak, parameter convertView should be checked, and only inflate new object when convertView is null. I Also make a AsyncTask to keep adding data into ArrayAdapter in background(in doInBackground), and keep notifyDataChanged to ListView(in onProgressUpdate() ).
Here is the problem: when I set MAX_ITEM=50 (which means how many data i will add in AsyncTask), everything works fine. But when I set MAX_ITEM=500, logcat shows error message: "Caused by: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views." and application shut down. Can anyone tell me where the problem is? The following is my source code "MyTest.java" and my layout xml file "main.xml" and "layout_row.xml", thanks for your watching and helping.
MyTest.Java:
public class MyTest extends Activity {
private static final String TAG="Tany";
private static final int MAX_ITEM = 50;
private MyArrayAdapter adapter;
private ListView listview;
private int addCounter = 0;
public class MyData implements Comparable<MyData>{
public String str1;
public String str2;
public String str3;
public MyData(String str1, String str2, String str3){
this.str1 = str1;
this.str2 = str2;
this.str3 = str3;
}
#Override
public int compareTo(MyData data) {
// TODO Auto-generated method stub
int result = this.str1.compareTo(data.str1);
return result;
}
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
listview = (ListView)findViewById(R.id.listview);
adapter = new MyArrayAdapter(this, R.layout.layout_row);
//set adapter
listview.setAdapter(adapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
Log.d(TAG, "position "+position+" is clicked");
Toast.makeText(parent.getContext(), adapter.getItem(position).str1+", "+adapter.getItem(position).str2, Toast.LENGTH_SHORT).show();
}
});
listview.setTextFilterEnabled(true);
}
public void onStart(){
super.onStart();
MyTask newTask = new MyTask();
newTask.execute();
}
public class MyTask extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
for(int i = addCounter; i<MAX_ITEM; i++)
{
adapter.add(new MyData("str1="+i,"str2="+i,"str3="+i));
addCounter++;
publishProgress();
}
return null;
}
#Override
protected void onProgressUpdate(Void... progress ){
adapter.notifyDataSetChanged();
}
#Override
protected void onPostExecute(Void result){
Log.d(TAG, "AsyncTask MyTask finsish its work");
}
}
public class MyArrayAdapter extends ArrayAdapter<MyData>{
public MyArrayAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
// TODO Auto-generated constructor stub
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row;
if(convertView == null){
LayoutInflater inflater = getLayoutInflater();
row = inflater.inflate(R.layout.layout_row, parent, false);
}else{
Log.d(TAG,"recycle view, pos="+position);
row = convertView;
}
TextView tv1 = (TextView) row.findViewById(R.id.textView1);
tv1.setText( ((MyData)getItem(position)).str1 );
TextView tv2 = (TextView) row.findViewById(R.id.textView2);
tv2.setText( ((MyData)getItem(position)).str2 );
TextView tv3 = (TextView) row.findViewById(R.id.textView3);
tv3.setText( ((MyData)getItem(position)).str3 );
return row;
}
}
}
main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/vertical_container"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:text="#string/list_title_start"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</TextView>
<ListView
android:id="#+id/listview"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</ListView>
<TextView
android:text="#string/list_title_end"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</TextView>
</LinearLayout>
layout_row.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/linearLayout1"
android:orientation="horizontal">
<ImageView
android:layout_height="wrap_content"
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:src="#drawable/ic_launcher">
</ImageView>
<TextView
android:text="TextView1"
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="6dip"
android:layout_marginTop="6dip"
android:textAppearance="?android:attr/textAppearanceLarge">
</TextView>
</LinearLayout>
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/linearLayout1"
android:orientation="horizontal">
<TextView
android:id="#+id/textView2"
android:text="TextView"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall">
</TextView>
<TextView
android:text="TextView"
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:layout_marginLeft="6dip">
</TextView>
</LinearLayout>
</LinearLayout>
as Selvin rightly says You're modifying your Views from the method doInBackground which runs on another thread. In android this is forbidden, instead you should modify the views from the onPostExecute method also.

Categories

Resources