Friday, 23 May 2014

facebook Post Status From Android


You can download facebook sdk .

https://www.dropbox.com/s/5woagok3tvq2pui/FacebookSDK.rar

private void FaceBook_Sharing()
{
final Bundle params = new Bundle();




params.putString("name", "Title");
params.putString("description","Description");

params.putString("picture","Image Url");


if (Session.getActiveSession() == null|| Session.getActiveSession().isClosed())
{
Session.openActiveSession(this, true, new StatusCallback() 
{
private List<String> permissions;

@SuppressWarnings("deprecation")
@Override
public void call(Session session, SessionState state,Exception exception)
{




System.out.println("State= " + session.isOpened());

if (session.isOpened()) 
{
try 
{
permissions = session.getPermissions();
if (!permissions.contains("publish_actions")) {
Log.i("System out","come for permition in");
Session.NewPermissionsRequest newPermissionsRequest = new Session.NewPermissionsRequest(MainActivity.this, Arrays.asList("",""))
.setDefaultAudience(SessionDefaultAudience.FRIENDS);
//session.requestNewPublishPermissions(newPermissionsRequest);
}
}
catch (Exception e)
{
// TODO: handle exception
}

Log.i("System out","come for permition else");

System.out.println("Token=" + session.getAccessToken());



facebook.setAccessToken(session.getAccessToken());

session  = Session.getActiveSession();



WebDialog feedDialog = (new WebDialog.FeedDialogBuilder(MainActivity.this,session,params)).setOnCompleteListener(new OnCompleteListener() 
{

@Override
public void onComplete(Bundle values,FacebookException error)
{
if (error == null)
{
// When the story is posted, echo the success
// and the post Id.
final String postId = values.getString("post_id");
if (postId != null) {

Toast.makeText(MainActivity.this, "Posted  successfully.", Toast.LENGTH_LONG).show();

}
else 
{
// User clicked the Cancel button
Toast.makeText(MainActivity.this, "Publish cancelled", Toast.LENGTH_SHORT).show();
}
else if (error instanceof FacebookOperationCanceledException) 
{
// User clicked the "x" button
Toast.makeText(MainActivity.this, "Publish cancelled",Toast.LENGTH_SHORT).show();
else 
{
// Generic, ex: network error
Toast.makeText(MainActivity.this, "Error posting story", Toast.LENGTH_SHORT).show();
}
}

})
.build();
feedDialog.show();
}
if (exception != null) 
{
System.out.println("Some thing bad happened!");
exception.printStackTrace();
}
}

});
}
}

How to Use Facebook SDK to Post Status From Android

 Useing this link :- http://www.londatiga.net/it/how-to-use-facebook-sdk-to-post-status-from-android/


I. Register Facebook Application
To enable user to post status to Facebook, first you have to create a Facebook application:
  • Login to Facebook and go to Facebook Developer page then register your application by clicking the Create New App button on top right of the page.
    Create New Facebook App
  • Fill the App Name with your application name.
    Facebook Create New App
  • Note the App ID, we will use it later on Android code. Note that you don’t have to select how app integrate with Facebook option, just click the Save Changes button.
    Facebook App Setting
II. Android Integration
To integrate Facebook with Android, you can use official Facebook SDK for Android that can be downloaded from github page. For sample project in this tutorial, i use old version of Facebook SDK downloaded from the github page with some small modification. If you want to use the latest version, just download the SDK from the link above.
Facebook Android SDK
In my sample project, i create two packages, one for Facebook SDK and the other for application main package.
Code implementation
1. Facebook Connection (TestConnect.java)
This example shows how to connect to Facebook, display webview dialog to authorize user then save the access token and username on shared preference for later use.
?
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
public class TestConnect extends Activity {
    private Facebook mFacebook;
    private CheckBox mFacebookBtn;
    private ProgressDialog mProgress;
    private static final String[] PERMISSIONS = new String[] {"publish_stream", "read_stream", "offline_access"};
    private static final String APP_ID = "*****app id ******";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mFacebookBtn    = (CheckBox) findViewById(R.id.cb_facebook);
        mProgress       = new ProgressDialog(this);
        mFacebook       = new Facebook(APP_ID);
        SessionStore.restore(mFacebook, this);
        if (mFacebook.isSessionValid()) {
            mFacebookBtn.setChecked(true);
            String name = SessionStore.getName(this);
            name        = (name.equals("")) ? "Unknown" : name;
            mFacebookBtn.setText("  Facebook (" + name + ")");
            mFacebookBtn.setTextColor(Color.WHITE);
        }
        mFacebookBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                onFacebookClick();
            }
        });
        ((Button) findViewById(R.id.button1)).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(TestConnect.this, TestPost.class));
            }
        });
    }
    private void onFacebookClick() {
        if (mFacebook.isSessionValid()) {
            final AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage("Delete current Facebook connection?")
                   .setCancelable(false)
                   .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                       public void onClick(DialogInterface dialog, int id) {
                           fbLogout();
                       }
                   })
                   .setNegativeButton("No", new DialogInterface.OnClickListener() {
                       public void onClick(DialogInterface dialog, int id) {
                            dialog.cancel();
                            mFacebookBtn.setChecked(true);
                       }
                   });
            final AlertDialog alert = builder.create();
            alert.show();
        } else {
            mFacebookBtn.setChecked(false);
            mFacebook.authorize(this, PERMISSIONS, -1, new FbLoginDialogListener());
        }
    }
    private final class FbLoginDialogListener implements DialogListener {
        public void onComplete(Bundle values) {
            SessionStore.save(mFacebook, TestConnect.this);
            mFacebookBtn.setText("  Facebook (No Name)");
            mFacebookBtn.setChecked(true);
            mFacebookBtn.setTextColor(Color.WHITE);
            getFbName();
        }
        public void onFacebookError(FacebookError error) {
           Toast.makeText(TestConnect.this, "Facebook connection failed", Toast.LENGTH_SHORT).show();
           mFacebookBtn.setChecked(false);
        }
        public void onError(DialogError error) {
            Toast.makeText(TestConnect.this, "Facebook connection failed", Toast.LENGTH_SHORT).show();
            mFacebookBtn.setChecked(false);
        }
        public void onCancel() {
            mFacebookBtn.setChecked(false);
        }
    }
    private void getFbName() {
        mProgress.setMessage("Finalizing ...");
        mProgress.show();
        new Thread() {
            @Override
            public void run() {
                String name = "";
                int what = 1;
                try {
                    String me = mFacebook.request("me");
                    JSONObject jsonObj = (JSONObject) new JSONTokener(me).nextValue();
                    name = jsonObj.getString("name");
                    what = 0;
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                mFbHandler.sendMessage(mFbHandler.obtainMessage(what, name));
            }
        }.start();
    }
    private void fbLogout() {
        mProgress.setMessage("Disconnecting from Facebook");
        mProgress.show();
        new Thread() {
            @Override
            public void run() {
                SessionStore.clear(TestConnect.this);
                int what = 1;
                try {
                    mFacebook.logout(TestConnect.this);
                    what = 0;
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                mHandler.sendMessage(mHandler.obtainMessage(what));
            }
        }.start();
    }
    private Handler mFbHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            mProgress.dismiss();
            if (msg.what == 0) {
                String username = (String) msg.obj;
                username = (username.equals("")) ? "No Name" : username;
                SessionStore.saveName(username, TestConnect.this);
                mFacebookBtn.setText("  Facebook (" + username + ")");
                Toast.makeText(TestConnect.this, "Connected to Facebook as " + username, Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(TestConnect.this, "Connected to Facebook", Toast.LENGTH_SHORT).show();
            }
        }
    };
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            mProgress.dismiss();
            if (msg.what == 1) {
                Toast.makeText(TestConnect.this, "Facebook logout failed", Toast.LENGTH_SHORT).show();
            } else {
                mFacebookBtn.setChecked(false);
                mFacebookBtn.setText("  Facebook (Not connected)");
                mFacebookBtn.setTextColor(Color.GRAY);
                Toast.makeText(TestConnect.this, "Disconnected from Facebook", Toast.LENGTH_SHORT).show();
            }
        }
    };
}

Wednesday, 14 August 2013

Launch an activity only the first time the application starts in android

SharedPreferences prefre=this.getSharedPreferences("firstt", Context.MODE_PRIVATE);
boolean firsttimes=prefre.getBoolean("firstt", true);
if(firsttimes)
{
SharedPreferences.Editor editere=prefre.edit();
editere.putBoolean("firstt", false);
editere.commit();

thread=new Thread()
{
@Override
public void run()
{
super.run();

synchronized (this)
{
try {
wait(3000);
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
finish();
Intent intent = new Intent(MainActivity.this,LoginActivity.class);
startActivity(intent);
}
}
}
};
thread.start();
}
else
{
//MainActivity.this.finishActivity(0);
startActivity(new Intent(MainActivity.this, LoginActivity.class));
}

}
You can also see this


http://stackoverflow.com/questions/2960888/launch-an-activity-only-the-first-time-the-application-starts/18231638#18231638

Monday, 15 July 2013

marquee in android

<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"
    tools:context=".MainActivity" >

   <TextView
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       android:singleLine="true"
       android:ellipsize="marquee"
       android:marqueeRepeatLimit="marquee_forever"
       android:focusable="true"
       android:id="@+id/fd"
       android:focusableInTouchMode="true"
       android:text="http://androidresearch.wordpress.com/2012/03/17/understanding-asynctask-once-and-forever/"
       />

</LinearLayout>





Java Interview Question Answer

Java Interview Question Answer:

Java was developed by a team of computer professionals under the guidance of James
Gosling at Sun Microsystems in 1991. They wanted to give a suitable name. Initially
they called it “oak” after seeing an oak tree from their window, but after some weeks
they were discussing another name and were sipping Java coffee, so one of them
suggested the name “Java”.

Q: What is the difference between an Interface and an Abstract class?

A: An abstract class can have instance methods that implement a default behavior. An Interface can only declare constants and instance methods, but cannot implement default behavior and all methods are implicitly abstract. An interface has all public members and no implementation. An abstract class is a class which may have the usual flavors of class members (private, protected, etc.), but has some abstract methods.

Q: What is the purpose of garbage collection in Java, and when is it used?

A: The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused. A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used. 

Q: Describe synchronization in respect to multithreading.

A: With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchonization, it is possible for one thread to modify a shared variable while another thread is in the process of using or updating same shared variable. This usually leads to significant errors.  

Q: Explain different way of using thread?

A: The thread could be implemented by using runnable interface or by inheriting from the Thread class. The former is more advantageous, 'cause when you are going for multiple inheritance..the only interface can help.

Q: What are pass by reference and passby value?

A: Pass By Reference means the passing the address itself rather than passing the value. Passby Value means passing a copy of the value to be passed. 

Q: What is HashMap and Map?

A: Map is Interface and Hashmap is class that implements that.

Q: Difference between HashMap and HashTable?

A: The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesnt allow). HashMap does not guarantee that the order of the map will remain constant over time. HashMap is unsynchronized and Hashtable is synchronized. 

Q: Difference between Vector and ArrayList?

A: Vector is synchronized whereas arraylist is not.

Q: Difference between Swing and Awt?

A: AWT are heavy-weight componenets. Swings are light-weight components. Hence swing works faster than AWT.

Q: What is the difference between a constructor and a method?

A: A constructor is a member function of a class that is used to create objects of that class. It has the same name as the class itself, has no return type, and is invoked using the new operator.
A method is an ordinary member function of a class. It has its own name, a return type (which may be void), and is invoked using the dot operator.

Q: What is an Iterator?

A: Some of the collection classes provide traversal of their contents via a java.util.Iterator interface. This interface allows you to walk through a collection of objects, operating on each object in turn. Remember when using Iterators that they contain a snapshot of the collection at the time the Iterator was obtained; generally it is not advisable to modify the collection itself while traversing an Iterator.

Q: State the significance of public, private, protected, default modifiers both singly and in combination and state the effect of package relationships on declared items qualified by these modifiers.

A: public : Public class is visible in other packages, field is visible everywhere (class must be public too)
private : Private variables or methods may be used only by an instance of the same class that declares the variable or method, A private feature may only be accessed by the class that owns the feature.
protected : Is available to all classes in the same package and also available to all subclasses of the class that owns the protected feature.This access is provided even to subclasses that reside in a different package from the class that owns the protected feature.
default :What you get by default ie, without any access modifier (ie, public private or protected).It means that it is visible to all within a particular package.

Q: What is an abstract class?

A: Abstract class must be extended/subclassed (to be useful). It serves as a template. A class that is abstract may not be instantiated (ie, you may not call its constructor), abstract class may contain static data. Any class with an abstract method is automatically abstract itself, and must be declared as such.
A class may be declared abstract even if it has no abstract methods. This prevents it from being instantiated.

Q: What is static in java?

A: Static means one per class, not one for each object no matter how many instance of a class might exist. This means that you can use them without creating an instance of a class.Static methods are implicitly final, because overriding is done based on the type of the object, and static methods are attached to a class, not an object. A static method in a superclass can be shadowed by another static method in a subclass, as long as the original method was not declared final. However, you can't override a static method with a nonstatic method. In other words, you can't change a static method into an instance method in a subclass.

Q: What is final?

A: A final class can't be extended ie., final class may not be subclassed. A final method can't be overridden when its class is inherited. You can't change value of a final variable (is a constant).

Q: What if the main method is declared as private?

A: The program compiles properly but at runtime it will give "Main method not public." message.

Q: What if the static modifier is removed from the signature of the main method?

A: Program compiles. But at runtime throws an error "NoSuchMethodError". 

Q: What if I write static public void instead of public static void?

A: Program compiles and runs properly. 

Q: What if I do not provide the String array as the argument to the method?

A: Program compiles but throws a runtime error "NoSuchMethodError". 

Q: What is the first argument of the String array in main method?

A: The String array is empty. It does not have any element. This is unlike C/C++ where the first element by default is the program name.

Q: If I do not provide any arguments on the command line, then the String array of Main method will be empty or null?

A: It is empty. But not null.

Q: How can one prove that the array is not null but empty using one line of code?

A: Print args.length. It will print 0. That means it is empty. But if it would have been null then it would have thrown a NullPointerException on attempting to print args.length.

Q: What environment variables do I need to set on my machine in order to be able to run Java programs?

A: CLASSPATH and PATH are the two variables.

Q: Can an application have multiple classes having main method?

A: Yes it is possible. While starting the application we mention the class name to be run. The JVM will look for the Main method only in the class whose name you have mentioned. Hence there is not conflict amongst the multiple classes having main method.

Q: Can I have multiple main methods in the same class?

A: No the program fails to compile. The compiler says that the main method is already defined in the class.

Q: Do I need to import java.lang package any time? Why ?

A: No. It is by default loaded internally by the JVM.

Q: Can I import same package/class twice? Will the JVM load the package twice at runtime?

A: One can import the same package or same class multiple times. Neither compiler nor JVM complains abt it. And the JVM will internally load the class only once no matter how many times you import the same class.

Q: What are Checked and UnChecked Exception?

A: A checked exception is some subclass of Exception (or Exception itself), excluding class RuntimeException and its subclasses.
Making an exception checked forces client programmers to deal with the possibility that the exception will be thrown. eg, IOException thrown by java.io.FileInputStream's read() method·
Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses also are unchecked. With an unchecked exception, however, the compiler doesn't force client programmers either to catch the
exception or declare it in a throws clause. In fact, client programmers may not even know that the exception could be thrown. eg, StringIndexOutOfBoundsException thrown by String's charAt() method· Checked exceptions must be caught at compile time. Runtime exceptions do not need to be. Errors often cannot be.

Q: What is Overriding?

A: When a class defines a method using the same name, return type, and arguments as a method in its superclass, the method in the class overrides the method in the superclass.
When the method is invoked for an object of the class, it is the new definition of the method that is called, and not the method definition from superclass. Methods may be overridden to be more public, not more private. 

Q: What are different types of inner classes?

A: Nested top-level classes, Member classes, Local classes, Anonymous classes

Nested top-level classes- If you declare a class within a class and specify the static modifier, the compiler treats the class just like any other top-level class.
Any class outside the declaring class accesses the nested class with the declaring class name acting similarly to a package. eg, outer.inner. Top-level inner classes implicitly have access only to static variables.There can also be inner interfaces. All of these are of the nested top-level variety.

Member classes - Member inner classes are just like other member methods and member variables and access to the member class is restricted, just like methods and variables. This means a public member class acts similarly to a nested top-level class. The primary difference between member classes and nested top-level classes is that member classes have access to the specific instance of the enclosing class.

Local classes - Local classes are like local variables, specific to a block of code. Their visibility is only within the block of their declaration. In order for the class to be useful beyond the declaration block, it would need to implement a
more publicly available interface.Because local classes are not members, the modifiers public, protected, private, and static are not usable.