Thursday 7 August 2014

Difference Between JSON Object and JSON Array

The difference is the same as a (Hash)Map vs List.

JSONObject:  JSON objects are written inside curly brackets,A modifiable set of name/value mappings. 

Contains named values (key->value pairs, tuples or whatever you want to call them) -like ID : 1 . Order of elements is not important -a JSONObject of {id: 1, name: 'B'} is equal to 
{name: 'B', id: 1}.

JSONArray: JSON arrays are written inside square brackets.An array can contain multiple objects(jsonobject)  A dense indexed sequence of values. Contains only series values -like [1, 'value'] .Order of values is important -array of [1,'value'] is not the same as ['value',1]


Monday 21 April 2014

JSON Parsing Using Thread

 Ravi - Android Hive implemented using Asyn Task . but i have implemented it using Thread and Handlers
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
 import java.io.BufferedReader;  
 import java.io.IOException;  
 import java.io.InputStream;  
 import java.io.InputStreamReader;  
 import org.apache.http.HttpEntity;  
 import org.apache.http.HttpResponse;  
 import org.apache.http.client.HttpClient;  
 import org.apache.http.client.methods.HttpGet;  
 import org.apache.http.impl.client.DefaultHttpClient;  
 import org.json.JSONArray;  
 import org.json.JSONException;  
 import org.json.JSONObject;  
 import android.app.Activity;  
 import android.app.ProgressDialog;  
 import android.os.Bundle;  
 import android.os.Handler;  
 import android.os.Message;  
 import android.util.Log;  
 import android.widget.TextView;  
 public class MainActivity extends Activity {  
      TextView tv;  
      StringBuilder sb;  
      BufferedReader br;  
      InputStream is;  
      String jsn;  
      HttpEntity httpEntity = null;  
      ProgressDialog progDialog;  
      HttpClient httpClient;  
      HttpResponse response;  
      HttpGet get;  
      String url = "http://api.androidhive.info/contacts/";  
      @Override  
      protected void onCreate(Bundle savedInstanceState) {  
           super.onCreate(savedInstanceState);  
           setContentView(R.layout.activity_main);  
           tv = (TextView) findViewById(R.id.textView1);  
           getData();  
      }  
      private void getData() {  
           progDialog = ProgressDialog.show(MainActivity.this, "please Wait ", "Loading....");  
           Thread background = new Thread(new Runnable() {  
                @Override  
                public void run() {  
                     // TODO Auto-generated method stub  
                     try {  
                          httpClient = new DefaultHttpClient();  
                          get = new HttpGet(url);  
                          response = httpClient.execute(get);  
                          httpEntity = response.getEntity();  
                          is = httpEntity.getContent();  
                          br = new BufferedReader(new InputStreamReader(is));  
                          sb = new StringBuilder();  
                          String line = null;  
                          while ((line = br.readLine()) != null) {  
                               sb.append(line);  
                          }  
                          br.close();  
                          jsn = sb.toString();  
                          handler.sendEmptyMessage(0);  
                     } catch (IOException e) {  
                          // TODO Auto-generated catch block  
                          e.printStackTrace();  
                          handler.sendEmptyMessage(1);  
                     } catch (Throwable e) {  
                          // just end the background thread  
                          Log.i("ThreadHandler", "Thread exception " + e);  
                          handler.sendEmptyMessage(1);  
                     }  
                }  
           });  
           background.start();  
      }  
      Handler handler = new Handler() {  
           @Override  
           public void handleMessage(Message msg) {  
                // TODO Auto-generated method stub  
                super.handleMessage(msg);  
                if (progDialog != null && progDialog.isShowing()) {  
                     progDialog.dismiss();  
                }  
                if (msg.what == 0) {  
                     try {  
                          if (jsn != null) {  
                               JSONObject jsonobj = new JSONObject(jsn);  
                               Log.d("obj ", jsonobj.toString());  
                               JSONArray arry = jsonobj  
                                         .getJSONArray("contacts");  
                               for (int i = 0; i <= arry.length(); i++) {  
                                    JSONObject temp = arry.getJSONObject(i);  
                                    Log.d("objects " + i, temp.toString());  
                                    String id = temp.getString("id");  
                                    String name = temp.getString("name");  
                                    String email = temp.getString("email");  
                                    JSONObject phone = temp  
                                              .getJSONObject("phone");  
                                    Log.d("phone ", phone.toString());  
                                    String mobile = phone.getString("mobile");  
                                    String home = phone.getString("home");  
                                    tv.append("id :" + id + "\n");  
                                    tv.append("Name : " + name + "\n");  
                                    tv.append("email :" + email + "\n");  
                                    tv.append("mobile :" + mobile + "\n");  
                                    tv.append("home :" + home + "\n\n\n");  
                               }  
                          }  
                     } catch (JSONException e) {  
                          // TODO Auto-generated catch block  
                          e.printStackTrace();  
                     }  
                } else if (msg.what == 1) {  
                }  
           }  
      };  
 }  

Thursday 10 April 2014

Android -Context Types -Usage

Context objects are so common, and get passed around so frequently, it can be easy to create a situation you didn’t intend.  Loading resources, launching a new Activity, obtaining a system service, getting internal file paths, and creating views all require a Context (and that’s not even getting started on the full list!) to accomplish the task.  What I’d like to do is provide for you some insights on how Context works alongside some tips that will (hopefully) allow you to leverage it more effectively in your applications.

Context Types

Not all Context instances are created equal.  Depending on the Android application component, the Context you have access to varies slightly:

Application – is a singleton instance running in your application process.  It can be accessed via methods like getApplication() from an Activity or Service, and getApplicationContext() from any other object that inherits from Context.  Regardless of where or how it is accessed, you will always receive the same instance from within your process.


Activity/Service – inherit from ContextWrapper which implements the same API, but proxies all of its method calls to a hidden internal Context instance, also known as its base context.  Whenever the framework creates a new Activity or Service instance, it also creates a new ContextImpl instance to do all of the heavy lifting that either component will wrap.  Each Activity or Service, and their corresponding base context, are unique per-instance.


BroadcastReceiver – is not a Context in and of itself, but the framework passes a Context to it in onReceive() each time a new broadcast event comes in.  This instance is a ReceiverRestrictedContext with two main functions disabled; calling registerReceiver() and bindService().  These two functions are not allowed from within an existing BroadcastReceiver.onReceive().  Each time a receiver processes a broadcast, the Context handed to it is a new instance.


ContentProvider – is also not a Context but is given one when created that can be accessed via getContext().  If the ContentProvider is running local to the caller (i.e. same application process), then this will actually return the same Application singleton.  However, if the two are in separate processes, this will be a newly created instance representing the package the provider is running in.


Saved References

The first issue we need to address comes from saving a reference to a Context in an object or class that has a lifecycle that extends beyond that of the instance you saved.  For example, creating a custom singleton that requires a Context to load resources or access a ContentProvider, and saving a reference to the current Activity or Service in that singleton.



To protect against this, we modify the singleton to always reference the application context:
public class CustomManager {
    private static CustomManager sInstance;
    public static CustomManager getInstance(Context context) {
        if (sInstance == null) {
            //Always pass in the Application Context
            sInstance = new CustomManager(context.getApplicationContext());
        }
 }
    private Context mContext;
    private CustomManager(Context context) {
        mContext = context;
    }
}

Now it doesn’t matter where our Context came from, because the reference we are holding is safe.  The application context is itself a singleton, so we aren’t leaking anything by creating another static reference to it.  Another great example of places where this can crop up is saving references to a Context from inside a running background thread or a pending Handler.


Credits: http://www.doubleencore.com/2013/06/context/



Insights

 1. use if you want to send image and text  of current view of list adapter to next activity


  ListView lv = (ListView) arg0;
                   
                    String fieldname = names[arg2];
                    Toast mtost=Toast.makeText(getApplicationContext(),fieldname, T
oast.LENGTH_SHORT);
              
mtost.show();         
                    
                 /// fishtextview=(TextView)findViewById(R.id.textView1);

                   TextView name=(TextView)arg0.getChildAt(arg2-lv.g
etFirstVisiblePosition()).findViewById(R.id.textView1);
                   name.setText(fieldname);
                   TextView desc = (TextView)arg0.getChildAt(arg2-lv.
getFirstVisiblePosition()).findViewById(R.id.textView2);
              
                   ImageView img=(ImageView)arg0.getChildAt(arg2-lv.
getFirstVisiblePosition()).findViewById(R.id.icon);
                   img.buildDrawingCache();
                   Bitmap bmap = img.getDrawingCache();
                   
                   
                   Intent i = new Intent(getApplicationContext(), Second.class);
                   
                   
                   Bundle extras = new Bundle();
                   extras.putParcelable("imagebitmap", bmap);
                   i.putExtras(extras);
                   i.putExtra("text", fieldname.toString());
                i.putExtra("desc", desc.toString());
                   startActivity(i);
    
2. String ArrayList to String Array and Setting Text to edit Text


                      final List<String> Items = new ArrayList<String>(); 

                  String[] array = Items.toArray(new String[Items.size()]);
              StringBuilder builder = new StringBuilder();
              for (String s: array) {
                  builder.append(s);
                  builder.append("  ");

              }

Sunday 6 April 2014

Emu, A Smarter Messaging App With A Built-In Assistant, Schedule lunches, share your location, and set reminders — as easily as you send a photo...many more


Emu, a new mobile messaging application   is not just another text messaging alternative – it’s a full-fledged mobile assistant allowing you to schedule appointments, share your location, set reminders, get movie showtimes or buy tickets, reserve a table, and more, thanks to an artificial intelligence engine that understands the context of your messages in order to help you take action upon them.

The iOS app, now exiting beta, is a free download here on iTunes.
For android Devices  -Coming soon  

schedule-restaurant

Friday 4 April 2014

1 Private String TitleName[]={"Google ", "Facebook","LinkedIn","Twitter","Tech Crunch"}; 

ArrayList<string> array_sort=new ArrayList<string> (Arrays.asList(TitleName));



2. List : A List is a collection which maintains an ordering for its elements. Every element in the List has an index. Each element can thus be accessed by its index, with the first index being zero. Normally, Lists allow duplicate elements, as compared to Sets, where elements have to be unique.
3.TextWatcher -  Call addTextChangedListener(new TextWatcher()) to implement 
When an object of a type is attached to an Editable, its methods will be called when the text is changed. it has three abstract Methods .return type is void 

1. afterTextChanged(Editable s)
This method is called to notify you that, somewhere within s, the text has been changed.
but be careful not to get yourself into an infinite loop, because any changes you make will cause this method to be called again recursively. 
(You are not told where the change took place because other afterTextChanged() methods may already have made other changes and invalidated the offsets. But if you need to know here, you can use setSpan(Object, int, int, int) in
onTextChanged(CharSequence, int, int, int) to mark your place and then look up from here where the span ended up.

2. beforeTextChanged(CharSequence s, int start, int count, int after)
This method is called to notify you that, within s, the count characters beginning at start are about to be replaced by new text with length after.

3. onTextChanged(CharSequence s, int start, int before, int count)
This method is called to notify you that, within s, the count characters beginning at start have just replaced old text that had length before.
For Example and Code : Click Here

3. Data updates in the adapter
The notifyDataSetChanged() method on the adapter is called if the data has changed or if new data is available.
The notifyDataSetInvalidated() method is called if the data is not available anymore.
4. The setAdapter() method then sets a custom adapter (ImageAdapter) as the source for all items to be displayed in the grid. .

Mongo DB- Answering beginner’s questions

1)Q: How is the data stored in MongoDB?
A: The format of the data in Mongo is BSON, BSON is a binary-encoded serialization of JSON-like documents. BSON is designed to be lightweight, traversable, and efficient. BSON, like JSON, supports the embedding of objects and arrays within other objects and arrays. See bsonspec.org for the spec and more information in general. When we are using relational DB-s we are talking about tuples(or rows), when we are using Mongo the unit is a document.The notion of a table is substituted by the notion of collection. You could think of your database as of a set of collections holding a number of documents each of them aggregating a concept from your domain and storing it as a tree. So the linear structure of a common database became a tree-like structure.
2) Q: I’ve heard that MongoDB does not have transactions and the write mechanism is not safe. How could you comment on that?
A: First thing to consider is “safe” mode or “getLastError()”.
If you issue a “safe” write, you know that the database has received the insert and applied the write. However, MongoDB only flushes to disk every 60 seconds, so the server can fail without the data on disk.
Second thing to consider is “journaling” (v1.8+). With journaling turned on, data is flushed to the journal every 100ms. So you have a smaller window of time before failure. The drivers have an “fsync” option (check that name) that goes one step further than “safe”, it waits for acknowledgement that the data has be flushed to the disk (i.e. the journal file).However, this only covers one server. What happens if the hard drive on the server just dies? Well you need a second copy.An interesting thing is that “journaling” is the default option from 2.0+.
Third thing to consider is replication. The drivers support a “W” parameter that says “replicate this data to N nodes” before returning. If the write does not reach “N” nodes before a certain timeout, then the write fails (exception is thrown). However, you have to configure “W” correctly based on the number of nodes in your replica set. Again, because a hard drive could fail, even with journaling, you’ll want to look at replication. Then there’s replication across data centers which is too long to get into here. The last thing to consider is your requirement to “roll back”. From my understanding, MongoDB does not have this “roll back” capacity. If you’re doing a batch insert the best you’ll get is an indication of which elements failed.

3) Q: What makes the sharding and partition-tolerance possible? How do you keep track of id-s and make sure they are unique?
A: Each collection in Mongo contains in MongoId. The rules described below take the machine the document was created on into account so each document is unique throughout the distributed database.
BSON ObjectID is a 12-byte value consisting of a 4-byte timestamp (seconds since epoch), a 3-byte machine id, a 2-byte process id, and a 3-byte counter. Note that the timestamp and counter fields must be stored big endian unlike the rest of BSON. This is because they are compared byte-by-byte and we want to ensure a mostly increasing order.
TimeStamp. This is a unix style timestamp. It is a signed int representing the number of seconds before or after January 1st 1970 (UTC).
Machine. This is the first three bytes of the (md5) hash of the machine host name, or of the mac/network address, or the virtual machine id.
Pid. This is 2 bytes of the process id (or thread id) of the process generating the object id.
Increment. This is an ever incrementing value, or a random number if a counter can’t be used in the language/runtime.
4) Q: MongoDb is a non-relational DB. In RDB-s we have a well-known and defined set of mathematical rules of how to design the DB in order to avoid anomalies. What is the right design for Mongo Database?

A: There are several facts you should keep in mind:
Number 1 – There is no right strategy of dividing your aggregate into collection in mongo comparing to RDBMS-s. Each design is case-dependent.
Number 2 - despite of number 3 remark about the “no right way”, there is a general recommendation to keep your documents less than 10 MB size.
Number 3 – The consistency is part is left for yourself. The RDBM-s come with foreign key constraint mechanism which is now a developer’s headache, transaction adds up to it, etc. This is the cost of what is formally described as CAP theorem nicely described . We have both Partition – tolerance and availability for Mongo. Consistency which is the developer’s headache is the price you pay.
Credits: Amdaris LLP