Wednesday 30 October 2013

pinned listview in android with onclick listener

activity_main.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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

   <com.hb.views.PinnedSectionListView android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:id="@+id/lll"></com.hb.views.PinnedSectionListView>

</RelativeLayout>

MainActivity.java
package com.example.pinnedlistview;

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

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.hb.views.PinnedSectionListView;
import com.hb.views.PinnedSectionListView.PinnedSectionListAdapter;

public class MainActivity extends Activity {
 
 PinnedSectionListView lv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        lv = (PinnedSectionListView)findViewById(R.id.lll);
        
        lv.setAdapter(new MyPinnedSectionListAdapter(this, android.R.layout.simple_list_item_1, android.R.id.text1, prepareItems()));
        
        lv.setOnItemClickListener(new OnItemClickListener() {

   @Override
   public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
     long arg3) {
    
    Toast.makeText(MainActivity.this,"POsition : "+arg2,Toast.LENGTH_SHORT).show();
    
    
   }
  });
        
        
    }


 private static class MyPinnedSectionListAdapter extends ArrayAdapter<Item> implements PinnedSectionListAdapter {
  
  private static final int[] COLORS = new int[] {
   android.R.color.holo_green_light, android.R.color.holo_orange_light,
   android.R.color.holo_blue_light, android.R.color.holo_red_light };
  
  public MyPinnedSectionListAdapter(Context context, int resource, int textViewResourceId, List<Item> objects) {
   super(context, resource, textViewResourceId, objects);
  }
  
  @Override public View getView(int position, View convertView, ViewGroup parent) {
   TextView view = (TextView) super.getView(position, convertView, parent);
   view.setTextColor(Color.DKGRAY);
   if (getItem(position).type == Item.SECTION) {
    view.setBackgroundColor(parent.getResources().getColor(COLORS[position % COLORS.length]));
   }
   return view;
  }
  
  @Override public int getViewTypeCount() {
   return 2;
  }
  
  @Override public int getItemViewType(int position) {
   return getItem(position).type;
  }

  @Override public boolean isItemViewTypePinned(int viewType) {
   return viewType == Item.SECTION;
  }
 }
 private static class Item {
  public static final int ITEM = 0;
  public static final int SECTION = 1;
  
  public final int type;
  public final String text;
  
  public Item(int type, String text) {
   this.type = type;
   this.text = text;
  }
  
  @Override public String toString() {
   return text;
  }
 }
 
 private static ArrayList<Item> prepareItems() {
  ArrayList<Item> result = new ArrayList<Item>();
  for (int i = 0; i < 30; i++) {
   result.add(new Item(Item.SECTION, "Section " + i));
   for (int j=0; j<4; j++) {
    result.add(new Item(Item.ITEM, "Item " + j));
   }
  }
  return result;
 }
 
    
}
note: must use library for that demo code ok for above logic .
you can download library code for below link. https://github.com/beworker/pinned-section-listview

Easy to use ListView with pinned sections for Android.

iphone style  pinned sections for Android.

here is link

https://github.com/beworker/pinned-section-listview

Tuesday 22 October 2013

tab host back stack (back button)

Don't handle KeyEvent.KEYCODE_BACK in your tab activitys, do it in your main TabActivity.
As long as your tab activitys onKeyDown() methods don't handle it but they do callsuper.onKeyDown(keyCode, event); it will filter up to your TabActivity.
In your TabActivity have a member int currentTab = 0 then in the TabActivity do this...




@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        if (currentTab == 0)
            currentTab = 2;
        else
            currentTab--;
        tabHost.setCurrentTab(currentTab);
        return true;
    }
    else
        return super.onKeyDown(keyCode, event); 
}

Android Fragment back stack or tab host back stack

First of all, dont use replace() but instead use remove and add separately. It seems as though replace() doesnt work properly.
The next part to this is overriding the onKeyDown method and remove the current fragment every time the back button is pressed.



@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
    if (keyCode == KeyEvent.KEYCODE_BACK)
    {
        if (getSupportFragmentManager().getBackStackEntryCount() == 0)
        {
            this.finish();
            return false;
        }
        else
        {
            getSupportFragmentManager().popBackStack();
            removeCurrentFragment();

            return false;
        }



    }

    return super.onKeyDown(keyCode, event);
}


public void removeCurrentFragment()
{
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

    Fragment currentFrag =  getSupportFragmentManager().findFragmentById(R.id.detailFragment);


    String fragName = "NONE";

    if (currentFrag!=null)
        fragName = currentFrag.getClass().getSimpleName();


    if (currentFrag != null)
        transaction.remove(currentFrag);

    transaction.commit();

}

Thursday 17 October 2013

get location data logic from json

logic code
please run in AsyncTask  doinbackground method



JSONArray locationsobject = json.getJSONArray("locations");
String latitude = "";
String longitude = "";
String city = "";
String state = "";
String country = "";
String id = "";
String street = "";
String zip = "";

for (int i = 0; i < locationsobject.length(); i++) {
JSONObject i_Loc = locationsobject.getJSONObject(i);
System.out.println("location object:" + i_Loc);

try {
latitude = i_Loc.getString("latitude");
System.out.println("latitude :" + latitude);
} catch (Exception e) {

e.printStackTrace();
}
try {
longitude = i_Loc.getString("longitude");
System.out.println("longitude :" + longitude);
} catch (Exception e) {

e.printStackTrace();
}
try {
city = i_Loc.getString("city");
System.out.println("city name :" + city);
} catch (Exception e) {

e.printStackTrace();
}
try {
state = i_Loc.getString("state");
System.out.println("state :" + state);
} catch (Exception e) {

e.printStackTrace();
}
try {
country = i_Loc.getString("country");
System.out.println("country :" + country);
} catch (Exception e) {

e.printStackTrace();
}
try {
id = i_Loc.getString("id");
System.out.println("id :" + id);
} catch (Exception e) {

e.printStackTrace();
}

try {
street = i_Loc.getString("street");
System.out.println("street :" + street);
} catch (Exception e) {

e.printStackTrace();
}
try {
zip = i_Loc.getString("zip");
System.out.println("zip :" + zip);
} catch (Exception e) {

e.printStackTrace();
}
}

get location and event data from json url

mainActivity

package com.example.androidpractice;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Iterator;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;

public class MainActivity extends Activity {
 ArrayList<DateBean> sortArray = new ArrayList<DateBean>();

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  new FetchData().execute();
 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.main, menu);
  return true;
 }

 class FetchData extends AsyncTask<Void, Void, Void> {

  @Override
  protected void onPreExecute() {
   // TODO Auto-generated method stub
   super.onPreExecute();
  }

  @Override
  protected Void doInBackground(Void... params) {
   // Creating JSON Parser instance
   JSONParser jParser = new JSONParser();

   // getting JSON string from URL

   JSONObject json = jParser.getJSONFromUrl("your link");
   try {
    JSONObject eventobject = json.getJSONObject("events");

    Iterator<Object> keys = eventobject.keys();

    while (keys.hasNext()) {

     String datestring = String.valueOf(keys.next());

     // by below logic you skip missed date.
     if (datestring.trim().length() > 0) {
      SimpleDateFormat formatter = new SimpleDateFormat(
        "yyyy-MM-dd");
      Date date = formatter.parse(datestring);
      DateBean dateBean = new DateBean(date);
      sortArray.add(dateBean);
     } else {

     }
     // JSONArray jsonArray =
     // eventobject.getJSONArray(datestring);
     // System.out.println(" --"+jsonArray);
    }

    System.out.println("size:" + sortArray.size());

    System.out.println("==========sorting array======");
    Collections.sort(sortArray, new CompareDate());
    // reverse order
    // Collections.reverse(sortArray);

    for (DateBean d : sortArray) {
     String dateKey = new SimpleDateFormat("yyyy-MM-dd")
       .format(d.getDate());
     System.out.println(dateKey);

     JSONArray jsonArray = eventobject.getJSONArray(dateKey);
     System.out.println(" --" + jsonArray);

    }

    // fetching location data
    JSONArray locationsobject = json.getJSONArray("locations");
    String latitude = "";
    String longitude = "";
    String city = "";
    String state = "";
    String country = "";
    String id = "";
    String street = "";
    String zip = "";

    for (int i = 0; i < locationsobject.length(); i++) {
     JSONObject i_Loc = locationsobject.getJSONObject(i);
     System.out.println("location object:" + i_Loc);

     try {
      latitude = i_Loc.getString("latitude");
      System.out.println("latitude :" + latitude);
     } catch (Exception e) {

      e.printStackTrace();
     }
     try {
      longitude = i_Loc.getString("longitude");
      System.out.println("longitude :" + longitude);
     } catch (Exception e) {

      e.printStackTrace();
     }
     try {
      city = i_Loc.getString("city");
      System.out.println("city name :" + city);
     } catch (Exception e) {

      e.printStackTrace();
     }
     try {
      state = i_Loc.getString("state");
      System.out.println("state :" + state);
     } catch (Exception e) {

      e.printStackTrace();
     }
     try {
      country = i_Loc.getString("country");
      System.out.println("country :" + country);
     } catch (Exception e) {

      e.printStackTrace();
     }
     try {
      id = i_Loc.getString("id");
      System.out.println("id :" + id);
     } catch (Exception e) {

      e.printStackTrace();
     }

     try {
      street = i_Loc.getString("street");
      System.out.println("street :" + street);
     } catch (Exception e) {

      e.printStackTrace();
     }
     try {
      zip = i_Loc.getString("zip");
      System.out.println("zip :" + zip);
     } catch (Exception e) {

      e.printStackTrace();
     }
    }
   } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
   return null;
  }

  @Override
  protected void onPostExecute(Void result) {
   super.onPostExecute(result);

  }

  class CompareDate implements Comparator<DateBean> {

   @Override
   public int compare(DateBean d1, DateBean d2) {

    return d1.getDate().compareTo(d2.getDate());
   }

  }

 }

}