Search This Blog

Saturday, 25 February 2012

how to monitor network state

Many of the application involves some service running when there is network present or there is a internet access  for that we should know how to monitor the network state

Android provides a system service called ConnectivityManager that allows us to subscribe to notifications when network state is changed. Network connectivity changes can be due one of the following events:
  1. Current network interface being disconnected
  2. A new network interface being connected
  3. Handover (also known as “fallover”) between two network interfaces (usually as a result of one of the two events above), such as WiFi being activated as a result of user coming home and all network traffic will be routed through WiFi as opposed to 3G.
We can use BroadcastReceivers to subscribe to network connectivity changes as follows:
  1. Create a BroadcastReceiver that will handle connectivity status notifications
    The BroadcastReceiver will be notified whenever the network status changes with the following information:
    • ConnectivityManager.EXTRA_NETWORK_INFO – A NetworkInfo object with network information that caused the status change.
    • ConnectivityManager.EXTRA_REASON- A String value about the reason of the connection failure, which can be null.
    • ConnectivityManager.EXTRA_IS_FAILOVER – A boolean value indicating whether the connection manager is failing over from a disconnected network or not.
    • ConnectivityManager.EXTRA_NO_CONNECTIVITY – A boolean value indicating there is no internet connectivity.
    • ConnectivityManager.EXTRA_EXTRA_INFO – A string value indicating the network state.
    • ConnectivityManager.EXTRA_OTHER_NETWORK_INFO – An optional field that contains NetworkInfo describing properties of a new network that is connected as a result of loss of connectivity

    private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
                String reason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON);
                            boolean isFailover = intent.getBooleanExtra(ConnectivityManager.EXTRA_IS_FAILOVER, false);
                
                NetworkInfo currentNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
                NetworkInfo otherNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO);
                if(noConnectivity){
                isConnected=false;
                }else if(noConnectivity==false){
                isConnected=true;
                }
                // do application-specific task(s) based on the current network state, such 
                // as enabling queuing of HTTP requests when currentNetworkInfo is connected etc.
            }

    };















    More details about the CONNECTIVITY_ACTION can be found here
  2. Register the BroadcastReceiver within the application
    The next step is to register the BroadcastReceiver created in the previous step, so our application will actually receive network state change notifications.

    public class MainActivity extends Activity {
    // rest of the code in the Activity are committed for clarity
    /*
    * method to be invoked to register the receiver
    */
    private void registerReceivers() {
    registerReceiver(mConnReceiver,
    new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
    }
  3. Add the necessary permissions to your application manifest.
    Need to add the android.permission.ACCESS_NETWORK_STATE permission to the application’s Manifest (AndroidManifest.xml) file to enable the application to consume the ConnectivityManager service.
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    Any queries drop the comments!!!!

Friday, 24 February 2012

how to keep the listview in users focus


One of my favorite peeves is List-based applications that are always going back to the top of the list. To name a few examples:
  • the OpenIntents File Manager, when you delete an item from the bottom of a long list, goes back to the top of the list to redisplay it, ignoring the fact that if I deleted an item, I may be cleaning up, and would like to keep working in the same area;
  • the standard Contacts manager, when you edit an item, forgets about it and goes back to the top of the list;
  • several other List programs have this behaviour.
A similar error occurs in the HTC SenseUI for Tablets' mail program. When you select a bunch of emails using the per-message checkboxes and then delete them, the scrolling list is left in its previous position, which is now occupied by mail from yesterday or the day before!
It's actually pretty simple to set the focus. Just find the item's index in the Adapter (possibly using theList.getAdapter() if needed), then call
theList.setSelection(index);
This will scroll to the given item, and also select it so it becomes the default to act upon, though it doesn't invoke the action associated with the item.

Have any queries drop the comments

Friday, 17 February 2012

YQL open api

Many of the developers knows that the yql is well structured open api which can be used to retrieve the stock rates,photographs from flicker ,tweets of the person,statuses of the facebook etc. I dealt with this api and found it very beneficial for making the applications in various fields whether it is an app related to social networking entertainment and many if you want to use the yql you have to just query its database through the link and then it will return you the data either in the json(java script object notation) or in the xml format to view its console you can go here YQL console.
private static String convertStreamToString(InputStream is) {
        /*
         * To convert the InputStream to String we use the BufferedReader.readLine()
         * method. We iterate until the BufferedReader return null which means
         * there's no more data to read. Each line will appended to a StringBuilder
         * and returned as String.
         */
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
 
        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
 
    /* This is a test function which will connects to a given
     * rest service and prints it's response to Android Log with
     * labels "Praeda".
     */
    public void  connect(String url)
    {tv=(TextView)findViewById(R.id.TextView06);
tv1=(TextView)findViewById(R.id.TextView07);
tv2=(TextView)findViewById(R.id.TextView08);
tv3=(TextView)findViewById(R.id.TextView09);
tv4=(TextView)findViewById(R.id.TextView10);
   
        HttpClient httpclient = new DefaultHttpClient();
 
        // Prepare a request object
        HttpGet httpget = new HttpGet(url); 
 
        // Execute the request
        HttpResponse response;
        try {
            response = httpclient.execute(httpget);
            // Examine the response status
            Log.i("Praeda",response.getStatusLine().toString());
 
            // Get hold of the response entity
            HttpEntity entity = response.getEntity();
            // If the response does not enclose an entity, there is no need
            // to worry about connection release
            
            if (entity != null) {
 
                // A Simple JSON Response Read
                InputStream instream = entity.getContent();
                String result= convertStreamToString(instream);
                Log.i("Praedaresult",result);
 
                // A Simple JSONObject Creation
                JSONObject json=new JSONObject(result);
                Log.i("Praedaobject","<jsonobject>\n"+json.toString()+"\n</jsonobject>");
 
                // A Simple JSONObject Parsing
               // JSONArray nameArray=json.names();
                //Log.i("query",nameArray.toString());
                //JSONObject query=json.getJSONObject("query");
                //Log.i("query",query.toString());
                //JSONArray results=query.getJSONArray("results");
                //Log.i("rslts",results.toString());
               // JSONArray quote=results.getJSONArray("quote");
                //JSONObject quote=results.getJSONObject("quote");
                //Log.i("quote",quote.toString());
                JSONObject query=json.getJSONObject("query");
                Log.i("query",query.toString());
                JSONObject results=query.getJSONObject("results");
                Log.i("rslt",results.toString());
                JSONObject quote=results.getJSONObject("quote");
                Log.i("quote",quote.toString());
                for(int i=0;i<quote.length();i++)
                {
               
//                    Log.i("Praedafor","<jsonname"+i+">\n"+nameArray.getString(i)+"\n</jsonname"+i+">\n"
//                            +"<jsonvalue"+i+">\n"+valArray.getString(i)+"\n</jsonvalue"+i+">");
                //JSONObject quotes = results.getJSONObject(i)
                    //.getJSONObject("quote");
//                 Log,i
                //Log.i("name",quote.getString("Name"));
                //Log.i("name","pahunch");
                //Log.i("name",quote.getString("Symbol"));
               
                //Log.i("name",quote.getString("DaysLow"));
               
                //Log.i("name",quote.getString("DaysHigh"));
               
                //Log.i("name",quote.getString("Open"));
               
                //Log.i("name",quote.getString("PreviousClose"));
                String symbol=quote.getString("Symbol");
                tv.setText(symbol);
                String dayslow=quote.getString("DaysLow");
                tv1.setText(dayslow);
            //tv1.setText(quote.getString("DaysLow"));
            tv2.setText(quote.getString("DaysHigh"));
            tv3.setText(quote.getString("Open"));
            tv4.setText(quote.getString("Change"));
                }
 
                // A Simple JSONObject Value Pushing
                //json.put("execution-start-time", "sample value");
                Log.i("Praeda","<jsonobject>\n"+json.toString()+"\n</jsonobject>");
                //Log.i("Praeda12",json.get("").toString());
 
                // Closing the input stream will trigger connection release
                instream.close();
            }
 
 
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.getMessage();
        }
        
    }
 
}
Its a simple call to the url and how to retrieve the data from the json format hope it would be beneficial for you if any queries then you can drop a comment.!!!!!!!!

Thursday, 2 February 2012

Optimizing listview!!!

Well here is a short but beneficial tutorial on how to optimize the listview, many of the beginners asked me that if they set any color or background image in their listview the common problem they suffer is of flickering the background when they scroll the listview the color or the background image they added just disappears and after the scrolling make its end mark the background color appears immediately so the main logic behind this is the working of the listview i.e  ListViewredraws its children, it has to blend the children with the window's background. Once again, this requires costly readbacks from memory that are particularly painful during a scroll or a fling when drawing happens dozen of times per second.
To improve drawing performance during scrolling operations, the Android framework reuses the cache color hint. When this hint is set, the framework copies each child of the list in a Bitmap filled with the hint value (assuming that another optimization, called scrolling cache, is not turned off). ListView then blits these bitmaps directly on screen and because these bitmaps are known to be opaque, no blending is required. Also, since the default cache color hint is #191919, you get a dark background behind each item during a scroll.
To fix this issue, all you have to do is either disable the cache color hint optimization, if you use a non-solid color background, or set the hint to the appropriate solid color value. You can do this from code (see setCacheColorHint(int)) or preferably from XML, by using the android:cacheColorHint attribute. To disable the optimization, simply use the transparent color #00000000. The following screenshot shows a list with android:cacheColorHint="#00000000" set in the XML layout file:


well if you have any queries regarding this please drop the comments below !!!!