Thursday, December 26, 2013

XML Parsing using DOM parser in Android

Parsing is the technique to read the value of one object to convert it to another type.

DOM Parser-The Java DOM API comes with the JDK. The DOM(Document Object Model) Parser loads the complete XML content as Tree structure in the memory.
We can traverse(iterate) through the node and nodelist to get the content of the XML.


SAX Parser(Simple API for XML)-It doesn’t load the complete XML into the memory,it parses the XML line by line triggering different events as and when it encounters different elements like: opening tag, closing tag, character data, comments and so on. This is the reason why SAX Parser is called an event based parser.
It's event based which parse XML file step by step so much suitable for large XML Files. SAX XML Parser fires event when it encountered opening tag, element or attribute and the parsing works accordingly. It’s recommended to use SAX XML parser for parsing large xml files in Java because it doesn't require to load whole XML file in Java and it can read a big XML file in small parts.


Difference between SAX and DOM
SAX:
-Parse node by node
-Doesn't store the XML in memory
-We can insert or delete a node.
-SAX is an event based parser.
-SAX is a simple API for XML
-SAX generally runs a little faster than DOM.
DOM:
-Stores the entire XML document into memory before processing.
-Occupies more memory
-We can insert or delete nodes.
-Traverse in any direction.
-DOM is a tree model parser.
-DOM generally runs a little slower than SAX.

Now I am showing one example by using DOM

home.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/appbg"
    android:orientation="vertical" >


        <ListView
            android:id="@id/android:list"
            android:layout_width="fill_parent"
            android:layout_height="300dp"
            android:cacheColorHint="#00000000"
            android:scrollbars="vertical" >
        </ListView>
</LinearLayout>

cat_adapter.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/list_selector"
    android:orientation="horizontal" >
 
<TextView
            android:id="@+id/cat"
            android:layout_width="wrap_content"
            android:layout_height="33dp"
            android:layout_marginLeft="10dp"
            android:text="@string/Subcategories"
            android:textColor="@color/Black"
             android:layout_marginTop="5dp"
            android:textSize="15dp"
            android:textStyle="bold" />

</LinearLayout>

Home.java


public class Home extends ListActivity  {

ListView lv;

ListAdapter adapter;

final ArrayList<HashMap<String, String>> catItems = new ArrayList<HashMap<String, String>>();
public static String URLCAT = "http://www.oxyandroid.com/oxyandroid.php?type=1&cat=220";

static final String KEY_CATEGORY = "Category";
static final String KEY_CATID = "categoryId";
static final String KEY_CATEGORYNAME = "categoryName";

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
new RetreiveFeedTask().execute(URLCAT);
}

public void demo() {
adapter = new SimpleAdapter(this, catItems, R.layout.cat_adapter,
new String[] { KEY_CATEGORYNAME }, new int[] { R.id.cat });

setListAdapter(adapter);

/* If we are not using android list activity then we will use the below code
                   adapter = new SimpleAdapter(this, listSubCat, R.layout.cat_adapter,
new String[] { "subcate" }, new int[] { R.id.cat });

  lv1.setAdapter(adapter);*/

}

class RetreiveFeedTask extends AsyncTask<String, Void, Integer> {

private ProgressDialog dialog1;

protected void onPreExecute() {
dialog1 = ProgressDialog.show(Home.this, "", "Loading...");

}

protected void onPostExecute(Integer feed) {
try {
dialog1.dismiss();
demo();
} catch (Exception e) {
e.printStackTrace();
}
super.onPostExecute(feed);

}

@Override
protected Integer doInBackground(String... arg0) {
// TODO Auto-generated method stub

try {
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URLCAT);
Document doc = parser.getDomElement(xml);
NodeList nl = doc.getElementsByTagName(KEY_CATEGORY);

// 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_CATID, parser.getValue(e, KEY_CATID));
map.put(KEY_CATEGORYNAME,
parser.getValue(e, KEY_CATEGORYNAME));
// adding HashMap to ArrayList

catItems.add(map);
}
} catch (Exception e) {
}
return null;
}

}
}

//////////////////////////////////////////////////////////////////////////
//Using DOM parser
XMLParser.java

public class XMLParser {

// constructor
public XMLParser() {

}

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);
//Log.i("XML Parser", "xml=" + xml);

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

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;
}

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 "";
}

public String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return this.getElementValue(n.item(0));
}
}

Check Network and GPS connectivity in Android

////////////For network connectivity

public class Util {
public static boolean isNetworkAvailable(Activity activity) {
ConnectivityManager connectivity = (ConnectivityManager) activity
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity == null) {
return false;
} else {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
}
return false;
}

}
//////////////////////////////////////////////
//For GPS Connectivity

public class GPSLocation implements LocationListener {
double lat, lng;
LocationManager locationManager;
public Location location = null;
Context contxt;
private String provider;
public boolean isavailable, isgps;

public GPSLocation(Context mcontext) {
this.contxt = mcontext;
locationManager = (LocationManager) contxt
.getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
location = locationManager.getLastKnownLocation(provider);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
0, this);
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
isgps = false;
} else {
isgps = true;
}

}

public double getLatitudeGPS() {
return location.getLatitude();
}

public double getLongitudeGPS() {
return location.getLongitude();
}



public void onLocationChanged(Location arg0) {
if (arg0 != null) {

lat = (arg0.getLatitude());
lng = (arg0.getLongitude());
isavailable = true;
} else {
isavailable = false;
}
}

public void onProviderDisabled(String arg0) {

}

public void onProviderEnabled(String provider) {

}

public void onStatusChanged(String provider, int status, Bundle extras) {

}

}
///////////////////////////////////////////////////////////////////////////////////

/////In your class check

if (Util.isNetworkAvailable(HomeActivity.this)) {
if (!gps.isgps) {
myAlert("Please enable GPS for better performance of this application.");
}
try{
startService(new Intent(this, DownloadDataService.class));
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
updateWithNewLocation(location);

}catch (Exception e) {
e.printStackTrace();
}


//////////////////Find your city

public void updateWithNewLocation(Location location) {
if (location != null) {
lat = location.getLatitude();
lng = location.getLongitude();
}
try {
Geocoder gcd = new Geocoder(HomeActivity.this,
Locale.getDefault());
List<Address> addresses = gcd.getFromLocation(lat, lng, 1);
if (addresses.size() > 0) {

current_city = addresses.get(0).getLocality();
Toast.makeText(getApplicationContext(), current_city,
Toast.LENGTH_LONG).show();

}
} catch (Exception e) {

}

Send request on server using http post in Android

 class AnyntaskToSendData extends AsyncTask<String, Void, Integer> {
ProgressDialog dialog1;

@Override
protected void onPreExecute() {
dialog1 = ProgressDialog.show(TestActivity.this, "",
"Loading...");
super.onPreExecute();
}

@Override
protected void onPostExecute(Integer result) {
dialog1.dismiss();
Intent in = new Intent(TestActivity.this, DestActivity.class);
startActivity(in);
super.onPostExecute(result);
}

@Override
protected Integer doInBackground(String... params) {
//Getting email and mobile from phone
try {
AccountManager am = AccountManager.get(TestActivity.this);
Account[] accounts = am.getAccounts();

for (Account ac : accounts) {
String acname = ac.name;
actype = ac.type;
boolean isEmail = checkEmail(acname);
if (isEmail) {
emailId = acname;
}
if(emailId == null){
emailId = "faiz@gmail.com";
}
// Take your time to look at all available accounts
if (acname.startsWith("91")) {
number = acname;
}
if(number == null){
number = "7411415755";
}

}

} catch (Exception e) {
e.printStackTrace();
}
try{

String storeDataUrl = "http://oxyandroid.blogspot.com/postRequest.php?request_parameter=";
String url1="%7B"+"%22EmailId%22%3A"+"%22"+emailId.trim()+"%22"+"%2C"+"%22MobileNo%22%3A"+"%22"+number.trim()+"%22%7D";
String con_url=convertURL(url1);
System.out.println("con_url====="+con_url);
String freshurl=storeDataUrl.trim()+con_url.trim();
System.out.println("freshurl====="+freshurl);
JSONParser jParser = new JSONParser();

JSONObject json = jParser.getJSONFromUrl(freshurl);
JSONObject webobj = json.getJSONObject("webservice");
boolean status=webobj.getBoolean("system_status");

} catch (JSONException e) {
e.printStackTrace();
}
return null;
}

}
//creating valid url for post
 public static String convertURL(String str) {

   String url = null;
   try{
   url = new String(str.trim().replace(" ", "%20").replace("&", "%26")
           .replace(",", "%2c").replace("(", "%28").replace(")", "%29")
           .replace("!", "%21").replace("=", "%3D").replace("<", "%3C")
           .replace(">", "%3E").replace("#", "%23").replace("$", "%24")
           .replace("'", "%27").replace("*", "%2A").replace("-", "%2D")
           .replace(".", "%2E").replace("/", "%2F").replace(":", "%3A")
           .replace(";", "%3B").replace("?", "%3F").replace("@", "%40")
           .replace("[", "%5B").replace("\\", "%5C").replace("]", "%5D")
           .replace("_", "%5F").replace("`", "%60").replace("{", "%7B")
           .replace("|", "%7C").replace("}", "%7D"));
   }catch(Exception e){
       e.printStackTrace();
   }
   return url;
}
//checking valid email using pattern

public final Pattern EMAIL_ADDRESS_PATTERN = Pattern
.compile("[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" + "\\@"
+ "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" + "(" + "\\."
+ "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" + ")+");

private boolean checkEmail(String email) {
return EMAIL_ADDRESS_PATTERN.matcher(email).matches();
}

////////////////////////////////////JSON Parsor Class////////////////////////////////////////////////////////////////////////////////////////////

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;

}
}

Android Seek Bar

XML File

<SeekBar
                        android:id="@+id/sbfactor"
                        android:layout_width="85dp"
                        android:layout_height="wrap_content"
                        android:layout_marginLeft="0dp"
                        android:max="5"
                        android:progressDrawable="@drawable/bar"

                        android:thumb="@drawable/button_slider" />

Java Code

SeekBar sbTestFactor= (SeekBar) findViewById(R.id.sbfactor);

sbTestFactor.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
int progress = 0;

public void onProgressChanged(SeekBar seekBar, int progresValue,
boolean fromUser) {
progress = progresValue;
}

public void onStartTrackingTouch(SeekBar seekBar) {
}

public void onStopTrackingTouch(SeekBar seekBar) {

rate1 = progress;

LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast,
(ViewGroup) findViewById(R.id.toast_layout));
TextView tv = ((TextView) layout.findViewById(R.id.toast_text_1));
tv.setTypeface(type_regular);
tv.setText("Your Rating Is " + progress);
Toast toast1 = new Toast(getBaseContext());
toast1.setDuration(Toast.LENGTH_SHORT);
toast1.setGravity(Gravity.TOP | Gravity.CENTER, 0, 400);
toast1.setView(layout);
toast1.show();

try {
                                       //set result on textview
tvTestFactor.setText("" + rate1 + "/5");
} catch (Exception e) {
e.printStackTrace();
}

}
});

Android SQLite - Access data from local database where sqlite database kept inside assets folder

public class MyDataBaseHelper extends SQLiteOpenHelper {
private SQLiteDatabase myDataBase;
private final Context myContext;

private static String DB_DIR = "/data/data/com.test/";
private static String DB_NAME = "TestDB.sqlite";
private static String DB_PATH = DB_DIR + DB_NAME;
boolean dbfnd;
Cursor chk;
private String TAG = "Database Helper";

public WineDataHelperNew(Context context) {

super(context, MyDataBaseHelper.DB_NAME, null, 1);
this.myContext = context;
// DB_PATH=myContext.getDatabasePath(DB_NAME).getAbsolutePath();
System.out.println("My DataBase Path: " + DB_PATH);
try {
copyDataBase();
openDataBase();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

public void createDataBase() throws IOException {

Log.e("createDataBase1", "+++++++++++++");
boolean dbExist = checkDataBase();

if (dbExist) {
Log.e("createDataBase2", "++++++ database already exist");
// do nothing - database already exist
} else {

// this.getReadableDatabase();

try {

copyDataBase();

} catch (IOException e) {

throw new Error("Error copying database");

}
}

}

private boolean checkDataBase() {

/*
* //SQLiteDatabase checkDB = null; String myPath = DB_PATH; File dbFile
* = new File(myPath); return dbFile.exists();
*/
SQLiteDatabase checkDB = null;

try {
String myPath = DB_PATH;
checkDB = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);

} catch (SQLiteException e) {
// database does't exist yet.
}
if (checkDB != null) {
checkDB.close();
}

return checkDB != null ? true : false;

}

private void copyDataBase() throws IOException {

// Open your local db as the input stream
InputStream myInput = myContext.getAssets().open(DB_NAME);

// Path to the just created empty db
String outFileName = DB_PATH;

// Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);

// transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
// Close the streams
myOutput.flush();
myOutput.close();
myInput.close();

}

public static void copyFile(InputStream fromFile, OutputStream toFile)
throws IOException {
// transfer bytes from the inputfile to the outputfile
System.out.println("In copying.....");
byte[] buffer = new byte[1024];
int length;

try {
while ((length = fromFile.read(buffer)) > 0) {
toFile.write(buffer, 0, length);
System.out.println("Reading & writing the file....");
}
} catch (Exception e) {
System.out.println("Error in copy1 file :" + e.toString());
}
// Close the streams
finally {
try {
if (toFile != null) {
try {
toFile.flush();
} finally {
toFile.close();
}
}
} catch (Exception e) {
System.out.println("Error in copy2 file :" + e.toString());
} finally {
if (fromFile != null) {
fromFile.close();
System.out.println("File copied successfully.....");
}
}
}
}

public static void copyFile(String fromFile, String toFile)
throws IOException {
copyFile(new FileInputStream(fromFile), new FileOutputStream(toFile));
}

// Open the database
public void openDataBase() {

String myPath = DB_PATH;
try {

myDataBase = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);
System.out.println(myDataBase.toString()
+ " Database found....................!!!!!!!");
dbfnd = true;
} catch (Exception e) {
System.out.println("Database not found....................!!!!!!!");
// TODO: handle exception
dbfnd = false;
}
}

public SQLiteDatabase getReadableDatabase() {
myDataBase = SQLiteDatabase.openDatabase(DB_PATH, null,

SQLiteDatabase.OPEN_READONLY);
return myDataBase;
}

public SQLiteDatabase getWritableDatabase() {
myDataBase = SQLiteDatabase.openDatabase(DB_PATH, null,

SQLiteDatabase.OPEN_READWRITE);

return myDataBase;
}

@Override
public synchronized void close() {

if (myDataBase != null)
myDataBase.close();
super.close();

}

@Override
public void onCreate(SQLiteDatabase db) {

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}

public Cursor get_Data() {
chk = null;

try {
System.out.println("select Distinct Bang from city");
chk = myDataBase.rawQuery(
"select Distinct Bangalore from city", null);

} catch (Exception e) {
Log.e(TAG, "Error in city_table");
e.printStackTrace();
return null;
}
return chk;

}

public Cursor get_Brand(String selBrand) {
// TODO Auto-generated method stub
chk = null;

try {
System.out
.println("select brand from city where Bangalore='"
+ selBrand + "'");
chk = myDataBase.rawQuery(
"select OvalBar from city where Bangalore='"
+ selBrand + "'", null);

} catch (Exception e) {
Log.e(TAG, "Error in brands_table");
e.printStackTrace();
return null;
}
return chk;
}

public Cursor get_Brand() {
chk = null;

try {
System.out.println("select Distinct brand_type from brand");
chk = myDataBase.rawQuery(
"select Distinct alcohol_type from brand", null);

} catch (Exception e) {
Log.e(TAG, "Error in brand");
e.printStackTrace();
return null;
}
return chk;

}

public Cursor get_SuperBrand(String selType) {
// TODO Auto-generated method stub
chk = null;

try {
System.out
.println("select brand_name from brand where type='"
+ selSuperType + "'");
chk = myDataBase.rawQuery(
"select brand_name from brand_alcohol where type='"
+ selType + "'", null);

} catch (Exception e) {
Log.e(TAG, "Error in brand");
e.printStackTrace();
return null;
}
return chk;
}

}