Monday, 17 December 2012

API Key

For Facebook ::

 C:\>keytool -exportcert -alias androiddebugkey -keystore "C:\Users\User 24\.andr
oid\debug.keystore" |"C:\Users\User 24\openssl-0.9.8k_WIN32\bin\openssl.exe" sha
1 -binary |"C:\Users\User 24\openssl-0.9.8k_WIN32\bin\openssl.exe" base64
Enter keystore password:  android
13LEnEDLbjogU86xPtNVzSnTHAc=


For Google Map ::


C:\>keytool -list -alias androiddebugkey -keystore "C:\Users\User 24\.android\debug.keystore"
Enter keystore password:

or  keytool -exportcert -alias androiddebugkey -keystore "C:\Users\User 24\.android\debug.keystore" -list -v 

AsyncTask with ProgressBar and Xml parsing using DOM parser

AsynCall.java ::

package com.web;

import java.util.logging.Level;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.w3c.dom.Document;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;

public class Async extends AsyncTask<String, Void, Document> {

public ProgressDialog pDialog;
Context context;
public boolean isRunning = false;
AsyncListener listener;
public boolean isCancelled = false;
String errorMessage;
boolean isError = false;
public String message = "Loading please wait...";
Document doc;
DefaultHttpClient client;
HttpParams httpParameters;

public Async(Context context) {
this.context = context;
pDialog = new ProgressDialog(context);
pDialog.setMessage(message);
pDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {

@Override
public void onCancel(DialogInterface arg0) {
cancel(true);
}
});
client = new DefaultHttpClient(httpParameters);
}

@Override
protected Document doInBackground(String... params) {
try {
pDialog.setCancelable(false);
HttpGet uri = new HttpGet("Your Url.");
httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 4000);
HttpConnectionParams.setSoTimeout(httpParameters, 5000);
client = new DefaultHttpClient(httpParameters);
HttpResponse resp = client.execute(uri);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
doc = db.parse(resp.getEntity().getContent());
return doc;
} catch (Exception e) {
     e.printStack();
return null;
}
}

public void setAsyncListener(AsyncListener listener) {
this.listener = listener;
}

public void setProggressDialogMessage(String msg) {
this.message = msg;
}

@Override
protected void onPostExecute(Document doc) {
pDialog.dismiss();
if (listener != null) {
if (isError) {
listener.onErrorReceived(errorMessage);
} else
listener.onResponseReceived(doc);
}
}

@Override
protected void onPreExecute() {
pDialog.setMessage(message);
showProgressbar();
}

private void showProgressbar() {
if (!isCancelled) {
pDialog.show();
}
}

@Override
protected void onCancelled() {
pDialog.dismiss();
super.onCancelled();
isCancelled = true;
}
}

AsyncListener.java ::


package com.web;
import org.w3c.dom.Document;

public interface AsyncListener {
  public void onResponseReceived(Document doc);
public void onErrorReceived(String str);
}

AsyncActivity.java ::

public class AsyncActivity  extends BaseActivity{
public AsyncCall asyncCall;
private Async async;
@Override
public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
asyncCall = (AsyncCall) getLastNonConfigurationInstance();
  
if (asyncCall == null) {
asyncCall = new AsyncCall(this);
}
async = (Async) getLastNonConfigurationInstance();
if (async == null) {
async = new Async(this);
}
}
  
@Override
public void onResume() {
if(async != null && async.isRunning && async.pDialog != null && !async.pDialog.isShowing()) {
async.pDialog.setMessage(async.message);
async.pDialog.show();
}
else if(async != null && !async.isRunning && async.pDialog.isShowing()) {
async.pDialog.dismiss();
}
if(asyncCall != null && asyncCall.isRunning && asyncCall.pDialog != null && !asyncCall.pDialog.isShowing()) {
asyncCall.pDialog.setMessage(asyncCall.message);
asyncCall.pDialog.show();
}
else if(asyncCall != null && !asyncCall.isRunning && asyncCall.pDialog.isShowing()) {
asyncCall.pDialog.dismiss();
}
super.onResume();
}
    @Override
    protected void onPause() {
    super.onPause();
    }
}

XMLParser :: 


public class XMLParser {

/**
* Getting XML from URL making HTTP request
* @param url string
* */


public String getXmlFromUrl(String url) {
String xml = null;
try {
       DefaultHttpClient httpClient = new DefaultHttpClient();
       HttpPost httpPost = new HttpPost(url);
        HttpResponse httpResponse = httpClient.execute(httpPost);
      HttpEntity httpEntity = httpResponse.getEntity();
      xml = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return xml;
}

/**
* Getting XML DOM element
* @param XML string
* */
public Document getDomElement(String xml){
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
doc = db.parse(is);
} catch (ParserConfigurationException e) {
return null;
} catch (SAXException e) {
return null;
} catch (IOException e) {
return null;
}
return doc;
}
/** Getting node value
* @param elem element
*/
public final String getElementValue( Node elem ) {
Node child;
if( elem != null){
if (elem.hasChildNodes()){
for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
if( child.getNodeType() == Node.TEXT_NODE  ){
return child.getNodeValue();
}
}
}
}
return "";
}
/**
* Getting node value
* @param Element node
* @param key string
* */
public String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return this.getElementValue(n.item(0));
}


// code snipest ::


NodeList nl,statelist;
nl= doc.getElementsByTagName("country");
XMLParser parser = new XMLParser();
// looping through all item nodes <item>
if(nl != null) {
for (int i = 0; i < nl.getLength(); i++) {
Country country_obj = new Country();
Element e = (Element) nl.item(i);

country_obj.c_id = parser.getValue(e, "id");
country_obj.c_name = parser.getValue(e, "c_name");
statelist = e.getElementsByTagName("state");
------------------------------------

}
}

Thursday, 29 November 2012

Android ExpandableListView with multiple CheckBoxes


Hello Android Developers.
              Here I will show you how to create ExpandableListView with multiple checkboxes . I have been trying to use CheckBox Controls But everytime I scrolling or expand the view, CheckBox state has been changed. After trying a lot, I got a solutions, may help you.


Here is code: 

1. activity_expandable_list_view.xml

<LinearLayout        xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"  >
    <ExpandableListView
        android:id="@+id/expandableListView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >
    </ExpandableListView>
</LinearLayout> 


2. ExpandableListViewActivity.java


public class ExpandableListViewActivity extends Activity {

ExpandableListView expandableListview;
ExpandableListViewAdapter adapter;
ArrayList<Category> category_array = new ArrayList<Category>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_expandable_list_view);

// Data
for (int i = 0; i < 10; i++) {
Category category = new Category();
category.category_name = "Category - " + i;
for (int j = 0; j < 2; j++) {
SubCategory subcategory = new SubCategory();
subcategory.subcategory_name =  "  SubCategory - " + j;
subcategory.selected = true;
category.subcategory_array.add(subcategory);
}
category_array.add(category);
}
expandableListview=(ExpandableListView) findViewById(R.id.expandableListView);
adapter = new ExpandableListViewAdapter(ExpandableListViewActivity.this, expandableListview, category_array);
expandableListview.setAdapter(adapter);
 
expandableListview.setOnChildClickListener(new OnChildClickListener() {

@Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
Log.e("Group position :: "+groupPosition, " &&   Child position :: "+childPosition);
if(category_array.get(groupPosition).subcategory_array.get(childPosition).selected) {
category_array.get(groupPosition).subcategory_array.get(childPosition).selected = false;
} else {
category_array.get(groupPosition).subcategory_array.get(childPosition).selected = true;
}
adapter.notifyDataSetChanged();
return true;
}
});
}
}

3. ExpandableListViewAdapter.java


public class ExpandableListViewAdapter extends BaseExpandableListAdapter {
private Context mContext;
private ExpandableListView mExpandableListView;
private List<Category> mGroupCollection;
private int[] groupStatus;
Boolean isActive=false;

public ExpandableListViewAdapter(Context pContext, ExpandableListView pExpandableListView,
List<Category> pGroupCollection) {
mContext = pContext;
mGroupCollection = pGroupCollection;
mExpandableListView = pExpandableListView;
groupStatus = new int[mGroupCollection.size()];
setListEvent();
}
private void setListEvent() {
mExpandableListView.setOnGroupExpandListener(new OnGroupExpandListener() {
@Override
public void onGroupExpand(int arg0) {
groupStatus[arg0] = 1;
}
});
mExpandableListView.setOnGroupCollapseListener(new OnGroupCollapseListener() {
@Override
public void onGroupCollapse(int arg0) {
groupStatus[arg0] = 0;
}
});
}
@Override
public String getChild(int arg0, int arg1) {
return mGroupCollection.get(arg0).subcategory_array.get(arg1).subcategory_name;
}
@Override
public long getChildId(int arg0, int arg1) {
return arg1;
}
@Override
public View getChildView(final int groupPosition, final int childPosition, boolean arg2, View convertView,ViewGroup parent)
{
final ChildHolder childHolder;
if (convertView == null) {
convertView = LayoutInflater.from(mContext).inflate(R.layout.child_row, null);
childHolder = new ChildHolder();
childHolder.checkBox = (ImageView) convertView.findViewById(R.id.checkbox);
childHolder.name=(TextView)convertView.findViewById(R.id.childname);
convertView.setTag(childHolder);
} else {
childHolder = (ChildHolder) convertView.getTag();
}
childHolder.name.setText(mGroupCollection.get(groupPosition).subcategory_array.get(childPosition).subcategory_name);

if(mGroupCollection.get(groupPosition).subcategory_array.get(childPosition).selected) {
childHolder.checkBox.setImageResource(R.drawable.checkbox_selected);
} else {
childHolder.checkBox.setImageResource(R.drawable.checkbox_normal);
}
return convertView;
}
@Override
public int getChildrenCount(int arg0) {
return mGroupCollection.get(arg0).subcategory_array.size();
}
@Override
public Object getGroup(int arg0) {
return mGroupCollection.get(arg0);
}
@Override
public int getGroupCount() {
return mGroupCollection.size();
}
@Override
public long getGroupId(int arg0) {
return arg0;
}
@Override
public View getGroupView(int groupPosition, boolean arg1, View view, ViewGroup parent) {
GroupHolder groupHolder;

if (view == null) {
view = LayoutInflater.from(mContext).inflate(R.layout.group_row,null);
groupHolder = new GroupHolder();
groupHolder.img = (ImageView) view.findViewById(R.id.tab_img);
groupHolder.title = (TextView) view.findViewById(R.id.group_name);
view.setTag(groupHolder);
} else {
groupHolder = (GroupHolder) view.getTag();
}
groupHolder.title.setText(mGroupCollection.get(groupPosition).category_name);
return view;
}
class GroupHolder {
ImageView img;
TextView title;
}
class ChildHolder {
ImageView checkBox;
TextView name;
}
@Override
public boolean hasStableIds() {
return true;
}
@Override
public boolean isChildSelectable(int arg0, int arg1) {
return true;
}
}

There are two Object class for Sample Data :

Category.java 

public class Category {
public String category_name = null;
public ArrayList<SubCategory> subcategory_array = new ArrayList<SubCategory>();
}


SubCategory.java


public class SubCategory {
public String subcategory_name = null;
public boolean selected = false;
}

I hope this will help you.
regards
Roshni.