WebResponce in Android

Posted: July 31, 2012 in Android
Tags: , ,

Hello Droids..!

Here i am demonstrating a class file which will be very helpful in getting web-response. I read so many comments on Web-Response that giving error in fetching.

So here is the .java file into which you just have to pass the URL! and in response you will get String value! That’s it!  Easy and handy!

Here is the Code,


import java.io.ByteArrayOutputStream;
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

public class WebResponse {

	public String getWebResponse(String URL)
	{
	  HttpClient httpclient = new DefaultHttpClient();
      HttpResponse response;
     String responseString = "";
      try {

//           String temp = URL;
//              temp = temp.replaceAll(" ","%20");

          response = httpclient.execute(new HttpGet(URL));
          StatusLine statusLine = response.getStatusLine();
          if(statusLine.getStatusCode() == HttpStatus.SC_OK){
              ByteArrayOutputStream out = new ByteArrayOutputStream();
              response.getEntity().writeTo(out);
              out.close();
              responseString = out.toString();

          } else{
              //Closes the connection.
              response.getEntity().getContent().close();
              throw new IOException(statusLine.getReasonPhrase());
          }
      } catch (ClientProtocolException e) {
          //TODO Handle problems..

      } catch (IOException e) {
          //TODO Handle problems..
      e.printStackTrace();
      }
      return responseString;
	}

}

How to use:

//first create an object of this class file
WebResponse wr = new WebResponse();
String resp = wr.getWebResponse(your url); //add your url

Download here:: WebResponse.java

Comments will be appreciated. 🙂

Advertisements

This is a sample app for integrating Facebook in android.

This will show you how to manage session(is session expired or not), how to handle it.

You are able to post on your own wall, with Title, Message, Link of app, Image and Properties of particular app.

You just have to provide your Facebook app id.

Here is the source code, Android Facebook Demo

Android Twitter Demo

Posted: July 18, 2012 in Android

Hello all,
This is a sample demo how to integrate twitter in android.
How to follow the OAUTH flow, i tried my best to make it simple and understandable.
Here is link for download sourccode,
Android Twitter Demo

If you found any mistake then leave a reply me on my post.

Toggle on/off GPS in Android

Posted: June 3, 2012 in Android
Tags: ,

Hello folks, here am again with android simple code of GPS toggle on/off from code.
what you have to do is just copy the following code in Global.java (where you set your global variables and functions)

when you need to turn on GPS, just call Global.turnGPSOn(“your context”)

here, “your context” will be the class file from where you are calling this function,
let say, i have a class file, named “SplashActivity.java” so what i have to pass as a parameter in that function is,
Global.turnGPSOn(SplashActivity.this);

you can also use, getApplicationContext() as a parameter. But I recommend to use class file name.

Now here is the code,

public static void turnGPSOn(Context context){
        String provider = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);

        if(!provider.contains("gps"))
{ //if gps is disabled
            final Intent poke = new Intent();
            poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider"); 
            poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
            poke.setData(Uri.parse("3")); 
            context.sendBroadcast(poke);
        }
    }
    
    public static void turnGPSOff(Context context){
        String provider = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);

        if(provider.contains("gps")){
            final Intent poke = new Intent();
            poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider"); 
            poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
            poke.setData(Uri.parse("3")); 
            context.sendBroadcast(poke);
        }
    }    

we heard and face so many times that our phone battery is drawn and all that, its due to constant pinging of GPS from any application, which will cause the battery issues. So when you need to fetch location from GPS provider, just turn on the GPS from code and after using it, turn off it.

JSON Parsing in android

Posted: May 23, 2012 in Android

Hello folks, this is how JSON parsing works in android, you just have to follow these few steps!!

e.g., this is JSON,

{
    "Info": {
        "1": {
            "id": "1",
            "name": "xyz",
            "phone_no": "4803578181",
            "address": "asdf",
            "lat": "33.384692",
            "long": "-111.598151"
        }
    }
}

String jsonParse = getJSONfromURL("your URL");  
/*here getJSONfromURL is function, u have to create it globally or locally in your program*/
Log.i(tag,"converted url:"+jsonParse);
JSONObject json;
String id, name,phone_no,address,lat,lon;
try{
       json = new JSONObject(jsonParse);
       JSONObject image = json.getJSONObject("Info");
       JSONObject subJson = image.getJSONObject("1");
       id = subJson.getString("id");
       name = subJson.getString("name");
       phone_no = subJson.getString("phone_no");
       address = subJson.getString("address");
       lat = subJson.getString("lat");
       lon = subJson.getString("long");
}
catch(Exception e){
       System.out.println(e.printStackTrace());
}

//getJSONfromURL function

public static String getJSONfromURL(String url){

       //initialize
       InputStream is = null;
       String result = "";
       JSONObject jArray = null;

       //http post
       try{
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(url);
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();

       }catch(Exception e){
            Log.e(tag, "Error in http connection "+e.toString());
       }

       //convert response to string
      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();
           result=sb.toString();
      }catch(Exception e){
      Log.e(tag, "Error converting result "+e.toString());
     }

      //try parse the string to a JSON object
      try{
          jArray = new JSONObject(result);
      }catch(JSONException e){
        Log.e(tag, "Error parsing data "+e.toString());
      }

      //return jArray;
      return result;
    }

This slideshow requires JavaScript.

An Android Application, which prompt you when you connect your device to USB mode or direct to AC plug.

It will ask for password setup on first time run, you have to initialize that. When any person unplugged your device it starts ringing and notify you that your mobile is in untrusted hand. The only thing to stop notification is password, you have to supply password to stop it.

*May be there are some errors, as it is tested only on my cell, but keep writing me, if you found any bugs there, i’ll definitely solve it and improve the application.

Disclaimer:
This application is developed by me, not to harm any firmware or any organization. If anyone blames the application then it’ll be his/her fault


Get it on Google Play

Waiting for your Comments and Response.

Bigtable is a distributed storage system (built by Google) for managing structured data that is designed to scale to a very large size: petabytes of data across thousands of commodity servers.

Many projects at Google store data in Bigtable, including web indexing, Google Earth, and Google Finance. These applications place very different demands on Bigtable, both in terms of data size (from URLs to web pages to satellite imagery) and latency requirements (from backend bulk processing to real-time data serving).

Despite these varied demands, Bigtable has successfully provided a flexible, high-performance solution for all of these Google products.

Some features

* fast and extremely large-scale DBMS
* a sparse, distributed multi-dimensional sorted map, sharing characteristics of both row-oriented and column-oriented databases.
* designed to scale into the petabyte range
* it works across hundreds or thousands of machines
* it is easy to add more machines to the system and automatically start taking advantage of those resources without any reconfiguration
* each table has multiple dimensions (one of which is a field for time, allowing versioning)
* tables are optimized for GFS (Google File System) by being split into multiple tablets – segments of the table as split along a row chosen such that the tablet will be ~200 megabytes in size.

Architecture

BigTable is not a relational database. It does not support joins nor does it support rich SQL-like queries. Each table is a multidimensional sparse map. Tables consist of rows and columns, and each cell has a time stamp. There can be multiple versions of a cell with different time stamps. The time stamp allows for operations such as “select ‘n’ versions of this Web page” or “delete cells that are older than a specific date/time.”

In order to manage the huge tables, Bigtable splits tables at row boundaries and saves them as tablets. A tablet is around 200 MB, and each machine saves about 100 tablets. This setup allows tablets from a single table to be spread among many servers. It also allows for fine-grained load balancing. If one table is receiving many queries, it can shed other tablets or move the busy table to another machine that is not so busy. Also, if a machine goes down, a tablet may be spread across many other servers so that the performance impact on any given machine is minimal.

Tables are stored as immutable SSTables and a tail of logs (one log per machine). When a machine runs out of system memory, it compresses some tablets using Google proprietary compression techniques (BMDiff and Zippy). Minor compactions involve only a few tablets, while major compactions involve the whole table system and recover hard-disk space.

The locations of Bigtable tablets are stored in cells. The lookup of any particular tablet is handled by a three-tiered system. The clients get a point to a META0 table, of which there is only one. The META0 table keeps track of many META1 tablets that contain the locations of the tablets being looked up. Both META0 and META1 make heavy use of pre-fetching and caching to minimize bottlenecks in the system.

Implementation

BigTable is built on Google File System (GFS), which is used as a backing store for log and data files. GFS provides reliable storage for SSTables, a Google-proprietary file format used to persist table data.

Another service that BigTable makes heavy use of is Chubby, a highly-available, reliable distributed lock service. Chubby allows clients to take a lock, possibly associating it with some metadata, which it can renew by sending keep alive messages back to Chubby. The locks are stored in a filesystem-like hierarchical naming structure.

There are three primary server types of interest in the Bigtable system:

1. Master servers: assign tablets to tablet servers, keeps track of where tablets are located and redistributes tasks as needed.
2. Tablet servers: handle read/write requests for tablets and split tablets when they exceed size limits (usually 100MB – 200MB). If a tablet server fails, then a 100 tablet servers each pickup 1 new tablet and the system recovers.
3. Lock servers: instances of the Chubby distributed lock service. Lots of actions within BigTable require acquisition of locks including opening tablets for writing, ensuring that there is no more than one active Master at a time, and access control checking.

Example from Google’s research paper:

alt text

A slice of an example table that stores Web pages. The row name is a reversed URL. The contents column family contains the page contents, and the anchor column family contains the text of any anchors that reference the page. CNN’s home page is referenced by both the Sports Illustrated and the MY-look home pages, so the row contains columns named anchor:cnnsi.com and anchor:my.look.ca. Each anchor cell has one version; the contents column has three versions, at timestamps t3, t5, and t6.

API

Typical operations to BigTable are creation and deletion of tables and column families, writing data and deleting columns from a row. BigTable provides this functions to application developers in an API. Transactions are supported at the row level, but not across several row keys.