Pages

Saturday, January 24, 2015

Setting ToolBar As ActionBar with Navigation Drawer and Lollipop Drawer Toggle Animation

This tutorial shows how to set Android Toolbar as ActionBar along with beautiful Android Navigation Drawer and Drawer Toggle animation.

First Step: Import Support Libraries 

If you are using Gradle, add appcompat as dependency in your build.gradle file.


 dependencies {  
   compile "com.android.support:appcompat-v7:21.0.+"  
 }  


Second Step: Add ToolBar and Navigation Drawer in the XML Layout file.


activity_main.xml



 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
   xmlns:app="http://schemas.android.com/apk/res-auto"  
   android:layout_width="fill_parent"  
   android:layout_height="fill_parent"  
   android:orientation="vertical">  
   <android.support.v7.widget.Toolbar  
     android:id="@+id/toolbar"  
     android:layout_width="match_parent"  
     android:layout_height="wrap_content"  
     android:layout_marginTop="@dimen/statusbar_padding"  
     android:background="@color/transparent"  
     android:elevation="3dp"  
     android:minHeight="?attr/actionBarSize"  
     app:popupTheme="@style/ThemeOverlay.AppCompat.Light"  
     app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"  
     app:title="@string/app_name"  
     app:titleTextAppearance="@style/MyTheme.MyToolbar.TitleTextStyle_Main" />  
   <android.support.v4.widget.DrawerLayout  
     android:id="@+id/drawer_layout"  
     android:layout_width="match_parent"  
     android:layout_height="match_parent">  
     <!-- The main content view -->  
     <RelativeLayout  
       android:id="@+id/container"  
       android:layout_width="match_parent"  
       android:layout_height="match_parent">  
     </RelativeLayout>  
     <!-- The navigation drawer -->  
     <FrameLayout  
       android:layout_width="@dimen/navdrawer_width"  
       android:layout_height="match_parent"  
       android:layout_gravity="start">  
       <ScrollView  
         android:id="@+id/drawer"  
         android:layout_width="match_parent"  
         android:layout_height="match_parent"  
         android:background="@color/navdrawer_background">  
         <LinearLayout  
           android:layout_width="match_parent"  
           android:layout_height="wrap_content"  
           android:orientation="vertical">  
           <include layout="@layout/navdrawer_content" />  
         </LinearLayout>  
       </ScrollView>  
     </FrameLayout>  
   </android.support.v4.widget.DrawerLayout>  
 </LinearLayout>  


Note: Create themes based on your requirements for toolbar.

Third Step: Link XML to JAVA Class

ActivityMain.Java (extends ActionBarActivity)



  @Override  
   protected void onCreate(Bundle savedInstanceState) {  
     super.onCreate(savedInstanceState);  
     setContentView(R.layout.activity_main);  
     DrawerLayout mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);  
     ActionBarDrawerToggle mDrawerToggle;   
    Toolbar  toolbar = (Toolbar) findViewById(R.id.toolbar);  
     setSupportActionBar(toolbar);  
     mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar,  
         R.string.hello_world, R.string.hello_world);  
     mDrawerToggle.setDrawerIndicatorEnabled(true);  
     mDrawerLayout.post(new Runnable() {  
       @Override  
       public void run() {  
         mDrawerToggle.syncState();  
       }  
     });  
     mDrawerLayout.setDrawerListener(mDrawerToggle);  
     mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, Gravity.START);  
 }  

Fourth Step: Set Theme


In styles.xml create a new theme and add this theme as the Application theme in the Manifest.xml file



  <style name="Theme.Sample" parent="Theme.AppCompat.Light">  
     <item name="windowActionBar">false</item>  
   </style>  

Now Run your code.


Your Toolbar with Navigation Drawer look similar to this screenshot.

Happy Coding....:)

Friday, September 27, 2013

Simple XML parsing in android using ksoap2.

The example is for doing an authentication by entering the username and password as Properties. On login success it returns an id, Which is used for further operations.


First of all download the latest ksoap2 - Android from here:
https://code.google.com/p/ksoap2-android/wiki/HowToUse?tm=2

And include it into your project.

In your MainActivity.java :


 private static String SOAP_ACTION = "http://tempuri.org/fnGetId";   
 private static String NAMESPACE = "http://tempuri.org/";  
 private static String METHOD_NAME = "fnGetId";  
 private static String URL = "http://187.168.1.100/api/Service.asmx";   

Using an AsyncTask :


 new AsyncTask<String, String, String>() {    
 protected void onPreExecute() {   
 progress = ProgressDialog.show(MainActivity.this, "","Authenticating...",true,true,  
 new DialogInterface.OnCancelListener() {  
     @Override  
       public void onCancel(DialogInterface dialog) {  
                  cancel(true);  
                            }  
                });  
      };  
     @Override  
     protected String doInBackground(String... params) {  
     // TODO Auto-generated method stub  
     SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);  
     // add properties here       
     request.addProperty("userName", et_username.getText().toString());   
     request.addProperty("password", et_password.getText().toString());  
 SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);  
           envelope.dotNet = true;  
           envelope.setOutputSoapObject(request);  
      HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);  
      try {     
           androidHttpTransport.call(SOAP_ACTION, envelope);  
     if (envelope.bodyIn instanceof SoapObject) {  
            // SoapObject = SUCCESS  
             SoapObject vSoapObject = (SoapObject) envelope.bodyIn;  
             vCount = vSoapObject.getPropertyCount();  
             System.out.println("count: " + vCount);              
             SoapObject response = (SoapObject)envelope.getResponse();  
        Log.e("Soapobject response at main activity", response.toString());  
      if (response != null) {  
  SoapObject dataset = (SoapObject)            response.getProperty("NewDataSet");  
 //for <NewDataSet>tag  
 SoapObject table = (SoapObject) dataset.getProperty("Table");  
 // for <Table> tag under                                                                           
 SoapPrimitive agentid = (SoapPrimitive) table.getProperty("AGENT_ID");  
 // <AGENT_ID> tag                                                                     
                  aid = agentid.toString();  
                      }  
  } else if (envelope.bodyIn instanceof SoapFault) {  
  // SoapFault = FAILURE  
      SoapFault response = (SoapFault) envelope.bodyIn;  
      Log.e("response", response.toString());  
  }  
           } catch (Exception e) {  
           e.printStackTrace();  
           Log.e("Authentivcations error", "GLdkjgl");  
           }  
          return null;  
        }  
        protected void onPostExecute(String result) {  
        // Log.e(pdlist.size()+"size", "dfsadfas");  
          if(progress!=null)  
          {  
          progress.dismiss();  
          progress.cancel();  
         }  
          if(vCount==0){  
   Toast.makeText(MainActivity.this,"Authentication Failed" , Toast.LENGTH_LONG).show();  
          }  
 else{  
          Bundle bundle=new Bundle();  
          bundle.putString("agentid", aid);  
          Intent intent = new Intent(MainActivity.this,HomeActivity.class);  
          intent.putExtra("Bundle", bundle);  
          startActivity(intent);  
            MainActivity.this.finish();  
   }  
        };  
      }.execute();  

Thanks...:)     


Thursday, August 22, 2013

Export coordinates obtained from Location Providers to GPX file.

This code will help you convert the coordinates and data that you obtained from Location Providers(Both GPS and Network) to GPX file.

First of all you need to add on your coordinates and data to listarray and then pass on these values to the Filewriter.



Lets say these are your listarrays:



   latlist.add(latitudes)  
   lonlist.add(longitudes)  
   timelist.add(time);  
   altitudelist.add(altitude);  
   speedlist.add(speed);  


Then pass on these values to Writer as given below:



 File root = new File(Environment.getExternalStorageDirectory().getPath() + "/MyGPX/");  
               root.mkdirs();  
              if (root.canWrite()) {  
          File gpxfile = new File(root, "Mytrace.gpx");  
          FileWriter gpxwriter = new FileWriter(gpxfile);  
          BufferedWriter out = new BufferedWriter(gpxwriter);  
  out.write("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>"  
              + "\n\n" + "<gpx version=\"1.0\" creator=\"Traceify\">"  
               + "\n" + "<trk>" + "\n");  
          out.write("<name>MyGPX GPX DOC</name>"+"\n");  
          out.write("<trkseg>"+"\n");  
          Log.e("list size is","PPPP"+latlist.size() );  
          for (int i = 0; i < latlist.size(); i++) {  
          // String outDate = ISO_8601_DATE_TIME.format(timelist.get(i));  
           Log.e("writing to file","PPPPPPPPP" );  
 out.write("<trkpt" +" " +"lat="+"\""+(latlist.get(i))+"\""+" "+"lon="+"\""+(lonlist.get(i))+"\"" +">" + "\n"  
      + "<ele>"+(altitudelist.get(i))+"</ele>" + "\n" + "<speed>"+(speedlist.get(i))+"</speed>" + "\n"  
             +"<time>"+(timelist.get(i))+"</time>" + "\n"+ "</trkpt>" +"\n");  
          }  
          out.write("</trkseg>" + "\n" + "</trk>" +"\n"+"</gpx>");  
          out.close();  
          latlist.clear();  
          lonlist.clear();  
          Log.e("cleared from list","dffffffffffff" );  
          timelist.clear();  
          altitudelist.clear();  
          speedlist.clear();  
          try{  
          cur.close();  
         db.close();  
          }catch (Exception e) {  
    // TODO: handle exception  
    }  



You may customize the code depending on your needs!!
Thanks...:)


                

Wednesday, July 10, 2013

Step By Step Procedure to Decompile Android .apk file

Step 1:

Make a new folder and put .apk file in it (which you want to decode). Now rename the extension of this .apk file to .zip (eg.: rename from filename.apk to filename.apk.zip) and save it. Now you get classes.dex files, etc. At this stage you are able to see drawables... but not xml and java files, so continue to step 2.

Step 2:

Now extract this zip apk file in the same folder (or NEW FOLDER). Now download dex2jar from this link http://code.google.com/p/dex2jar/ and extract it to the same folder (or NEW FOLDER). Now open command prompt and change directory to that folder (or NEW FOLDER). Then write dex2jar classes.dex and press enter. Now you get classes.dex.dex2jar file in the same folder. Then download java decompiler from http://java.decompiler.free.fr/?q=jdgui and now double click on jd-gui and click on open file. Then open classes.dex.dex2jar file from that folder. Now you get class files and save all these class files (click on file then click "save all sources" in jd-gui) by src name. At this stage you get java source but the xml files are still unreadable, so continue to step 3.

Step 3:

Now open another new folder and put these files
  1. put .apk file which you want to decode
  2. download apktool v1.x AND apktool install window (both can be downloaded at the same location) and put in the same folder
  3. download framework-res.apk file and put in the same folder (Not all apk file need framework-res.apk file)
  4. Open a command window
  5. Navigate to the root directory of APKtool and type the following command: apktool if framework-res.apk
  6. apktool d "fname".apk ("fname" denotes filename which you want to decode)
now you get a file folder in that folder and now you can easily read xml files also.

Step 4:

Now just copy contents of both folder(in this case both new folder)to the single one
and now enjoy the complete source code........

Also Check out the following for more references:

Happy Coding!!

Monday, June 17, 2013

Creating your Custom Toast View in Android

You can create a customised layout for your toast notification. Its pretty easy.
To create a custom layout, define a View layout, in XML or in your application code, and pass the root View object to the setView(View) method.
For example, you can create the layout for the toast with the following XML (saved as toast_new_layout.xml):

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:id="@+id/toast_layout_r"
              android:orientation="horizontal"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:padding="8dp"
              android:background="#DAAA"
              >
    <ImageView android:src="@drawable/droid"
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:layout_marginRight="8dp"
               />
    <TextView android:id="@+id/text"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:textColor="#FFF"
              />
</LinearLayout>

Notice that the ID of the LinearLayout element is "toast_layout_r". You must use this ID to inflate the layout from the XML, as shown here:
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast,
                               (ViewGroup) findViewById(R.id.toast_layout_r));
TextView text = (TextView) layout.findViewById(R.id.text);
text.setText("This is a custom toast");
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();


First, retrieve the LayoutInflater with getLayoutInflater() (or getSystemService()), and then inflate the layout from XML using inflate(int, ViewGroup). The first parameter is the layout resource ID and the second is the root View. You can use this inflated layout to find more View objects in the layout, so now capture and define the content for the ImageView and TextView elements. Finally, create a new Toast withToast(Context) and set some properties of the toast, such as the gravity and duration. Then callsetView(View) and pass it the inflated layout. You can now display the toast with your custom layout by calling show().
Note: Do not use the public constructor for a Toast unless you are going to define the layout withsetView(View). If you do not have a custom layout to use, you must use makeText(Context, int, int)to create the Toast.
For more reference visit:  http://developer.android.com/reference/android/widget/Toast.html
Screen-shot of  a custom toast displayed while outgoing calls.

You can customize the design of toast layout depending on your needs like the above one.