Progress Bar Tutorial in Android

In this tutorial I am using my previous project (you can see the post here) in which I fetched the data from my blog using JSOUP library. In this project, I made a progress dialog till the network operation occur.

In progress dialog there is a dialog with the message and a spinner which revolves till the network operation or any background task.


During the data is fetched in the background, progress dialog is used to give the user a better interaction in the android application.

Create new project in Eclipse : File => New => Android Application Project and give any package name.

Code for activity_main.xml is same as previous tutorial and is shown below :

 <LinearLayout 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:orientation="vertical"  
   >  
   
   <LinearLayout   
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:orientation="horizontal"  
     >  
   <TextView  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:text="TITLE :"   
     android:textSize="20sp"  
     android:textStyle="bold"  
     android:layout_marginLeft="15px"  
     android:layout_marginTop="10px"  
       
     />  
   <TextView  
     android:id="@+id/titleText"  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:textSize="18sp"  
     android:layout_marginLeft="15px"  
     android:layout_marginTop="10px"  
     />  
   
   </LinearLayout>  
     
     
   <TextView  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:text="POSTS TITLE :"   
     android:textSize="20sp"  
     android:textStyle="bold"  
     android:layout_marginLeft="15px"  
     android:layout_marginTop="10px"  
       
     />  
   <TextView  
     android:id="@+id/postsText"  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:textSize="15sp"  
     android:layout_marginLeft="15px"  
     android:layout_marginTop="10px"  
     />   
 </LinearLayout>  
   


Now code for MainActivity.java is shown below :

 package com.javalanguageprogramming.jsoupdemo;  
   
 import org.jsoup.Jsoup;  
 import org.jsoup.nodes.Document;  
 import org.jsoup.select.Elements;  
   
 import android.app.Activity;  
 import android.app.ProgressDialog;  
 import android.os.Bundle;  
 import android.widget.TextView;  
   
   
 public class MainActivity extends Activity {  
   
      TextView titleText, postText;  
      String title, posts = "";  
      ProgressDialog progressDialog;  
        
      @Override  
      protected void onCreate(Bundle savedInstanceState) {  
           super.onCreate(savedInstanceState);  
           setContentView(R.layout.activity_main);  
             
           //initialize variables  
           titleText = (TextView)findViewById(R.id.titleText);  
           postText = (TextView)findViewById(R.id.postsText);  
             
           //start progress dialog at the start of network operation  
           progressBarInitialize();  
             
           //run on new thread because we cannot do network operation on main thread  
           new Thread(new Runnable() {  
                  
                @Override  
                public void run() {  
                     try{  
                                 
                     //get the Document object from the site. Enter the link of site you want to fetch  
                     Document document = Jsoup.connect("http://javalanguageprogramming.blogspot.in/").get();  
                       
                     //Get the title of blog using title tag  
                     title = document.select("h1.title").text().toString();  
                     //set the title of text view  
                       
                       
                     //Get all the elements with h3 tag and has attribute a[href]  
                     Elements elements = document.select("div.post-outer").select("h3").select("a[href]");  
                     int length = elements.size();  
                       
                     for(int i=0; i<length; i++){  
                          //store each post heading in the string  
                          posts += elements.get(i).text() + "\n\n";  
                            
                     }  
                       
                     //Run this on ui thread because another thread cannot touch the views of main thread  
                     runOnUiThread(new Runnable() {  
                            
                          @Override  
                          public void run() {  
                                 
                               //set both the text views  
                               titleText.setText(title);  
                               postText.setText(posts);  
                                 
                               //first check if the progress Dialog is already showing than dismiss it  
                               if(progressDialog.isShowing())  
                                    progressDialog.dismiss();  
                          }  
                     });  
                       
                       
                       
                }catch(Exception e){  
                     e.printStackTrace();  
                     //if any exception occurs than progress Dialog should be removed  
                     if(progressDialog.isShowing())  
                          progressDialog.dismiss();  
                }  
                }  
           }).start();  
             
             
 }  
        
      private void progressBarInitialize(){  
           //initialize the progress dialog during the start of network operation  
                     progressDialog = ProgressDialog.show(MainActivity.this, "Loading...", "Fetching the data");  
                     //set the progress dialog to indeterminate state  
                     progressDialog.setIndeterminate(true);  
                     //make the progress dialog not cancellable so that user cannot cancel the network operation  
                     //or you can set it cancellable but for that you need to set the cancel mechanism for the network operation  
                     progressDialog.setCancelable(false);  
                       
      }  
 }  
   


In above activity I used show function of ProgressDialog object and through parameters the message and sub message is passed to show it on the Activity. I initialize the progress dialog when the network operation is started and cancel it when network operation finished.
Do not forget to give the uses permission : Internet for the network operation in this application.

Auto Complete Text View Tutorial in Android

In Auto Complete Text View whenever we start writing a text in the Edit View than it will automatically show the available optionsrelated to that text as you stored in an array or in a database. 

In this example, I am storing the available options in the array and than just set the adapter for simple dropdown list available in android environment with that list.

To make this type of application you need to use theAutoCompleteTextView class available in android environment rather than simple TextView or EditView.

Let’s start coding by creating a project in Eclipse : File => New =>Android Application Project and give a package name ascom.javalanguageprogramming.autocompletetextdemo.

Copy the code for activity_main.xml as shown below :

 <LinearLayout 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"  
   >  
   
   <AutoCompleteTextView  
     android:id="@+id/autoText"  
     android:layout_width="220dp"  
     android:layout_height="50dp"  
     android:layout_marginLeft="40dp"  
     android:layout_marginTop="50dp"  
     />  
   
 </LinearLayout>  
In this xml file I am using AutoCompleteTextView for completing of text automatically from String array.
Now consider the code for Main.java as shown below :
package com.javalanguageprogramming.autocompletetextdemo;  
   
 import android.app.Activity;  
 import android.os.Bundle;  
 import android.widget.ArrayAdapter;  
 import android.widget.AutoCompleteTextView;  
   
   
 public class MainActivity extends Activity {  
   
      AutoCompleteTextView autoText;  
      @Override  
      protected void onCreate(Bundle savedInstanceState) {  
           super.onCreate(savedInstanceState);  
           setContentView(R.layout.activity_main);  
             
           //initialize auto complete text view  
           autoText = (AutoCompleteTextView)findViewById(R.id.autoText);  
             
           //make an array for the suggestions  
           String[] suggest = {"aa", "all", "auto", "ask", "bb", "bat", "bad", "back", "ball", "cat", "java", "Program", "tutorial"};  
             
           //make an array adapter for viewing string array  
           ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_dropdown_item_1line, suggest);  
             
           //set the adapter to the auto complete text view  
           autoText.setAdapter(adapter);  
      }  
 }  
   


In this Activity, a String array named as “suggest” is used to provide the available options and ArrayAdapter for providing the views to the drop down list

How to call a web service from Android

By far the easiest way is to use the ksoap2-android API. You need the ksoap2 jar file (with all dependencies) which can be found here and you need to add this to your classpath. In the following sample code we call a free web service, called currency convertor, which has one operation (method) that is is called ConversionRate. If you look at the service dscription (the WSDL file), you will see that this operation takes two parameters, FromCurrency andToCurrency. Lets say that we want to find out the conversion rate from USD to EUR. We implement the following Activity



package gr.panos.caller;

import java.io.IOException;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.SoapFault;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.widget.TextView;

public class ConvertorCaller extends Activity {

    public final static String URL = "http://www.webservicex.net/CurrencyConvertor.asmx";
    public static final String NAMESPACE = "http://www.webserviceX.NET/";
    public static final String SOAP_ACTION = "http://www.webserviceX.NET/ConversionRate";
    private static final String METHOD = "ConversionRate";
    private TextView textView;
     
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_convertor_caller);
        textView = (TextView) findViewById(R.id.textView1);
        AsyncTaskRunner runner = new AsyncTaskRunner();
        runner.execute();
    }

     private class AsyncTaskRunner extends AsyncTask<String, String, String>{

         private String resp;

        @Override
        protected String doInBackground(String... params) {
             try {
              SoapObject request = new SoapObject(NAMESPACE, METHOD);
              request.addProperty("FromCurrency", "USD");
              request.addProperty("ToCurrency", "EUR");

              SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
              envelope.dotNet = true;
              envelope.setOutputSoapObject(request);  
              System.out.println("************ I AM SENDING: " + envelope.bodyOut);
               
               HttpTransportSE transport = new HttpTransportSE(URL);
               try {
                 transport.call(SOAP_ACTION, envelope);
               } catch (IOException e) {
                 e.printStackTrace();
               } catch (XmlPullParserException e) {
                 e.printStackTrace();
             }
           if (envelope.bodyIn != null) {
               if (envelope.bodyIn instanceof SoapFault) {
                   String s = ((SoapFault) envelope.bodyIn).faultstring;
                   System.out.println("************ ERROR: " + s);
                   resp = s;
               } else if (envelope.bodyIn instanceof SoapObject) {
                   SoapObject obj = ((SoapObject) envelope.bodyIn); 
                   System.out.println("**** RESPONSE: " +obj);
                    
                   SoapPrimitive root = (SoapPrimitive) obj.getProperty(0);
                   System.out.println("**** CONVERSION RATE: " +root.toString());
                    
                   resp = root.toString();
               }
                    
           }
         } catch (Exception e) {
           e.printStackTrace();
           resp = e.getMessage();
         }
         return resp;
       }

          /**
           * 
           * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
           */
          @Override
          protected void onPostExecute(String result) {
              textView.setText(resp);
          }
     
          /**
           * 
           * @see android.os.AsyncTask#onPreExecute()
           */
          @Override
          protected void onPreExecute() {
          }
          /**
           * 
           * @see android.os.AsyncTask#onProgressUpdate(Progress[])
           */
          @Override
          protected void onProgressUpdate(String... text) {
          }
    }


}



You also need to define a text view in your layout as well as give the activity INTERNET permission in your manifest file.

Write a program with triangle star pattern


How to write a program with triangle star pattern. 



*
* *
* * *



public class triangle {
public static void main(String[] args) {
for(int i=1;i<=3;i++) {
for(int j=3;j>=i; j--) {
System.out.print(" ");
}
for(int k=1;k<=i; k++) {
System.out.print("* ");
}
System.out.print("\n");
}
}

}

Write a program with L shape triangle pattern


*
* *
* * *





public class task1 {


public static void main(String[] args) {


for(int i=1;i<=3;i++) {


for(int j=1;j<=i; j++) {


System.out.print("*");


}

System.out.print("\n");

}

}
}

LinkWithin

Related Posts Plugin for WordPress, Blogger...