Umesh

Untitled Document

Monday, 1 April 2013

android.os.NetworkOnMainThreadException or Unable to load Images From Twitter on android 4.0 Emulator or Device


Hello guys, after spending whole day, I got nice solution for my own  problem. Actualy I am feeding twitter data in my android application.  I am parsing user_name, created_at(means tweet time) and profile image url. When I parse these from twitter JSON, all data will shown in my listview properly. These is no any problem with my android 2.2,2.3.. emulator and device, but when I run this same code for my android 4.0 or up emulator and device , Image does not loads.


But finally I got my solution : Please fallow steps to resolve your problem..

Write below code into your Main Activity where your are showing listview just below

setContentView(R.layout.main_activity);

code:

if (android.os.Build.VERSION.SDK_INT > 9)
 {
     StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
     StrictMode.setThreadPolicy(policy);
 }

The above if condition is execute if your device api version is > 9 and if your device api version is less than 9 then your code is completely work without any error. Now my code works fine with all v ersion of devices properly.

And import below statement into your activity

import android.os.StrictMode

Friday, 22 March 2013

Finishes all the intents in stack which are on the top of any other activity


Let suppose if you want to log-out from last activity and come on to front activity. It removes all intents from stack which are on the top of front activity. It's nice search for me.This is the nice code. It finishes all the activities which are on the top of MagicMap--By Umesh


Intent intent = new Intent(getApplicationContext(), MagicMap.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);

Thursday, 21 March 2013

Design your own check box in android


Hello guys, if you want to design your own check box for your android app then just go through fallowing steps : 


 Step 1 : Add these four images in your drawable folder 


checkbox_on_background_focus_yellow.png

checkbox_off_background.png

checkbox_on_background.png

checkbox_off_background_focus_yellow.png



Step 2 : Also add following chk.xml in your drawable folder 


chk.xml : 


<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/checkbox_on_background_focus_yellow" android:state_checked="true" android:state_focused="true"/>
    <item android:drawable="@drawable/checkbox_off_background_focus_yellow" android:state_checked="false" android:state_focused="true"/>
    <item android:drawable="@drawable/checkbox_off_background" android:state_checked="false"/>
    <item android:drawable="@drawable/checkbox_on_background" android:state_checked="true"/>

</selector>


Step 3 : write following code in check box property in your main layout 


android:background="@drawable/chk"


Selector for different button states in android


Change button on focus, on-clicked and active mode. Here is a simple and nice code. Add three different buttons of same size in your drawable folder. There is no need to code in your java file.


File : res/drawable/new_button.xml


<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/button_pressed_yellow"
android:state_pressed="true" />
<item android:drawable="@drawable/button_focused_orange"
android:state_focused="true" />
<item android:drawable="@drawable/button_normal_green" />
</selector>

File : res/layout/main.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="fill_parent"
android:orientation="vertical" >

<Button
android:id="@+id/imageButtonSelector"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/new_button" />

</LinearLayout>


Android : XMLParser class to parse xml online with example


Step 1 : Hello guys, here is simple XMLParser class which is used to parse almost all xml files. Just keep this file in your project and pass xml url in it.

XMLParser.java :


package com.umesh.xmlparsing;

import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import android.util.Log;

public class XMLParser {

// constructor
 public XMLParser() {
 }

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

 public String getXmlFromUrl(String url) {
  String xml = null;
  try {
   // defaultHttpClient
   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
  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) {
    Log.e("Error: ", e.getMessage());
    return null;
   } catch (SAXException e) {
    Log.e("Error: ", e.getMessage());
             return null;
   } catch (IOException e) {
    Log.e("Error: ", e.getMessage());
    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));
  }
}

Step 2 :This will be any class to parse xml.

AndroidXMLParsingActivity.java


package com.umesh.xmlparsing;

import java.util.ArrayList;
import java.util.HashMap;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class AndroidXMLParsingActivity extends ListActivity {

 // All static variables
 static final String URL = "http://api.androidhive.info/pizza/?format=xml";

 // XML node keys
 static final String KEY_ITEM = "item"; // parent node
 static final String KEY_ID = "id";
 static final String KEY_NAME = "name";
 static final String KEY_COST = "cost";
 static final String KEY_DESC = "description";

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);  //we can comment this line, because we are extending ListActivity

  ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
  XMLParser parser = new XMLParser();
  String xml = parser.getXmlFromUrl(URL); // getting XML
  Document doc = parser.getDomElement(xml); // getting DOM element
  NodeList nl = doc.getElementsByTagName(KEY_ITEM);
  // looping through all item nodes <item>
  for (int i = 0; i < nl.getLength(); i++) {
   // creating new HashMap
   HashMap<String, String> map = new HashMap<String, String>();
   Element e = (Element) nl.item(i);
   // adding each child node to HashMap key => value
   map.put(KEY_ID, parser.getValue(e, KEY_ID));
   map.put(KEY_NAME, parser.getValue(e, KEY_NAME));
   map.put(KEY_COST, "Rs." + parser.getValue(e, KEY_COST));
   map.put(KEY_DESC, parser.getValue(e, KEY_DESC));
   // adding HashList to ArrayList
   menuItems.add(map);
  }
  // Adding menuItems to ListView
  ListAdapter adapter = new SimpleAdapter(this, menuItems,
    R.layout.list_item,
    new String[] { KEY_NAME, KEY_DESC, KEY_COST }, new int[] {
      R.id.name, R.id.desciption, R.id.cost });
  setListAdapter(adapter);
 }
}

In the above code, the line setContentView(R.layout.main) is no longer needed, because we are extends activiy as ListActivity.

Step 3 : Here is simple list_item.xml file.

list_item.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="wrap_content"
    android:orientation="horizontal"> 
    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
  <!-- Name Label -->
        <TextView
            android:id="@+id/name"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:textColor="#dc6800"
            android:textSize="16sp"
            android:textStyle="bold"
            android:paddingTop="6dip"
            android:paddingBottom="2dip" />
  <!-- Description label -->
        <TextView
            android:id="@+id/desciption"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:textColor="#acacac"
            android:paddingBottom="2dip">
        </TextView>
        <!-- Linear layout for cost and price Cost: Rs.100 -->
        <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <!-- Cost Label -->
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#5d5d5d"
            android:gravity="left"
            android:textStyle="bold"
            android:text="Cost: " >
        </TextView>
        <!-- Price Label -->
        <TextView
            android:id="@+id/cost"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#acacac"
            android:textStyle="bold"
            android:gravity="left">
        </TextView>
        </LinearLayout>
    </LinearLayout>
</LinearLayout>

Android : JSONParser class with simple JSON parsing example


Step 1  : Simple JSON format :


{

  "contacts": [
        {
                "id": "c200",
                "name": "Ravi Tamada",
                "email": "
umesh@gmail.com",
                "address": "xx-xx-xxxx,x - street, x - country",
                "gender" : "male",
                "phone": {
                    "mobile": "+91 0000000000",
                    "home": "00 000000",
                    "office": "00 000000"
                }
        },
        {
                "id": "c201",
                "name": "Johnny Depp",
                "email": "
suryawanshi@gmail.com",
                "address": "xx-xx-xxxx,x - street, x - country",
                "gender" : "male",
                "phone": {
                    "mobile": "+91 0000000000",
                    "home": "00 000000",
                    "office": "00 000000"
                }
        },

/
/
/
/
so on...


Step 2 : Hello guys, this is comman JSONParser class.  Use this code and parse any    JSON.  Just put this java file in your package.



package com.umesh.jsonparse;import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    public JSONObject getJSONFromUrl(String url) {

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();          

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String        return jObj;

    }
}




Step 3 : This is simple  class which parse JSON and show values in listiview.


Main.java :

import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.Bundle;
import android.app.Activity;
import android.app.ListActivity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.Menu;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class Main extends ListActivity {
 private static String url="http://api.androidhive.info/contacts/";
 ArrayList<HashMap<String, String>> contactList;
 JSONArray contacts=null;

 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);

  //setContentView(R.layout.main);

  contactList=new ArrayList<HashMap<String,String>>();
  JSONParser jparse=new JSONParser();
  JSONObject jobject=jparse.getJSONFromUrl(url);

  try
  {
   contacts=jobject.getJSONArray("contacts");
 
   for(int i=0;i<contacts.length();i++)
   {
    HashMap<String,String> map=new HashMap<String, String>();
  
    JSONObject c=contacts.getJSONObject(i);
  
    map.put("id",c.getString("id"));
    map.put("name",c.getString("name"));
    map.put("email",c.getString("email"));
  
    JSONObject phone=c.getJSONObject("phone");
    map.put("phone",phone.getString("mobile"));
    contactList.add(map);
  
  
   }
  }
  catch(Exception e)
  {
   e.printStackTrace();
  }

  ListAdapter adapter=new SimpleAdapter(this,contactList,R.layout.listitems,new String[]{"name","email","phone"},new int []{R.id.tv_name,R.id.tv_email,R.id.tv_mobile});
  setListAdapter(adapter);

 }
}


Step 4 : As we are extending ListActivity, no need to use main layout with list view. Just define listitems. Following is the simple listitem layout




listitems.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="match_parent"
    tools:context=".Main" >
    <TextView
        android:id="@+id/tv_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Name"
        android:textSize="16dp"
        android:textAppearance="?android:attr/textAppearanceLarge" />
    <TextView
        android:id="@+id/tv_email"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/tv_name"
        android:text="email id"
        android:textSize="14dp"
        android:textAppearance="?android:attr/textAppearanceMedium" />
    <TextView
        android:id="@+id/tv_mobile"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/tv_email"
        android:text="Mobile : "
        android:textSize="14dp"
        android:textAppearance="?android:attr/textAppearanceMedium" />
    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/tv_mobile"
        android:src="@drawable/ic_launcher" />
</RelativeLayout>

 


Friday, 15 March 2013

Get MD5 fingerprint from Java's keytool, not only SHA-1?


With JDK 1.7 installed, keytool always outputs by default SHA1 fingerprint, not MD5. You can get the MD5 Certificate by adding -v option.


use the following code :-

1.  keytool -v -list -alias androiddebugkey -keystore debug.keystore -storepass android -keypass android

or you can simply use following short command also. It will also outputs same Certificate

2. keytool -v -list -keystore debug.keystore

It will output MD5 Certificate as well.