Wednesday, 27 August 2014

sharing with social media in android examples

This tutorial runs through the basic process of creating a share button, implementing the share Intent, passing your content, and building the chooser list.
Implementing the share Intent allows users of your apps to share content across multiple channels, including email, text messaging, social networking and more. You can give your users a good level of control over how they wish to share your content by letting them select from the list of sharing applications available on their own devices.
If you already have an application you want to implement sharing with, you can use it. If not, create a new project in your Android IDE. In Eclipse, choose "File," "New," "Project" then "Android Project." Fill in your project details and click "Finish." your new app's details will appear in the workspace.
Creating a New Android Project in Eclipse
If you already have an Activity in your Android app that you plan on launching the share Intent from, open it in your IDE's editor area. Otherwise, you can use the main class for your new app or create a new class, making it an Activity so that you can include a button to launch your sharing Intent. Make your class extend the Activity class and include an "onCreate" method in which you can build your user interface elements.
You can launch your sharing Intent on any user action, such as pressing an options or context menu item. The following Java code creates an image button, inside the "onCreate" method of the Activity:
1
2
3
ImageButton sharingButton = new ImageButton(this);
sharingButton.setLayoutParams(new ViewGroup.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
sharingButton.setImageResource(R.drawable.sharing);
This creates a button based on the Android ImageButton class, which the Activity will need to import. This code refers to an image saved with the file-name "sharing" which is stored the drawable folder of the application resources. You can use your own image and alter the code to reflect its name. Alternatively, you can create a standard button with text rather than an image.
Depending on which type of button you're using to launch your Intent, you may need to implement a listener function. For the image button, you can add the following code:
1
2
3
4
5
sharingButton.setOnClickListener(new View.OnClickListener() {  
public void onClick(View v) {
shareIt();
}
});
This code specifies a method for the application to call when users press the share button. By including the code in a dedicated method, you can call on the sharing functionality from multiple locations in your code, such as from the "onContextItemSelected" method for long-presses or the "onOptionsItemSelected" for option menu button presses.
Add a new method to your Activity, matching the name specified in your button listener method, as follows:
1
2
3
private void shareIt() {
//sharing implementation here
}
This method will contain the implementation code for sharing content from your app. You can choose to pass parameters to the method if this suits your project.
Create the sharing Intent. Add the following Java code inside your sharing method, creating an Intent object with the send action type:
1
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
Option List to Appear on Pressing the Share Button
Set a MIME type for the content you're sharing. This will determine which applications the chooser list presents to your users. Plain text, HTML, images and videos are among the common types to share. The following Java code demonstrates sending plain text:
1
sharingIntent.setType("text/plain");
This is a flexible option, as you can send plain text reliably through many different channels.
It is possible to target specific applications using the "setType" method, but this can be a risky strategy, potentially causing problems if the user does not have those particular apps installed. By keeping the sharing function as generic as possible, you give your users control over how they want to share your content. Sticking to the standard behaviour for sharing in Android applications also creates an intuitive user experience.
You can pass various elements of your sharing content to the send Intent, including subject, text / media content, and addresses to copy to in the case of email sharing. This Java code builds a string variable to hold the body of the text content to share:
1
String shareBody = "Here is the share content body";
You can of course build the content using variables and methods within your application.
Remember that some of your content will not appear when the user chooses certain channels. For example, if you set a subject, it will not appear if the user chooses to share using text messaging, and anything over 140 characters will be cropped if the user chooses Twitter.
Scrolling Through the Chooser List for Sharing a Web page
Pass your sharing content to the "putExtra" method of the Intent class using the following Java code:
1
2
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Subject Here");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
This code first adds a subject to the sharing content, then adds the text body by referring to the string variable
Now that you have defined the content to share when the user presses the share button, you simply have to instruct Android to let the user choose their sharing medium. Add the following code inside your share method:
1
startActivity(Intent.createChooser(sharingIntent, "Share via"));
This code passes the name of the sharing Intent along with a title to display at the top of the chooser list. This example uses "Share via" which is a standard option you may have seen in existing apps. However, you can choose a title to suit your own application.
When the user chooses an application from the list, your share content will be passed to that application. For example, if the user chooses an email application, any subject you specified will be automatically populated in the subject field. The user will be able to edit the content before sending it if they wish to do so.
The Sharing Content Passed to the Gmail Application
The process of implementing a share Intent in your Android applications is not a complex one. However, the bigger challenge is choosing your sharing content in a way that serves the purpose of your application, while keeping it user-friendly. For example, you can't share the same content in a text message or tweet that you could send using email. For this reason it's best to keep your sharing content as general as possible, so that the function will be as effective for Twitter and Facebook as it is for Gmail and email.
 I am refer http://code.tutsplus.com/tutorials/android-sdk-implement-a-share-intent--mobile-8433  this site

Tuesday, 3 June 2014

Universal JSON parsing

package YOUR PROJECT NAME.utils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

   // constructor
   public JSONParser() {

   }

   public JSONObject getJSONFromUrl(String url_str) {
    InputStream is = null;
JSONObject jObj = null;
String json = "";
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 50000);
HttpConnectionParams.setSoTimeout(httpParams,50000);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParams);

try {
Log.v("url str",url str);

HttpGet httpGet = new HttpGet(url_str);

HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();

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();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}

// try parse the string to a JSON object
try {

jObj = new JSONObject(json);
System.out.println(jObj);

} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}

return jObj;
   }

}

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();
            }
        }
    };
}