Saturday, June 21, 2014

WHEATHER INFO EXAMPLE / XML PARSER EXAMPLE

DOWNLOAD THE WEATHER INFO APP HERE



EXAMPLE-
MainActivity.java-
package com.example.xmlparser;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
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 android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;

public class MainActivity extends Activity {

   private String url1 = "http://api.openweathermap.org/data/2.5/weather?q=";
   private String url2 = "&mode=xml";
   private EditText location,country,temperature,humidity,pressure;
   private HandleXML obj;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      location = (EditText)findViewById(R.id.editText1);
      country = (EditText)findViewById(R.id.editText2);
      temperature = (EditText)findViewById(R.id.editText3);
      humidity = (EditText)findViewById(R.id.editText4);
      pressure = (EditText)findViewById(R.id.editText5);
   }

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

   public void open(View view){
      String url = location.getText().toString();
      String finalUrl = url1 + url + url2;
      country.setText(finalUrl);
      obj = new HandleXML(finalUrl);
      obj.fetchXML();
      while(obj.parsingComplete);
      country.setText(obj.getCountry());
      temperature.setText(obj.getTemperature());
      humidity.setText(obj.getHumidity());
      pressure.setText(obj.getPressure());

   }

}
 HandleXML.java-
package com.example.xmlparser;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

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.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;


public class HandleXML {

   private String country = "county";
   private String temperature = "temperature";
   private String humidity = "humidity";
   private String pressure = "pressure";
   private String urlString = null;
   private XmlPullParserFactory xmlFactoryObject;
   public volatile boolean parsingComplete = true;
   public HandleXML(String url){
      this.urlString = url;
   }
   public String getCountry(){
      return country;
   }
   public String getTemperature(){
      return temperature;
   }
   public String getHumidity(){
      return humidity;
   }
   public String getPressure(){
      return pressure;
   }

   public void parseXMLAndStoreIt(XmlPullParser myParser) {
      int event;
      String text=null;
      try {
         event = myParser.getEventType();
         while (event != XmlPullParser.END_DOCUMENT) {
            String name=myParser.getName();
            switch (event){
               case XmlPullParser.START_TAG:
               break;
               case XmlPullParser.TEXT:
               text = myParser.getText();
               break;

               case XmlPullParser.END_TAG:
                  if(name.equals("country")){
                     country = text;
                  }
                  else if(name.equals("humidity")){  
                     humidity = myParser.getAttributeValue(null,"value");
                  }
                  else if(name.equals("pressure")){
                     pressure = myParser.getAttributeValue(null,"value");
                  }
                  else if(name.equals("temperature")){
                     temperature = myParser.getAttributeValue(null,"value");
                  }
                  else{
                  }
                  break;
                  }   
                  event = myParser.next(); 

              }
                 parsingComplete = false;
      } catch (Exception e) {
         e.printStackTrace();
      }

   }
   public void fetchXML(){
      Thread thread = new Thread(new Runnable(){
         @Override
         public void run() {
            try {
               URL url = new URL(urlString);
               HttpURLConnection conn = (HttpURLConnection) 
               url.openConnection();
                  conn.setReadTimeout(10000 /* milliseconds */);
                  conn.setConnectTimeout(15000 /* milliseconds */);
                  conn.setRequestMethod("GET");
                  conn.setDoInput(true);
                  conn.connect();
            InputStream stream = conn.getInputStream();

            xmlFactoryObject = XmlPullParserFactory.newInstance();
            XmlPullParser myparser = xmlFactoryObject.newPullParser();

            myparser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES
            , false);
            myparser.setInput(stream, null);
            parseXMLAndStoreIt(myparser);
            stream.close();
            } catch (Exception e) {
               e.printStackTrace();
            }
        }
    });

    thread.start(); 


   }

}

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

   <TextView
      android:id="@+id/textView1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignParentLeft="true"
      android:layout_alignParentTop="true"
      android:layout_marginTop="15dp"
      android:text="@string/location"
      android:textAppearance="?android:attr/textAppearanceMedium" />

   <EditText
      android:id="@+id/editText1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignBottom="@+id/textView1"
      android:layout_alignParentRight="true"
      android:ems="10" />

   <TextView
      android:id="@+id/textView2"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignLeft="@+id/textView1"
      android:layout_below="@+id/textView1"
      android:layout_marginTop="68dp"
      android:text="@string/country"
      android:textAppearance="?android:attr/textAppearanceSmall" />

   <TextView
      android:id="@+id/textView3"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_below="@+id/textView2"
      android:layout_marginTop="19dp"
      android:text="@string/temperature"
      android:textAppearance="?android:attr/textAppearanceSmall" />

   <TextView
      android:id="@+id/textView4"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignLeft="@+id/textView3"
      android:layout_below="@+id/textView3"
      android:layout_marginTop="32dp"
      android:text="@string/humidity"
      android:textAppearance="?android:attr/textAppearanceSmall" />

   <TextView
      android:id="@+id/textView5"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignLeft="@+id/textView4"
      android:layout_below="@+id/textView4"
      android:layout_marginTop="21dp"
      android:text="@string/pressure"
      android:textAppearance="?android:attr/textAppearanceSmall" />

   <EditText
      android:id="@+id/editText2"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_above="@+id/textView3"
      android:layout_toRightOf="@+id/textView3"
      android:ems="10" >

      <requestFocus />
   </EditText>

   <EditText
      android:id="@+id/editText3"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignBaseline="@+id/textView3"
      android:layout_alignBottom="@+id/textView3"
      android:layout_alignLeft="@+id/editText2"
      android:ems="10" />

   <EditText
      android:id="@+id/editText4"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_above="@+id/textView5"
      android:layout_alignLeft="@+id/editText1"
      android:ems="10" />

   <EditText
      android:id="@+id/editText5"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignBaseline="@+id/textView5"
      android:layout_alignBottom="@+id/textView5"
      android:layout_alignRight="@+id/editText4"
      android:ems="10" />

   <Button
      android:id="@+id/button1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignLeft="@+id/editText2"
      android:layout_below="@+id/editText1"
      android:onClick="open"
      android:text="@string/weather" />

</RelativeLayout>
 
 STRINGS-
<?xml version="1.0" encoding="utf-8"?>
<resources>

   <string name="app_name">XMLParser</string>
   <string name="action_settings">Settings</string>
   <string name="hello_world">Hello world!</string>
   <string name="location">Location</string>
   <string name="country">Country:</string>
   <string name="temperature">Temperature:</string>
   <string name="humidity">Humidity:</string>
   <string name="pressure">Pressure:</string>
   <string name="weather">Weather</string>
</resources> 
 
 
 

ANDROID WIDGET EXAMPLE

WELL...A widget is a small gadget or control of your android application placed on the home screen. Widgets can be very handy as they allow you to put your favourite applications on your homescreen in order to quickly access them. You have probably seen some common widgets , such as music widget , weather widget , clock widget e.t.c

YOUR XML FILE SHOULD BE LIKE THIS-
<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:gravity="top"
   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" >

   <TextView
      android:id="@+id/textView1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignParentLeft="true"
      android:layout_alignParentTop="true"
      android:text="@string/website"
      android:textAppearance="?android:attr/textAppearanceMedium" />

   <Button
      android:id="@+id/button1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignLeft="@+id/textView1"
      android:layout_below="@+id/textView1"
      android:layout_marginLeft="18dp"
      android:text="@string/app_name" />

</RelativeLayout>
 
YOUR MAIN ACTIVITY FILE SHOULD BE LIKE THIS-
package com.example.widget;

import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.webkit.WebView.FindListener;
import android.widget.Button;
import android.widget.RemoteViews;
import android.widget.Toast;

public class MainActivity extends AppWidgetProvider{

   @Override
   public void onUpdate(Context context, AppWidgetManager appWidgetManager,
   int[] appWidgetIds) {
      for(int i=0; i<appWidgetIds.length; i++){
      int currentWidgetId = appWidgetIds[i];
      String url = "http://ultra-android-dev.blogspot.com";
      Intent intent = new Intent(Intent.ACTION_VIEW);
      intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
      intent.setData(Uri.parse(url));
      PendingIntent pending = PendingIntent.getActivity(context, 0,
      intent, 0);
      RemoteViews views = new RemoteViews(context.getPackageName(),
      R.layout.activity_main);
      views.setOnClickPendingIntent(R.id.button1, pending);
      appWidgetManager.updateAppWidget(currentWidgetId,views);
      Toast.makeText(context, "widget added", Toast.LENGTH_SHORT).show(); 
      }
   } 
}  
 PLACE THE PERMISSION 
<uses-permission android:name="android.permission.INTERNET"/>

Wednesday, June 18, 2014

Access JSTL variable define in a jsp inside AJAX call

 Access JSTL variable define in a jsp inside AJAX call

JSP file where It is defined JSTL variable like this (form value) :
<c:set var="idEtape" value="${etapeForm.etape.idEtape}" scope="page"/>
<c:set var="idContact" value="${etapeForm.etape.idContact}" scope="page"/>
<c:set var="numeroDossierFoa" value="${etapeForm.dossier.numeroDossier}" scope="page"/>
<script type="text/javascript" src=myfile.js"/>"></script>
  EL expression to access this variable like below :
var request = $.ajax({type: "POST",
    url: "/myUrl/" + '${numeroDossier}' + "/" + '${idContact}' + "/" + '${idEtape}',
    cache: false
    });
 


JSON in Android

JSON in Android
 

JSON is a very condense data exchange format. See JSON tutorial for details. The Android platform includes the json.org libraries which allow to work easily with JSON files.
The Parts
A fan object with email as a key and foo@bar.com as a value
{
  fan:
    {
      email : 'foo@bar.com'
    }
}
So the object equivalent would be fan.email; or fan['email'];. Both would have the same value of 'foo@bar.com'.

About HttpClient Request

The following is what our author used to make a HttpClient Request. I do not claim to be an expert at all this so if anyone has a better way to word some of the terminology feel free.
public static HttpResponse makeRequest(String path, Map params) throws Exception 
{
    //instantiates httpclient to make request
    DefaultHttpClient httpclient = new DefaultHttpClient();

    //url with the post data
    HttpPost httpost = new HttpPost(path);

    //convert parameters into JSON object
    JSONObject holder = getJsonObjectFromMap(params);

    //passes the results to a string builder/entity
    StringEntity se = new StringEntity(holder.toString());

    //sets the post request as the resulting string
    httpost.setEntity(se);
    //sets a request header so the page receving the request
    //will know what to do with it
    httpost.setHeader("Accept", "application/json");
    httpost.setHeader("Content-type", "application/json");

    //Handles what is returned from the page 
    ResponseHandler responseHandler = new BasicResponseHandler();
    return httpclient.execute(httpost, responseHandler);
}

Map

If you are not familiar with the Map data structure please take a look at the Java Map reference. In short, a map is similar to a dictionary or a hash.
private static JSONObject getJsonObjectFromMap(Map params) throws JSONException {

    //all the passed parameters from the post request
    //iterator used to loop through all the parameters
    //passed in the post request
    Iterator iter = params.entrySet().iterator();

    //Stores JSON
    JSONObject holder = new JSONObject();

    //using the earlier example your first entry would get email
    //and the inner while would get the value which would be 'foo@bar.com' 
    //{ fan: { email : 'foo@bar.com' } }

    //While there is another entry
    while (iter.hasNext()) 
    {
        //gets an entry in the params
        Map.Entry pairs = (Map.Entry)iter.next();

        //creates a key for Map
        String key = (String)pairs.getKey();

        //Create a new map
        Map m = (Map)pairs.getValue();   

        //object for storing Json
        JSONObject data = new JSONObject();

        //gets the value
        Iterator iter2 = m.entrySet().iterator();
        while (iter2.hasNext()) 
        {
            Map.Entry pairs2 = (Map.Entry)iter2.next();
            data.put((String)pairs2.getKey(), (String)pairs2.getValue());
        }

        //puts email and 'foo@bar.com'  together in map
        holder.put(key, data);
    }
    return holder;
}
view the JSON AND ANDROID in vogella.com here 

Sunday, June 15, 2014

odroidapps.blogspot.com

odroidapps.blogspot.com
GOING CRAZZZY TO FIND INTERESTING 
HOME MADE ANDROID APPS. 
VISIT odroidapps.blogspot.com

Adding a admob ads to android app

Adding a com.google.android.gms.ads.AdView

You can download an example project containing this code here.

Android apps are composed of View objects, which are Java instances the user sees as text areas, buttons and other controls. AdView is simply another View subclass displaying small HTML5 ads that respond to user touch.
Like any View, an AdView may be created either purely in code or largely in XML.
Here is the code for an Activity that will create and display a banner ad:
package com.google.example.gms.ads.banner;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import android.app.Activity;
import android.os.Bundle;
import android.widget.LinearLayout;
/**
 * A simple {@link Activity} that embeds an AdView.
 */
public class BannerSample extends Activity {
  /** The view to show the ad. */
  private AdView adView;

  /* Your ad unit id. Replace with your actual ad unit id. */
  private static final String AD_UNIT_ID = "INSERT_YOUR_AD_UNIT_ID_HERE";

  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Create an ad.
    adView = new AdView(this);
    adView.setAdSize(AdSize.BANNER);
    adView.setAdUnitId(AD_UNIT_ID);

    // Add the AdView to the view hierarchy. The view will have no size
    // until the ad is loaded.
    LinearLayout layout = (LinearLayout) findViewById(R.id.linearLayout);
    layout.addView(adView);

    // Create an ad request. Check logcat output for the hashed device ID to
    // get test ads on a physical device.
    AdRequest adRequest = new AdRequest.Builder()
        .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
        .addTestDevice("INSERT_YOUR_HASHED_DEVICE_ID_HERE")
        .build();

    // Start loading the ad in the background.
    adView.loadAd(adRequest);
  }

  @Override
  public void onResume() {
    super.onResume();
    if (adView != null) {
      adView.resume();
    }
  }

  @Override
  public void onPause() {
    if (adView != null) {
      adView.pause();
    }
    super.onPause();
  }

  /** Called before the activity is destroyed. */
  @Override
  public void onDestroy() {
    // Destroy the AdView.
    if (adView != null) {
      adView.destroy();
    }
    super.onDestroy();
  }
}
YOU HAVE TO CREATE YOUR BANNER IN YOUR XML 

The Result

When you now run your app you should see a banner at the top of the screen: