Add an image for Android marker info window - android

I'm making an android app. In this app, there are markers of some hotels and when user click on the marker info window appears and it should be like following image. (This is a web application)
I have a list view in my navigation drawer fragment and map fragment has the markers.
This is my code before I try to load image for the info window in MainActivity.java.
// Load Hotels
private class GetHotelTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... data) {
String identifier = data[0];
// Toast.makeText(getContext(), "Manuli "+identifier, Toast.LENGTH_LONG ).show();
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://api.ayubo.lk/android/retrievehotels");
HttpResponse response = null;
String responseStr = null;
try {
//add data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("long", data[0]));
nameValuePairs.add(new BasicNameValuePair("lat", data[1]));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//execute http post
response = httpclient.execute(httppost);
responseStr = EntityUtils.toString(response.getEntity());
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return responseStr;
}
protected void onPostExecute(String result) {
try {
JSONArray jObj = new JSONArray(result);
for(int a=0;a<jObj.length();a++){
JSONArray obj= (JSONArray) jObj.get(a);
Log.i("json", obj.get(3).toString());
Marker marker = GoogleMapsFragment.map.addMarker(new MarkerOptions()
.position(new LatLng( Double.valueOf(obj.get(3).toString()), Double.valueOf(obj.get(2).toString())))
.title(obj.get(1).toString()+" | simple Price : "+obj.get(4).toString())
.snippet(obj.get(5).toString())
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_marker_hotel)));
hotelMarkers.add(marker);
}
LatLng latLng = new LatLng(Double.valueOf(latitude),Double.valueOf(longtitude));
GoogleMapsFragment.map.moveCamera(CameraUpdateFactory.newLatLng(latLng));
GoogleMapsFragment.map.animateCamera(CameraUpdateFactory.zoomTo(15));
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
}
}
Here is the listview call of hotels inside MainActivity.java.
// Hotels
case 0:
if (A == 0){
Bundle bundle = new Bundle();
bundle.putString("restaurants", "Default");
fragmentObj = new GoogleMapsFragment();
fragmentObj.setArguments(bundle);
if (!sclItems.contains(0)){
new GetHotelTask().execute(longtitude, latitude);
sclItems.add(0);
}else {
removeHotels();
sclItems.remove((Integer)0);
}
A = 1;
}else {
if (!sclItems.contains(0)){
new GetHotelTask().execute(longtitude, latitude);
sclItems.add(0);
}else {
removeHotels();
sclItems.remove((Integer)0);
}
}
break;
I've tried adding info_window_layout.xml and here is the code.
<?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_prof"/>
<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>
But, I cannot load my info window like in the image. I've tried several solutions including this and any of that didn't give me a solution.
Can someone please help me with this?
Thanks in advance. :)
Error -

Figured it out finally. :D
Changed the info_window_layout.xml like this.
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#000000" >
<LinearLayout
android:id="#+id/text_box"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<ImageView
android:id="#+id/markerImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/distance"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
</ScrollView>
Then added a new class called, ManiInfoAdapter.java
class MapInfoWindowAdapter implements GoogleMap.InfoWindowAdapter {
private LayoutInflater inflater;
private Context context;
public MapInfoWindowAdapter(Context context){
inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
this.context = context;
}
#Override
public View getInfoWindow(Marker marker) {
// Getting view from the layout file
View v = inflater.inflate(R.layout.info_window_layout, null);
TextView title = (TextView) v.findViewById(R.id.title);
title.setText(marker.getTitle());
TextView address = (TextView) v.findViewById(R.id.distance);
address.setText(marker.getSnippet());
ImageView iv = (ImageView) v.findViewById(R.id.markerImage);
iv.setImageResource(R.drawable.ic_attraction1);
return v;
}
#Override
public View getInfoContents(Marker marker) {
return null;
}
}
Now working as expected. :)

Try this code :
Marker kiel=FragmentLeft.map.addMarker(new MarkerOptions().position(new LatLng(Double.parseDouble(p.getLatitude()), Double.parseDouble(p.getLongitude())))
.title(p.getEventName()).snippet(getLocationStringAddress(new LatLng(Double.parseDouble(p.getLatitude()), Double.parseDouble(p.getLongitude()))))
.icon(BitmapDescriptorFactory.fromResource(R.mipmap.map_set_marker)));
markers.put(kiel.getId(),"http://"+strPhoto);
kiel.setInfoWindowAnchor(1.95f,0.0f);
hMarker.put(kiel,p);
map.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
#Override
public View getInfoWindow(Marker arg0) {
View myContentView = flipscreen.this.getLayoutInflater().inflate(R.layout.custommarker, null);
TextView tvTitle = ((TextView) myContentView.findViewById(R.id.title));
tvTitle.setText(arg0.getTitle());
TextView tvSnippet = ((TextView) myContentView.findViewById(R.id.snippet));
tvSnippet.setText(arg0.getSnippet());
ImageView imgMarkerImage=(ImageView)myContentView.findViewById(R.id.imgMarkerImage);
System.out.println("List of Event Photos = " + strPhoto);
Picasso.with(flipscreen.this).load(markers.get(arg0.getId())).into(imgMarkerImage);
return myContentView;
}
#Override
public View getInfoContents(Marker marker) {
return null;
}
});
map.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
Iterator myVeryOwnIterator = hMarker.keySet().iterator();
while(myVeryOwnIterator.hasNext()) {
Marker key=(Marker)myVeryOwnIterator.next();
if(marker.getId().equals(key.getId())){
Event value=(Event)hMarker.get(key);
Activity_Event_Details.setEventDetails(value);
startActivity(new Intent(flipscreen.this,Activity_Event_Details.class));
}
}
}
});

I have tried to do the same for my app. I couldn't load images into the marker as I wanted.
So what I did was.
Created an xml layout maps_info_window_blue
I included into my map layout.
<fragment
android:id="#+id/map_booking_frg"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ImageView
android:id="#+id/center_marker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#id/shadowView"
android:layout_centerHorizontal="true"
android:src="#drawable/marker_start" />
<include layout="#layout/maps_info_window_blue"
android:id="#+id/rl_info_window_blue"
android:layout_width="wrap_content"
android:layout_centerHorizontal="true"
android:layout_above="#+id/shadowView"
android:layout_height="wrap_content"/>
<View
android:id="#+id/shadowView"
android:layout_width="wrap_content"
android:layout_height="1dp"
android:background="#color/transparent"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:visibility="invisible" />
For me the requirement was to have the marker info window in the center. You can set it where ever you want.
In order to give the illusion of a marker, I always set LatLng which I want to be the center of the map (CameraPosition target is set to the LatLng I want)

Try using info window adapter. This may help you i think.
mMap.setInfoWindowAdapter(setMarkerWindow());
private GoogleMap.InfoWindowAdapter setMarkerWindow() {
return new GoogleMap.InfoWindowAdapter() {
#Override
public View getInfoWindow(Marker marker) {
View myContentView = getLayoutInflater().inflate(
R.layout.map_info_window, null);
myContentView.setBackgroundColor(Color.TRANSPARENT);
TextView tvTitle = ((TextView) myContentView
.findViewById(R.id.title));
tvTitle.setText(marker.getTitle());
......
return myContentView;
}
#Override
public View getInfoContents(Marker marker) {
return null;
}
};
}

Related

Android 4.2.2 Map Fragment Issue

I have a map with toolbar and a autocomplete search bar in coordinate layout . Everything works fine in Android version above 4.x but in Android 4.2.2 , shows only map . The toolbar and autocomplete textview is not showing .
Please help me to understand why this is happening .
Xml :
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<include
android:id="#+id/toolbar"
layout="#layout/activity_self_assigned_toolbar" />
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginEnd="10dp"
android:layout_marginStart="10dp"
android:layout_marginTop="60dp"
android:background="#FFFF"
android:weightSum="1">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="horizontal">
<AutoCompleteTextView
android:id="#+id/autocomplete"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_gravity="bottom"
android:layout_weight="0.5"
android:hint="Type in your Location">
</AutoCompleteTextView>
<ImageView
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_gravity="center"
android:layout_weight="0"
android:id="#+id/custom_map_cross"
android:src="#drawable/icn_close"/>
<!--<Button-->
<!--android:id="#+id/search_button"-->
<!--android:layout_width="20dp"-->
<!--android:layout_weight="0.5"-->
<!--android:layout_height="40dp"-->
<!--android:layout_marginRight="5dp"-->
<!--android:layout_gravity="center"-->
<!--android:padding="5dp"-->
<!--android:background="#color/indigo_500"-->
<!--android:textColor="#android:color/white"-->
<!--android:text="Save" />-->
</LinearLayout>
</android.support.design.widget.AppBarLayout>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
</android.support.design.widget.CoordinatorLayout>
map.java :
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.custom_map_layout,container,false);
ButterKnife.inject(this,view);
// view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
// ViewGroup.LayoutParams.MATCH_PARENT));
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
// SupportMapFragment mapFragment = (SupportMapFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.map);
// mMap = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map))
// .getMap();
initialise();
initialiseListeners();
autoCompView.setAdapter(new GooglePlacesAutocompleteAdapter(getActivity(), R.layout.map_single_item));
autoCompView.setOnItemClickListener(this);
saveButton.setOnClickListener(this);
cancelButton.setOnClickListener(this);
return view;
}
private void initialise() {
// toolbar.setNavigationIcon(R.drawable.ic_keyboard_arrow_left_black_24dp);
activity = (AppCompatActivity) getActivity();
toolbar.setTitle("Address");
}
private void initialiseListeners() {
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
getActivity().onBackPressed();
}
});
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
View view1 = getActivity().getCurrentFocus();
if (view1 != null) {
InputMethodManager imm = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view1.getWindowToken(), 0);
}
// and next place it, for exemple, on bottom right (as Google Maps app)
str = (String) parent.getItemAtPosition(position);
// Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
getLocationFromAddress(str);
if (latitude != null && longitude != null) {
LatLng latLng = new LatLng(latitude, longitude);
mMap.addMarker(new MarkerOptions().position(latLng));
CameraPosition pos = CameraPosition.builder()
.target( latLng)
.zoom( 12f )
.bearing( 0.0f )
.tilt( 0.0f )
.build();
mMap.setMyLocationEnabled(true);
mMap.animateCamera( CameraUpdateFactory
.newCameraPosition( pos ), null );
}
}
public void getLocationFromAddress(String strAddress) {
Geocoder coder = new Geocoder(context);
List<Address> address;
try {
address = coder.getFromLocationName(strAddress, 5);
if (address != null) {
Address location = address.get(0);
latitude = location.getLatitude();
longitude = location.getLongitude();
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.self_assignment_save_textview:
new generateCheckinsTask(context).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
break;
case R.id.self_assignment_cancel_textview:
//
// getActivity().getSupportFragmentManager().popBackStack();
break;
}
}
private class generateCheckinsTask extends AsyncTask {
private Context context;
generateCheckinsTask(Context context) {
this.context = context;
}
#Override
protected Object doInBackground(Object[] params) {
return null;
}
#Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
Time time = new Time();
time.setToNow();
Fragment_Self_Assignment self_assignment = new Fragment_Self_Assignment();
self_assignment.updateAddress(str,latitude,longitude);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
// if (materialDialog != null && materialDialog.isShowing()) {
// materialDialog.dismiss();
// }
getActivity().finish();
}
}, 500);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
}
#Override
public void onResume() {
Spannable actionBarTitle = new SpannableString("Add Place");
actionBarTitle.setSpan(
new ForegroundColorSpan(Color.WHITE),
0,
actionBarTitle.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
if(((AppCompatActivity) getActivity()).getSupportActionBar() != null){
((AppCompatActivity) getActivity()).getSupportActionBar().setTitle(actionBarTitle);
InputMethodManager imm = (InputMethodManager) getActivity()
.getSystemService(Context.INPUT_METHOD_SERVICE);
if(!imm.isAcceptingText()){
imm.hideSoftInputFromWindow(getView().getWindowToken(),0);
}
}
super.onResume();
}
#Override
public void onStart() {
super.onStart();
if (activity.getSupportActionBar().isShowing())
activity.getSupportActionBar().hide();
}
#Override
public void onStop() {
super.onStop();
if (!activity.getSupportActionBar().isShowing())
activity.getSupportActionBar().show();
}
public static ArrayList autocomplete(String input) {
ArrayList resultList = null;
HttpURLConnection conn = null;
StringBuilder jsonResults = new StringBuilder();
try {
StringBuilder sb = new StringBuilder(PLACES_API_BASE + TYPE_AUTOCOMPLETE + OUT_JSON);
sb.append("?key=" + API_KEY);
// sb.append("&components=country:gr");
sb.append("&input=" + URLEncoder.encode(input, "utf8"));
URL url = new URL(sb.toString());
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
// Load the results into a StringBuilder
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1) {
jsonResults.append(buff, 0, read);
}
} catch (MalformedURLException e) {
Log.e(LOG_TAG, "Error processing Places API URL", e);
return resultList;
} catch (IOException e) {
Log.e(LOG_TAG, "Error connecting to Places API", e);
return resultList;
} finally {
if (conn != null) {
conn.disconnect();
}
}
try {
// Create a JSON object hierarchy from the results
JSONObject jsonObj = new JSONObject(jsonResults.toString());
JSONArray predsJsonArray = jsonObj.getJSONArray("predictions");
// Extract the Place descriptions from the results
resultList = new ArrayList(predsJsonArray.length());
for (int i = 0; i < predsJsonArray.length(); i++) {
System.out.println(predsJsonArray.getJSONObject(i).getString("description"));
System.out.println("============================================================");
resultList.add(predsJsonArray.getJSONObject(i).getString("description"));
}
} catch (JSONException e) {
Log.e(LOG_TAG, "Cannot process JSON results", e);
}
return resultList;
}
}
ISSUE : image(4.2.2 version):
image of same code on greater version (code working fine):
check this one
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<include
android:id="#+id/toolbar"
layout="#layout/toolbar" />
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginEnd="10dp"
android:layout_marginStart="10dp"
android:layout_marginTop="60dp"
android:background="#FFFF"
android:weightSum="1">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="horizontal">
<AutoCompleteTextView
android:id="#+id/autocomplete"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_gravity="bottom"
android:layout_weight="0.5"
android:hint="Type in your Location">
</AutoCompleteTextView>
<ImageView
android:id="#+id/custom_map_cross"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_gravity="center"
android:layout_weight="0"
android:src="#drawable/pick_ticket_bg_large" />
</LinearLayout>
</android.support.design.widget.AppBarLayout>
</RelativeLayout>
Your MapFragment is overlaping your ToolBar and autocomplete search bar, keep them above MapFragment.
Try this.
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<include
android:id="#+id/toolbar"
layout="#layout/activity_self_assigned_toolbar" />
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginEnd="10dp"
android:layout_marginStart="10dp"
android:layout_marginTop="60dp"
android:background="#FFFF"
android:weightSum="1">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="horizontal">
<AutoCompleteTextView
android:id="#+id/autocomplete"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_gravity="bottom"
android:layout_weight="0.5"
android:hint="Type in your Location">
</AutoCompleteTextView>
<ImageView
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_gravity="center"
android:layout_weight="0"
android:id="#+id/custom_map_cross"
android:src="#drawable/icn_close"/>
</LinearLayout>
</android.support.design.widget.AppBarLayout>
</RelativeLayout>
</android.support.design.widget.CoordinatorLayout>

Android Studio Unable to Display Photo Gallery on ListView

I'm developing a business profile page which contains profile image contact data and a photo gallery. I'm using Listview to check the urls from the received JSON data.
The problem is: the listview is not displayed on profile_layout. not inflated. Anyone can help?
Thanks a lot.
Here're the codes:
ProfileActivity.java
private void getGalleryJSON(String url) {
listView = (ListView) findViewById(R.id.gallery_listview);
galleryAdapter = new GalleryAdapter(this, R.layout.gallery_layout);
listView.setAdapter(galleryAdapter);
class GetGalleryJSON extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
String uri2 = params[0];
BufferedReader bufferedReader = null;
try {
URL url = new URL(uri2);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while((json = bufferedReader.readLine())!= null){
sb.append(json+"\n");
}
bufferedReader.close();
con.disconnect();
return sb.toString().trim();
}catch(Exception e){
return null;
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
gallery_json = s;
//TextView tv = (TextView)findViewById(R.id.gallery_content);
//tv.setText(gallery_json);
//=====================================
//======================================
// JSON OBJECT RECEIVED PERFECTLY
//======================================
//======================================
try {
gallery_jsonObject = new JSONObject(gallery_json);
gallery_jsonArray = gallery_jsonObject.getJSONArray("result");
int count = 0;
String thumb;
while (count < gallery_jsonArray.length()){
JSONObject JO = gallery_jsonArray.getJSONObject(count);
thumb = JO.getString("thumburl");
Gallery gallery = new Gallery(thumb);
galleryAdapter.add(gallery);
count++;
}
} catch (JSONException e1) {
e1.printStackTrace();
}
}
}
GetGalleryJSON ggj = new GetGalleryJSON();
ggj.execute(url);
}
This is the adapter GalleryAdapter.java
public class GalleryAdapter extends ArrayAdapter{
List list = new ArrayList();
public GalleryAdapter(Context context, int resource)
{
super(context, resource);
}
public void add(Profiles object) {
super.add(object);
list.add(object);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row;
row = convertView;
GalleryHolder galleryHolder;
if(row == null){
LayoutInflater layoutInflater = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.gallery_layout, parent, false);
galleryHolder = new GalleryHolder();
galleryHolder.img_url = (TextView) row.findViewById(R.id.img_url);
row.setTag(galleryHolder);
}
else {
galleryHolder = (GalleryHolder) row.getTag();
}
Gallery gallery = (Gallery) this.getItem(position);
galleryHolder.img_url.setText(gallery.getUrl());
//=====================================
//======================================
// LATER I WILL USE THIS FOR IMAGEVIEW
//======================================
//===== //Picasso.with(this.getContext()).load(gallery.getUrl()).into(galleryHolder.img_url);
return row;
}
static class GalleryHolder{
TextView img_url;
}}
And this is the Gallery.java
public class Gallery {
private String url;
public Gallery(String url)
{
this.setUrl(url);
}
public void setUrl(String url){
this.url = url;
}
public String getUrl(){
return url;
}}
I use this layout on profile page
<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="fill_parent"
android:orientation="vertical"
>
<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fitsSystemWindows="true"
android:orientation="horizontal"
>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
screen-wide thumb
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:id="#+id/data">contact data
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="top"
android:padding="10dp"
android:id="#+id/content">
<TextView
android:id="#+id/txt_content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:editable="false"
android:text="Content" />
</LinearLayout>
<TextView
android:id="#+id/gallery_content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Gallery"
android:textAlignment="center"
/>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="top"
android:padding="10dp"
android:id="#+id/gallery">
<ListView
android:id="#+id/gallery_listview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="5dp"
android:columnWidth="100dp"
android:drawSelectorOnTop="true"
android:gravity="center"
android:numColumns="auto_fit"
android:stretchMode="columnWidth"
android:verticalSpacing="5dp"
android:focusable="true"
android:clickable="true"
android:background="#FF0000"
/>
</LinearLayout>
</LinearLayout>
</ScrollView>
And this is the gallery_layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="85dp">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/img_url"
/>
</RelativeLayout>
Note:
I am using listview to check the urls only. I will change to GridView later
Probably your listview's height is calculated 'zero'. It's not recommended to put a listview inside scrollview, because the listview can not be scrolled anymore.
But if you insist to do this, calculate the listview's total height & update its height in runtime according to this answer: How to measure total height of ListView
But first set the listview's layout_height to wrap_content.

Android ListView lags for every scroll, even with ViewHolder

I want to give a little context: The app I'm currently involved in helping develop is an app a company has already developed for IOS and Android but the Android developer didn't delivered the expected results (mostly performance wise) so the leader gave me the code to see if I could fix it. Given the code I tried to improve it, now, the app is a picture sharing app somewhat like Instagram and it uses and endless scrolling list, the problem with the app is that every time I scroll a little bit, the app lags or freezes for a second and then loads a new row.
The listview only has one row visible at any moment.
What have I tried?:
The adapter wasn't using the ViewHolder pattern so I tried to implement it.
The programmer was defining a lot of click listeners on the getView method so I removed them.
still, every time I scroll ( a new row appears as there's only one visible row at any time) it lags. Are there any other noticeable problems here that could be the cause?
On another note, on this view there's a lot of overdraw so, maybe it's affecting the performance on the ListView? if so, tell me and I'll post the XML part.
Here's the code I adapted:
public class SomeFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener {
// declaration and constructors.....
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
//initialization......
//setting variables.......
//getting views.....
listview = (ListView)rootView.findViewById(R.id.listview);
listview.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
int threshold = 1;
int count = listview.getCount();
if (scrollState == SCROLL_STATE_IDLE) {
if (listview.getLastVisiblePosition() >= count - threshold) {
int position = listview.getLastVisiblePosition();
if (!loading) {
loading = true;
listview.addFooterView(footerView, null, false);
currentVal = position + 1;
LoadMoreStuffAsyncTask loadMoreStuffAsyncTask = new LoadMoreStuffAsyncTask();
loadMoreStuffAsyncTask.execute();
}
}
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
int topRowVerticalPosition = (listview == null || listview.getChildCount() == 0) ? 0 : listview.getChildAt(0).getTop();
swipeRefreshLayout.setEnabled(firstVisibleItem == 0 && topRowVerticalPosition >= 0);
}
});
LoadStuffAsyncTask loadStuffAsyncTask=new LoadStuffAsyncTask();
loadStuffAsyncTask.execute();
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.activity, container, false);
swipeRefreshLayout = (SwipeRefreshLayout)rootView.findViewById(R.id.swipe);
swipeRefreshLayout.setOnRefreshListener(SomeFragment.this);
return rootView;
}
private void LoadStuff () {
list=null;
ParseQuery<ParseObject> query = null;
query = ParseQuery.getQuery("Objects");
query.orderByDescending("createdAt");
query.include("User");
query.setLimit(20);
try {
list = query.find();
} catch (ParseException e) {
e.printStackTrace();
}
}
private void LoadMoreStuff () {
List<ParseObject> moreList=null;
ParseQuery<ParseObject> query = null;
query = ParseQuery.getQuery("Objects");
query.orderByDescending("createdAt");
query.include("User");
query.setLimit(20);
query.setSkip(currentVal);
try {
moreList = query.find();
if(moreList!=null|| moreList.size()!=0){
for(int i =0;i<moreList.size();i++){
list.add(moreList.get(i));
}
}else{
loading=false;
}
} catch (ParseException e) {
e.printStackTrace();
loading=false;
}
}
#Override
public void onRefresh() {
swipeRefreshLayout.setRefreshing(true);
listAdapter.notifyDataSetChanged();
LoadStuffAsyncTask loadStuffAsyncTask=new LoadStuffAsyncTask();
loadStuffAsyncTask.execute();
}
class LoadMoreStuffAsyncTask extends AsyncTask<Void, Void, Void>{
private ProgressDialog pDialog;
#Override
protected Void doInBackground(Void... params) {
LoadMoreStuff();
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
listAdapter.updateList(list);
listview.setAdapter(listAdapter);
loading=false;
listview.removeFooterView(footerView);
listview.setSelection(currentVal);
}
}
class LoadStuffAsyncTask extends AsyncTask<Void, Void, Void>{
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(activity);
pDialog.setMessage(activity.getString(R.string.loading));
pDialog.setCancelable(false);
pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
LoadStuff();
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
pDialog.dismiss();
swipeRefreshLayout.setRefreshing(false);
listAdapter = new CustomAdapter(activity,momentosGeneral);
listview.setAdapter(listAdapter);
}
}
}
This is the adapter:
public class CustomAdapter extends BaseAdapter {
//declaration of variables.....
public CustomAdapter(ActionBarActivity activity, List<ParseObject> list) {
this.activity = activity;
this.list = list;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
private static class ViewHolder{
//holderfields......
}
#Override
public View getView(final int position, View v, ViewGroup parent) {
ViewHolder holder;
if (v == null) {
v = View.inflate(activity.getApplicationContext(), R.layout.customview, null);
holder = new ViewHolder();
holder.profilepicture = (CircularImageView) v.findViewById(R.id.profilepic);
holder.username = (TextView) v.findViewById(R.id.username);
holder.picture = (ParseImageView) v.findViewById(R.id.picture);
holder.container =(LinearLayout)v.findViewById(R.id.container);
holder.share=(LinearLayout)v.findViewById(R.id.share);
holder.comment= (TextView) v.findViewById(R.id.comment);
holder.likes= (TextView) v.findViewById(R.id.likes);
holder.publishDate =(TextView)v.findViewById(R.id.publisdate);
holder.liked = (ImageView)v.findViewById(R.id.liked);
v.setTag(holder);
}
holder = (ViewHolder)v.getTag();
CustomTypography customTypo = new CustomTypography(activity.getApplicationContext());
holder.username.setTypeface(customTypo.OpenSansSemibold());
if(list.get(position).getParseUser("User")!=null){
holder.username.setText(list.get(position).getParseUser("User").getString("name"));
profilePic = list.get(position).getParseUser("User").getParseFile("profilePic");
if (profilePic != null) {
try {
Drawable drawable = new BitmapDrawable(BitmapFactory.decodeByteArray(profilePic.getData(), 0, profilePic.getData().length));
holder.profilepicture.setImageDrawable(drawable);
holder.profilepicture.setDrawingCacheEnabled(true);
} catch (Exception e) {
e.printStackTrace();
}
}
}
else{
holder.username.setText("");
}
final ParseFile picture = list.get(position).getParseFile("picture");
if (picture != null) {
try {
Drawable drawable = new BitmapDrawable(BitmapFactory.decodeByteArray(picture.getData(), 0, picture.getData().length));
holder.picture.setImageDrawable(drawable);
holder.picture.setDrawingCacheEnabled(true);
} catch (Exception e) {
e.printStackTrace();
}
}
else{
}
holder.container.setLayoutParams(customLayoutParams);
holder.comment.setText(capitalizarPrimeraLetra(list.get(postiion).getString("Comment")));
holder.comment.setTypeface(customTypo.OpenSansRegular());
final int likes= list.get(position).getInt("Likes");
if(likes==0|| likes<0){
holder.likes.setText("");
}else{
holder.likes.setText(String.valueOf(likes));
}
holder.likes.setTypeface(customTypo.OpenSansLight());
holder.publishDate.setText(timeBetween(list.get(position).getCreatedAt()));
ParseQuery<ParseObject> query = ParseQuery.getQuery("LikedPictures");
query.whereEqualTo("picture", list.get(position));
query.whereEqualTo("user", currentUser);
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> likelist, ParseException e) {
if (e == null) {
if (likelist.size() != 0) {
hasLiked = true;
holder.liked.setBackground(activity.getApplicationContext().getResources().getDrawable(R.drawable.like));
holder.likes.setTextColor(activity.getApplicationContext().getResources().getColor(R.color.red));
} else {
hasLiked = false;
}
} else {
hasLiked = false;
}
}
});
return v;
}
private String timeBetween(Date date){
String result="";
Date parsedPictureDate = null;
Date parsedCurrentDate=null;
Date today = new Date();
SimpleDateFormat dateFormatGmt = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");
dateFormatGmt.setTimeZone(TimeZone.getTimeZone("GMT"));
SimpleDateFormat dateFormatLocal = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");
try {
parsedPictureDate= dateFormatLocal.parse(dateFormatGmt.format(date));
parsedCurrentDate=dateFormatLocal.parse(dateFormatGmt.format(hoy));
} catch (java.text.ParseException e) {
result="";
}
long milis=parsedCurrentDate.getTime()-parsedPictureDate.getTime();
final long MILISECS_PER_MINUTE=milis/(60 * 1000);
final long MILISECS_PER_HOUR=milis/(60 * 60 * 1000);
final long MILLSECS_PER_DAY=milis/(24 * 60 * 60 * 1000);
if(milis<60000){
result="Now";
}
if(milis>=60000&&milis<3600000){
result=MILISECS_PER_MINUTE+" min";
}
if(milis>=3600000&&milis<86400000){
result=MILISECS_PER_HOUR+" h";
}
if(milis>=86400000){
result=MILLSECS_PER_DAY+" d";
}
return result;
}
This is the item that always gets populated in the listview
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical" android:layout_width="match_parent"
android:background="#android:color/white"
android:paddingBottom="20dp"
android:layout_height="match_parent">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:id="#+id/somelayout"
android:layout_weight="0.5"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="#dimen/margin_16dp_sw600"
android:layout_marginLeft="5dp"
android:paddingRight="#dimen/padding_16dp_sw600"
android:gravity="left"
android:layout_marginBottom="5dp">
<customImageView
android:layout_gravity="center"
android:layout_width="50dp"
android:layout_height="50dp"
android:id="#+id/profilepicture"
app:border_width="0dp"
/>
<TextView
android:layout_marginLeft="#dimen/margin_16dp_sw600"
android:layout_gravity="center"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/username"
android:textSize="14sp"
android:gravity="left"
android:singleLine="true"
android:minLines="1"
android:maxLines="1"
android:lines="1"
/>
</LinearLayout>
<LinearLayout
android:id="#+id/layoutTime"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="right"
android:layout_weight="0.5"
android:layout_gravity="center" >
<TextView
android:gravity="right"
android:id="#+id/publishdate"
android:layout_marginRight="#dimen/margin_16dp_sw600"
android:textSize="14sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:paddingLeft="5dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<LinearLayout
android:id="#+id/container"
android:layout_gravity="center"
android:background="#drawable/border"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<com.parse.ParseImageView
android:layout_margin="1dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/picture" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<LinearLayout
android:id="#+id/layoutlikes"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="left"
android:layout_weight="0.5"
android:layout_gravity="center" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:id="#+id/likes"
>
<TextView
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/numlikes"
android:text="0"
android:textSize="14sp"
android:layout_margin="#dimen/margin_16dp_sw600"
/>
<ImageView
android:layout_gravity="center"
android:layout_marginRight="#dimen/margin_16dp_sw600"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/likepic"
android:background="#drawable/like_off"
/>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="#+id/sharelayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="right"
android:padding="10dp"
android:layout_weight="0.5"
android:layout_marginTop="#dimen/margin_16dp_sw600"
android:layout_gravity="center" >
<ImageView
android:layout_gravity="center"
android:layout_marginRight="#dimen/margin_16dp_sw600"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/sharepic"
android:background="#drawable/ellipsis"
/>
</LinearLayout>
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="#dimen/division_2dp_sw_600"
android:layout_margin="#dimen/margin_16dp_sw600"
android:background="#color/loading" />
<TextView
android:layout_gravity="left"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/comment"
android:textSize= "14sp"
android:layout_marginLeft="#dimen/margin_16dp_sw600"
android:layout_marginRight="#dimen/margin_16dp_sw600"
/>
</LinearLayout>
Your biggest performance hit is probably the code below. You should use some sort of caching rather than decoding the Bitmap each time.
if (profilePic != null) {
try {
Drawable drawable = new BitmapDrawable(BitmapFactory.decodeByteArray(profilePic.getData(), 0, profilePic.getData().length));
holder.profilepicture.setImageDrawable(drawable);
holder.profilepicture.setDrawingCacheEnabled(true);
} catch (Exception e) {
e.printStackTrace();
}
Also, you are creating a new CustomTypography instance everytime getView() is called. I assume this class extends Typeface, in which case you could just use a single instance that gets initialised in the adapter's constructor.
Here are a couple of things:
1. in your adapter.getView() method, move the
holder = (ViewHolder)v.getTag();
to if/else scope:
if(view ==null){
//creation of viewHolder
}else{
holder = (ViewHolder)v.getTag();
}
2. There is too much code in the adapter.getView(), specially the parse query. You better call it once per item, by caching the result of query for each item in adapter. It is currently being called on every item get visible on scroll.
3. Try to reduce the count of views in your item's xml. Too many views in ListView items cause in memory leak and low performance.
4. Adding the hardwareAccelerated="true" to your activity in manifest might help.
5. Try to comment out the scroll listener, to find out if it is reducing the performance.

How to Change ListView to GridView on Button Click in android

I want to change my view listview to gridview and back gridview to listview on a button click.Here my product.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">
<LinearLayout
android:id="#+id/main_linear_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/image_product"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/product_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="name"
android:visibility="gone"/>
<TextView
android:id="#+id/product_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="name"
android:textColor="#166CED"
android:textAppearance="?android:attr/textAppearanceLarge"/>
<TextView
android:id="#+id/product_price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1000"
android:textColor="#D64530"/>
<TextView
android:id="#+id/product_discount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="discout price"
android:textColor="#D64530"
android:textAppearance="?android:attr/textAppearanceSmall"/>
<TextView
android:id="#+id/product_href"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="name"
android:visibility="gone"/>
<RatingBar
android:id="#+id/rating"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"/>
</LinearLayout> </LinearLayout></LinearLayout>
Here My product_category.xml:-
<?xml version="1.0" encoding="utf-8"?>
<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="shoppingmazza.android.catalyst.com.dynamiclayout.ProductCategory">
<!-- Header aligned to top -->
<RelativeLayout
android:id="#+id/header_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="FILTER"
android:id="#+id/textView" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="SORT"
android:id="#+id/textView2"
android:layout_marginLeft="257dp"
android:layout_marginStart="257dp" />
</LinearLayout>
</RelativeLayout>
<LinearLayout
android:layout_below="#+id/header_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<ListView
android:id="#+id/list_product"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:listitem="#layout/product"/>
</LinearLayout>
</RelativeLayout>
Here My ProductCategory.java:-
public class ProductCategory extends AppCompatActivity {
private ListView listView;
ProductAdapter adapter;
ArrayList<shoppingmazza.android.catalyst.com.dynamiclayout.Product> productsList;
private int len;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.product_category);
new Product().execute("http://opencart.codeniques.com/shopping/?route=feed/web_api/products&category=369&key=test123$");
listView = (ListView)findViewById(R.id.list_product);
productsList = new ArrayList<shoppingmazza.android.catalyst.com.dynamiclayout.Product>();
adapter = new ProductAdapter(getApplicationContext(),R.layout.product,productsList);
listView.setAdapter(adapter);
}
public class Product extends AsyncTask<String,Void,Boolean>{
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(ProductCategory.this);
dialog.setMessage("Loading, please wait");
dialog.setTitle("Connecting server");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... params) {
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(params[0]);
HttpResponse response = client.execute(post);
int status = response.getStatusLine().getStatusCode();
if(status==200){
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsonObject = new JSONObject(data);
JSONArray jsonArray = jsonObject.getJSONArray("products");
for(int i=0;i<jsonArray.length();i++){
len=jsonArray.length();
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
shoppingmazza.android.catalyst.com.dynamiclayout.Product product = new shoppingmazza.android.catalyst.com.dynamiclayout.Product();
product.setId(jsonObject1.getString("id"));
product.setName(jsonObject1.getString("name"));
product.setPrice(jsonObject1.getString("pirce"));
product.setDiscountprice(jsonObject1.getString("discountprice"));
product.setHref(jsonObject1.getString("href"));
product.setThumb(jsonObject1.getString("thumb"));
product.setRating(jsonObject1.getString("rating"));
productsList.add(product);
}
return true;
}
}catch (IOException |JSONException e){
Log.e("Error :",e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(Boolean aVoid) {
dialog.dismiss();
adapter.notifyDataSetChanged();
if(!aVoid){
Toast.makeText(ProductCategory.this, "Data is not Parsed", Toast.LENGTH_LONG).show();
}
else{
ProductAdapter adapter = new ProductAdapter(getApplicationContext(),R.layout.product,productsList);
listView.setAdapter(adapter);
}
}
}
}
Here My ProductAdapter.java:-
public class ProductAdapter extends ArrayAdapter<Product> {
ArrayList<Product> productsList;
LayoutInflater vi;
int Resource;
ViewHolder holder;
public ProductAdapter(Context context, int resource, ArrayList<Product> object) {
super(context, resource, object);
vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
productsList = object;
Resource = resource;
// this.context = context;
}
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
holder = new ViewHolder();
v = vi.inflate(Resource, null);
holder.imageView=(ImageView)v.findViewById(R.id.image_product);
holder.tvId = (TextView)v.findViewById(R.id.product_id);
holder.tvName = (TextView)v.findViewById(R.id.product_name);
holder.tvPrice = (TextView)v.findViewById(R.id.product_price);
holder.tvDiscount = (TextView)v.findViewById(R.id.product_discount);
holder.tvHref = (TextView)v.findViewById(R.id.product_href);
holder.tvRating = (RatingBar)v.findViewById(R.id.rating);
v.setTag(holder);
}
else{
holder = (ViewHolder)v.getTag();
}
new DownlaoadImageTask(holder.imageView).execute(productsList.get(position).getThumb());
holder.tvId.setText(productsList.get(position).getId());
holder.tvName.setText(productsList.get(position).getName());
holder.tvPrice.setText(productsList.get(position).getPrice());
holder.tvDiscount.setText(productsList.get(position).getDiscountprice());
holder.tvHref.setText(productsList.get(position).getHref());
holder.tvRating.setNumStars(Integer.parseInt(productsList.get(position).getRating()));
return v;
}
static class ViewHolder{
public TextView tvId;
public TextView tvName;
public TextView tvPrice;
public TextView tvDiscount;
public TextView tvHref;
public ImageView imageView;
public RatingBar tvRating;
}
private class DownlaoadImageTask extends AsyncTask<String,Void,Bitmap>{
ImageView bmImage;
public DownlaoadImageTask(ImageView bmImage){
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls){
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try{
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (IOException e){
Log.e("Error", e.getMessage());
}
return mIcon11;
}
protected void onPostExecute(Bitmap result){
bmImage.setImageBitmap(result);
}
}
}
I am new in android developing Please Help me thanks in advance!
You can add both ListView and GridView and set GridView android:visibility="gone"
<LinearLayout
android:layout_below="#+id/header_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<ListView
android:id="#+id/list_product"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:listitem="#layout/product"/>
<GridView
android:id="#+id/list_productGV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
on button click change visibilty of ListView to gone and GridView to visible and vice versa
1.You can try to use GridView only and change it's columns number using gridview.setNumColumns(n);. For ListView imitation just use n = 0.
2.Another option is to use RecyclerView with GridLayoutManager.
final int gridSpanCount = 4;
mImagesGrid = (RecyclerView) findViewById(R.id.gallery);
mLayoutManager = new GridLayoutManager(this, gridSpanCount);
mImagesGrid.setLayoutManager(mLayoutManager);
mSwitch = (Button) findViewById(R.id.switch_btn);
mSwitch.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v){
if (mLayoutManager.getSpanCount() == gridSpanCount){
mLayoutManager.setSpanCount(1);
}
else {
mLayoutManager.setSpanCount(gridSpanCount);
}
}
}

how to show text above list ,i use ListActivity to show a custom list

dear
how to show text above customise list when i extends listactivity in my class file..the code is given below..
public class ServerResponce extends ListActivity {
private ArrayList<listobj> tobj = new ArrayList<listobj>();
static String str1;
PickUpLocation pickup=new PickUpLocation();
String pickuplocid= pickup.locationid;
String des=planner.description;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
**//here not work force close**
// ****setContentView(R.layout.list_item);
**// TextView tv = (TextView)findViewById(R.id.text1);
// tv.setText("i want to book a cab for 4 hr/40km from sushant lok to delhi air port at" +
// "4 pm today"
// +"the cab should be 4 seater compact cab with carriage");
// tv.setBackgroundColor(R.color.black);**
//
new MyTask().execute();
}
private class MyTask extends AsyncTask<Void, Void, Void>
{
private ProgressDialog progressDialog;
protected void onPreExecute() {
progressDialog = ProgressDialog.show(ServerResponce.this,
"", "Loading. Please wait...", true);
}
protected void onProgressUpdate(Integer... integer){
TextView tv = null;
tv.setText("gjh");
}
#Override
protected Void doInBackground(Void... arg0) {
try {
URL url = new URL("http://qrrency.com/mobile/j2me/cab/CabBookingStatus.php?requestid=666");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
int l=0;
int k=0;
StringBuffer buffer=new StringBuffer();
String str=" ";
while ((l=in.read())!=-1)
{
buffer.append((char)l);
str=str+(char)l;
}
in.close();
//
try {
JSONObject json = new JSONObject(str);
JSONArray nameArray=json.getJSONArray("bookings");
JSONObject[] cabListing=new JSONObject[nameArray.length()];
for (int i = 0; i < cabListing.length; i++) {
//JSONObject jSONObject = cabListing[i];
JSONObject jSONObject = nameArray.getJSONObject(i);
listobj tweet = new listobj();
JSONObject temp=jSONObject.getJSONObject("booking");
tweet.cabid = temp.getString("cabbookingid");
tweet.author =temp.getString("CabDriverName");
tweet.content =temp.getString("price");
tweet.cabrat=temp.getString("cabrating");
tobj.add(tweet);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (MalformedURLException e)
{
} catch (IOException e)
{
}
return null;
}
#Override
protected void onPostExecute(Void result) {
progressDialog.dismiss();
setListAdapter(new tListAdaptor(
ServerResponce.this, R.layout.list_item, tobj));
}
}
private class tListAdaptor extends ArrayAdapter<listobj> {
private ArrayList<listobj> tobj;
public tListAdaptor(Context context,int textViewResourceId,ArrayList<listobj> items)
{
super(context, textViewResourceId, items);
this.tobj = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.list_item, null);
}
listobj o = tobj.get(position);
TextView tt = (TextView) v.findViewById(R.id.toptext);
TextView bt = (TextView) v.findViewById(R.id.bottomtext);
TextView bt1 = (TextView) v.findViewById(R.id.bottomtext1);
TextView bt2 = (TextView) v.findViewById(R.id.bottomtext2);
bt.setText("CAB NAME: " +o.author);
bt1.setText("CAB ID: " +o.cabid);
tt.setText("PRICE: " +o.content);
bt2.setText("CAB RATING: " +o.cabrat);
return v;
}
}
public String getItem(int position) {
// TODO Auto-generated method stub
return null;
}
}
xml file is...
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android= "http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<RelativeLayout xmlns:android= "http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingTop="6dip">
<TextView android:id="#+id/text" android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:singleLine="false"
android:text=" "
android:textStyle="italic"
/>
<Button
android:text="auto book"
android:id="#+id/autobook"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/text"/>
<Button
android:text="cancel"
android:id="#+id/cancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/text"
android:layout_toRightOf="#id/autobook"/>
</RelativeLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1">
<TextView android:id="#+id/toptext" android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:singleLine="true"
android:text=" " />
<TextView android:id="#+id/bottomtext" android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:singleLine="true" />
<TextView android:id="#+id/bottomtext1" android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:singleLine="true"
android:text=" " />
<TextView android:id="#+id/bottomtext2" android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:singleLine="true" />
</LinearLayout>
</LinearLayout>
You can set the header to by a textview. It will still be in the same format as a list view but the top item in the list view will be your text view
Your code is looking for R.id.text1
TextView tv = (TextView)findViewById(R.id.text1);
But your xml does not have any such id.
So you will get a null for tv.

Categories

Resources