I'm doing linkedin integration for sharing the data in android, after giving the username and password and clicked on "sign in and allow" button i'm not able to move to the next page instead coming back to the previous page, and also data not posted on the wall, i tried out many tutorials, links, but could not findout my mistake and struggling alot, can anyone please help me.
here's my MainActivity code
public class MainActivity extends Activity {
public static final String CONSUMER_KEY = "key";
public static final String CONSUMER_SECRET = "secret";
public static final String APP_NAME = "rebuix";
public static final String OAUTH_CALLBACK_SCHEME = "x-oauthflow-linkedin";
public static final String OAUTH_CALLBACK_HOST = "litestcalback";
public static final String OAUTH_CALLBACK_URL = OAUTH_CALLBACK_SCHEME + "://" + OAUTH_CALLBACK_HOST;
LinkedInOAuthService oAuthService = LinkedInOAuthServiceFactory
.getInstance().createLinkedInOAuthService(CONSUMER_KEY,
CONSUMER_SECRET);
LinkedInApiClientFactory factory = LinkedInApiClientFactory
.newInstance(CONSUMER_KEY, CONSUMER_SECRET);
LinkedInRequestToken liToken;
LinkedInApiClient client;
#SuppressLint({ "NewApi", "NewApi", "NewApi" })
Button btnLinkedin;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
Button btnLinkedinMain = (Button) findViewById(R.id.btnLinkedin);
btnLinkedinMain.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (v.getId() == R.id.btnLinkedin) {
oAuthService = LinkedInOAuthServiceFactory.getInstance()
.createLinkedInOAuthService(Constants.CONSUMER_KEY,
Constants.CONSUMER_SECRET);
System.out.println("oAuthService : " + oAuthService);
factory = LinkedInApiClientFactory.newInstance(
Constants.CONSUMER_KEY, Constants.CONSUMER_SECRET);
liToken = oAuthService
.getOAuthRequestToken(Constants.OAUTH_CALLBACK_URL);
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(liToken
.getAuthorizationUrl()));
i.putExtra( "sms_body", false );
try
{
startActivity(i);
} catch (ActivityNotFoundException e) {
// Display some sort of error message here.
}
}
}
protected void onNewIntent(Intent intent) {
try {
linkedInImport(intent);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
private void linkedInImport(Intent intent) {
String verifier = intent.getData().getQueryParameter("oauth_verifier");
System.out.println("liToken " + liToken);
System.out.println("verifier " + verifier);
LinkedInAccessToken accessToken = oAuthService.getOAuthAccessToken(
liToken, verifier);
client = factory.createLinkedInApiClient(accessToken);
// client.postNetworkUpdate("LinkedIn Android app test");
Person profile = client.getProfileForCurrentUser(EnumSet.of(
ProfileField.ID, ProfileField.FIRST_NAME,
ProfileField.LAST_NAME, ProfileField.HEADLINE));
System.out.println("First Name :: " + profile.getFirstName());
System.out.println("Last Name :: " + profile.getLastName());
System.out.println("Head Line :: " + profile.getHeadline());
};
});
}
}
try out this tutorial...you will get message post feature in this tutorial..and for step by step integration in your app see this link... http://code.google.com/p/socialauth-android/wiki/Linkedin
https://github.com/srivastavavivek1987/LinkedIn-Connection-in-Android
Related
i'm new in android and i'm trying to pass a string from a TextView from the MainActivity to the Client.java class without activity.
I'm actually trying to make it doing in MainActivity :
Intent i = new Intent(MainActivity.this, Client.class);
i.putExtra("STRING_I_NEED", String.valueOf(indr));
While in Client :
Context context;
Intent intent = ((Activity) context).getIntent();
static Bundle getIp = getIntent.getExtra("STRING_I_NEED");
public static final Bundle SERVERIP = getIp;
But that's saying "
Cannot resolve symbol "getIntent" in the string
static Bundle getIp = getIntent.getExtra("STRING_I_NEED");
Client code:
public class Client {
private static String mIP= "";
private String serverMessage;
public static final String SERVERIP = mIP;
public static final int SERVERPORT = 4444;
private OnMessageReceived mMessageListener = null;
private boolean mRun = false;
PrintWriter out;
BufferedReader in;
public void setIp(String _IP) {
mIP = _IP;
}
public Client(OnMessageReceived listener) {
mMessageListener = listener;
}
public void sendMessage(String message){
if (out != null && !out.checkError()) {
out.println(message);
out.flush();
}
}
public void stopClient(){
mRun = false;
}
public void run() {
mRun = true;
try {
InetAddress serverAddr = InetAddress.getByName(String.valueOf(SERVERIP));
Log.e("TCP Client", "C: Connecting...");
Socket socket = new Socket(serverAddr, SERVERPORT);
try {
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
Log.e("TCP Client", "C: Sent.");
Log.e("TCP Client", "C: Done.");
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (mRun) {
serverMessage = in.readLine();
if (serverMessage != null && mMessageListener != null) {
mMessageListener.messageReceived(serverMessage);
}
serverMessage = null;
}
Log.e("RESPONSE FROM SERVER", "S: Received Message: '" + serverMessage + "'");
} catch (Exception e) {
Log.e("TCP", "S: Error", e);
} finally {
socket.close();
}
} catch (Exception e) {
Log.e("TCP", "C: Error", e);
}
}
public interface OnMessageReceived {
void messageReceived(String message);
}
}
And here is the MainActivity :
public class MainActivity extends AppCompatActivity {
Server server;
Client client;
public static String message,ippi;
public static TextView terminale,indr,msg;
TextView log;
DataBaseHandler myDB;
allert Allert;
SharedPreferences prefs;
String s1 = "GAB Tamagnini SRL © 2017 \n" +
"Via Beniamino Disraeli, 17,\n" +
"42124 Reggio Emilia \n" +
"Telefono: 0522 / 38 32 22 \n" +
"Fax: 0522 / 38 32 72 \n" +
"Partita IVA, Codice Fiscale \n" +
"Reg. Impr. di RE 00168780351 \n" +
"Cap. soc. € 50.000,00 i.v. \n" + "" +
"REA n. RE-107440 \n" +
"presso C.C.I.A.A. di Reggio Emilia";
ImageButton settings,helps,allerts,home;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Utils.darkenStatusBar(this, R.color.colorAccent);
server = new Server(this);
myDB = DataBaseHandler.getInstance(this);
new connectTask().execute("");
msg = (TextView) findViewById(R.id.msg);
log = (TextView) findViewById(R.id.log_avviso);
settings = (ImageButton) findViewById(R.id.impo);
helps = (ImageButton) findViewById(R.id.aiut);
allerts = (ImageButton) findViewById(R.id.msge);
home = (ImageButton) findViewById(R.id.gab);
terminale = (TextView) findViewById(R.id.terminal);
indr = (TextView) findViewById(R.id.indr);
Cursor cursor = myDB.fetchData();
if(cursor.moveToFirst()){
do {
indr.setText(cursor.getString(1));
terminale.setText(cursor.getString(2));
}while(cursor.moveToNext());
}
client.setIp(indr.getText().toString());
cursor.close();
server.Parti();
message = indr.getText().toString();
if (client != null) {
client.sendMessage(message);
}
home.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(MainActivity.this,Client.SERVERIP, Toast.LENGTH_LONG).show();
}
});
settings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent impostazioni = new Intent(getApplicationContext(), settingsLogin.class);
startActivity(impostazioni);
}
});
helps.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent pgHelp = new Intent(getApplicationContext(), help.class);
startActivity(pgHelp);
}
});
allerts.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Server.count = 0;
SharedPreferences prefs = getSharedPreferences("MY_DATA", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.clear();
editor.apply();
msg.setVisibility(View.INVISIBLE);
Intent pgAlert = new Intent(getApplicationContext(), allert.class);
startActivity(pgAlert);
}
});
}
public class connectTask extends AsyncTask<String,String,Client> {
#Override
protected Client doInBackground(String... message) {
//we create a TCPClient object and
client = new Client(new Client.OnMessageReceived() {
#Override
//here the messageReceived method is implemented
public void messageReceived(String message) {
//this method calls the onProgressUpdate
publishProgress(message);
}
});
client.run();
return null;
}
}
#Override
protected void onDestroy() {
super.onDestroy();
server.onDestroy();
}
}
Problem:
Since Client.java (according to you) is not an Activity type class, you cannot call/invoke Client.java using an Intent. Intent is only used for invoking: Activities, BroadcastReceiver, and Services.
Your Client.java does not extend an Activity, Broadcast, or a Service. This is the reason why you don't have the getIntent() function, or even the functions onCreate(), onReceive(),onStartCommand()oronHandleIntent()'` for that matter.
Correct way:
1. So what you have to do is create an object of that class just like any other object and call its setter. You can define a public method in you class to set the value of IP:
YourClass {
private String mIP;
public void setIp(String _IP) {
mIp = _IP;
}
}
And in the MainActivity class you can just call that method after the object is initialized:
MyClassObject.setIp("127.0.0.1");
2. Define an overloaded constructor, and set the value using it.
3. Create a public static String IP in MainActivity, assign value to it and then in your class do this to retrieve the value:
YourClass {
private String mIP;
public void getIp() {
mIP = MainActivity.IP;
}
}
In your Client class.
public void setString(String yourString){
variableToStoreStringInClass = yourString;
}
And in your MainActivity, where you want to send the string to the Client.
Client yourClient = new Client();
yourClient.setString("Enter the string");
Or you can use an static method:
In Client class:
public static void setString(String yourString){
variableToStoreStringInClass = yourString;
}
And in your MainActivity
Client.setString("Enter the string");
In your Settings activity when you set the String in that TextView also save it in a shared preference like this:
SharedPreferences prefs = this.getSharedPreferences(
"com.example.app", Context.MODE_PRIVATE);
prefs.edit().putString("IP", IP_String).apply();
And then in main activity:
SharedPreferences prefs = this.getSharedPreferences(
"com.example.app", Context.MODE_PRIVATE);
String ip = prefs.getString("IP", "AnyDefaultValue");
client.setIp(ip);
Intialize static string in MainActivity and assign textView text to that string.
In Client.java call like this MainActivity.IntializedString
Try following sample
public class Client {
Context context;
Intent intent;
String value = "";
public Client(Activity activity) {
context = activity;
intent = ((Activity) context).getIntent();
value = intent.getStringExtra("String_i_need");
}
}
I m trying to make a simple version facebook messenger.The code that i used has worked well for gtalk and requires facebook authentication to be used for chatting with facebook friends.For that, i have used SASLXFacebookPlatfromMechanism class where i will store the api token and api key along with the apisecret of my app. The problem is SASLXFacebookPlatfromMechanism.java class is full of errors which i cannot resolve at all.Here are my classes-
**MainActivity.java**
public class MainActivity extends ActionBarActivity {
private ArrayList<String> messages = new ArrayList();
private Handler mHandler = new Handler();
private SettingsDialog mDialog;
private EditText mRecipient;
private EditText mSendText;
private ListView mList;
private XMPPConnection connection;
/**
* Called with the activity is first created.
*/
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
Log.i("XMPPClient", "onCreate called");
setContentView(R.layout.activity_main);
mRecipient = (EditText) this.findViewById(R.id.recipient);
Log.i("XMPPClient", "mRecipient = " + mRecipient);
mSendText = (EditText) this.findViewById(R.id.sendText);
Log.i("XMPPClient", "mSendText = " + mSendText);
mList = (ListView) this.findViewById(R.id.listMessages);
Log.i("XMPPClient", "mList = " + mList);
setListAdapter();
// Dialog for getting the xmpp settings
mDialog = new SettingsDialog(this);
// Set a listener to show the settings dialog
Button setup = (Button) this.findViewById(R.id.setup);
setup.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
mHandler.post(new Runnable() {
public void run() {
mDialog.show();
}
});
}
});
// Set a listener to send a chat text message
Button send = (Button) this.findViewById(R.id.send);
send.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
try
{
String to = mRecipient.getText().toString();
String text = mSendText.getText().toString();
Log.i("XMPPClient", "Sending text [" + text + "] to [" + to + "]");
Message msg = new Message(to, Message.Type.chat);
msg.setBody(text);
connection.sendPacket(msg);
messages.add(connection.getUser() + ":");
messages.add(text);
setListAdapter();
}catch(Exception e)
{
Toast.makeText(MainActivity.this, "Error="+e.getMessage(), Toast.LENGTH_LONG).show();
}
}
});
}
/**
* Called by Settings dialog when a connection is establised with the XMPP server
*
* #param connection
*/
public void setConnection (XMPPConnection connection) {
this.connection = connection;
if (connection != null) {
// Add a packet listener to get messages sent to us
PacketFilter filter = new MessageTypeFilter(Message.Type.chat);
connection.addPacketListener(new PacketListener() {
public void processPacket(Packet packet) {
Message message = (Message) packet;
if (message.getBody() != null) {
String fromName = StringUtils.parseBareAddress(message.getFrom());
Log.i("XMPPClient", "Got text [" + message.getBody() + "] from [" + fromName + "]");
messages.add(fromName + ":");
messages.add(message.getBody());
// Add the incoming message to the list view
mHandler.post(new Runnable() {
public void run() {
setListAdapter();
}
});
}
}
}, filter);
}
}
private void setListAdapter
() {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.multi_line_list_item,
messages);
mList.setAdapter(adapter);
}
}
SettingsDialog.java
public class SettingsDialog extends Dialog implements android.view.View.OnClickListener {
private MainActivity xmppClient;
public SettingsDialog(MainActivity xmppClient) {
super(xmppClient);
this.xmppClient = xmppClient;
}
protected void onStart() {
super.onStart();
setContentView(R.layout.settings);
getWindow().setFlags(4, 4);
setTitle("XMPP Settings");
Button ok = (Button) findViewById(R.id.ok);
ok.setOnClickListener(this);
}
public void onClick(View v) {
final String host = "chat.facebook.com";
final String port = ""+5222;
final String service = "chat.facebook.com";
final String username = "*****";
final String password = "****";
new Thread() {
public void run() {
// Create a connection
ConnectionConfiguration connConfig =new ConnectionConfiguration(host, Integer.parseInt(port), service);
connConfig.setSASLAuthenticationEnabled(true);
XMPPConnection connection = new XMPPConnection(connConfig);
try {
connection.connect();
Log.i("XMPPClient", "[SettingsDialog] Connected to " + connection.getHost());
} catch (Exception ex) {
Log.e("XMPPClient", "[SettingsDialog] Failed to connect to " + connection.getHost());
Log.e("XMPPClient", ex.toString());
xmppClient.setConnection(null);
}
try {
connection.login(username, password);
Log.i("XMPPClient", "Logged in as " + connection.getUser());
// Set the status to available
Presence presence = new Presence(Presence.Type.available);
connection.sendPacket(presence);
xmppClient.setConnection(connection);
} catch (XMPPException ex) {
Log.e("XMPPClient", "[SettingsDialog] Failed to log in as " + username);
Log.e("XMPPClient", ex.toString());
xmppClient.setConnection(null);
}
}
}.start();
dismiss();
}
private String getText(int id) {
EditText widget = (EditText) this.findViewById(id);
return widget.getText().toString();
}
}
SASLXFacebookPlatformMechanism.java
public class SASLXFacebookPlatformMechanism extends SASLMechanism
{
private static final String NAME = "X-FACEBOOK-PLATFORM";
private String apiKey = "";
private String applicationSecret = "";
private String sessionKey = "";
/**
* Constructor.
*/
public SASLXFacebookPlatformMechanism(SASLAuthentication saslAuthentication)
{
super(saslAuthentication);
}
#Override
protected void authenticate() throws IOException, XMPPException
{
getSASLAuthentication().send(new AuthMechanism(NAME, ""));
}
#Override
public void authenticate(String apiKeyAndSessionKey, String host,
String applicationSecret) throws IOException, XMPPException
{
if (apiKeyAndSessionKey == null || applicationSecret == null)
{
throw new IllegalArgumentException("Invalid parameters");
}
String[] keyArray = apiKeyAndSessionKey.split("\\|", 2);
if (keyArray.length < 2)
{
throw new IllegalArgumentException(
"API key or session key is not present");
}
this.apiKey = keyArray[0];
this.applicationSecret = applicationSecret;
this.sessionKey = keyArray[1];
this.authenticationId = sessionKey;
this.password = applicationSecret;
this.hostname = host;
String[] mechanisms = { "DIGEST-MD5" };
Map<String, String> props = new HashMap<String, String>();
this.sc =
Sasl.createSaslClient(mechanisms, null, "xmpp", host, props,
this);
authenticate();
}
#Override
public void authenticate(String username, String host, CallbackHandler cbh)
throws IOException, XMPPException
{
String[] mechanisms = { "DIGEST-MD5" };
Map<String, String> props = new HashMap<String, String>();
this.sc =
Sasl.createSaslClient(mechanisms, null, "xmpp", host, props,
cbh);
authenticate();
}
#Override
protected String getName()
{
return NAME;
}
#Override
public void challengeReceived(String challenge) throws IOException
{
byte[] response = null;
if (challenge != null)
{
String decodedChallenge = new String(Base64.decode(challenge));
Map<String, String> parameters = getQueryMap(decodedChallenge);
String version = "1.0";
String nonce = parameters.get("nonce");
String method = parameters.get("method");
long callId = new GregorianCalendar().getTimeInMillis();
String sig =
"api_key=" + apiKey + "call_id=" + callId + "method="
+ method + "nonce=" + nonce + "session_key="
+ sessionKey + "v=" + version + applicationSecret;
try
{
sig = md5(sig);
} catch (NoSuchAlgorithmException e)
{
throw new IllegalStateException(e);
}
String composedResponse =
"api_key=" + URLEncoder.encode(apiKey, "utf-8")
+ "&call_id=" + callId + "&method="
+ URLEncoder.encode(method, "utf-8") + "&nonce="
+ URLEncoder.encode(nonce, "utf-8")
+ "&session_key="
+ URLEncoder.encode(sessionKey, "utf-8") + "&v="
+ URLEncoder.encode(version, "utf-8") + "&sig="
+ URLEncoder.encode(sig, "utf-8");
response = composedResponse.getBytes("utf-8");
}
String authenticationText = "";
if (response != null)
{
authenticationText =
Base64.encodeBytes(response, Base64.DONT_BREAK_LINES);
}
// Send the authentication to the server
getSASLAuthentication().send(new Response(authenticationText));
}
private Map<String, String> getQueryMap(String query)
{
Map<String, String> map = new HashMap<String, String>();
String[] params = query.split("\\&");
for (String param : params)
{
String[] fields = param.split("=", 2);
map.put(fields[0], (fields.length > 1 ? fields[1] : null));
}
return map;
}
private String md5(String text) throws NoSuchAlgorithmException,
UnsupportedEncodingException
{
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(text.getBytes("utf-8"), 0, text.length());
return convertToHex(md.digest());
}
private String convertToHex(byte[] data)
{
StringBuilder buf = new StringBuilder();
int len = data.length;
for (int i = 0; i < len; i++)
{
int halfByte = (data[i] >>> 4) & 0xF;
int twoHalfs = 0;
do
{
if (0 <= halfByte && halfByte <= 9)
{
buf.append((char) ('0' + halfByte));
}
else
{
buf.append((char) ('a' + halfByte - 10));
}
halfByte = data[i] & 0xF;
} while (twoHalfs++ < 1);
}
return buf.toString();
}
#Override
protected String getAuthenticationText(String arg0, String arg1, String arg2) {
// TODO Auto-generated method stub
return null;
}
#Override
protected String getChallengeResponse(byte[] arg0) {
// TODO Auto-generated method stub
return null;
}
}
The code shows error stating
"The method send(String) in the type SASLAuthentication is not applicable for arguments(Response).The constructor Response(String) is undefined"
in the line-->"getSASLAuthentication().send(new Response(authenticationText));"
I am also confused on how to use this SASLXFacebookPlatformMechanism.java class in my MainActivity.class.I have been trying to get a sense of how it works but failing.A complete guideline on how to develop a xmpp facebook chat client using asmack library would be appreciated since the internet lacks enough documentation on it.Thanks.
[I have the apikeys and apitokens,so the empty string will not remain empty]
When i rum my application it will give me error
MainActivity
public class MainActivity<XMPPConnection> extends Activity {
private ArrayList<String> messages = new ArrayList();
private Handler mHandler = new Handler();
private SettingsDialog mDialog;
private EditText mRecipient;
private EditText mSendText;
private ListView mList;
private XMPPConnection connection;
public static String setConnection;
/**
* Called with the activity is first created.
*/
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
Log.i("XMPPClient", "onCreate called");
setContentView(R.layout.activity_main);
mRecipient = (EditText) this.findViewById(R.id.recipient);
Log.i("XMPPClient", "mRecipient = " + mRecipient);
mSendText = (EditText) this.findViewById(R.id.sendText);
Log.i("XMPPClient", "mSendText = " + mSendText);
mList = (ListView) this.findViewById(R.id.listMessages);
Log.i("XMPPClient", "mList = " + mList);
setListAdapter();
// Dialog for getting the xmpp settings
mDialog = new SettingsDialog(this);
new MyTask().execute();
// Set a listener to show the settings dialog
Button setup = (Button) this.findViewById(R.id.setup);
setup.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
new MyTask().execute();
}
});
// Set a listener to send a chat text message
Button send = (Button) this.findViewById(R.id.send);
send.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String to = mRecipient.getText().toString();
String text = mSendText.getText().toString();
Log.i("XMPPClient", "Sending text [" + text + "] to [" + to + "]");
Message msg = new Message(to, Message.Type.chat);
msg.setBody(text);
((org.jivesoftware.smack.XMPPConnection) connection).sendPacket(msg);
messages.add(((org.jivesoftware.smack.XMPPConnection) connection).getUser() + ":");
messages.add(text);
setListAdapter();
}
});
}
/**
* Called by Settings dialog when a connection is establised with the XMPP server
*
* #param connection
*/
public void setConnection
(XMPPConnection
connection) {
this.connection = connection;
if (connection != null) {
// Add a packet listener to get messages sent to us
PacketFilter filter = new MessageTypeFilter(Message.Type.chat);
((Connection) connection).addPacketListener(new PacketListener() {
public void processPacket(Packet packet) {
Message message = (Message) packet;
if (message.getBody() != null) {
String fromName = StringUtils.parseBareAddress(message.getFrom());
Log.i("XMPPClient", "Got text [" + message.getBody() + "] from [" + fromName + "]");
messages.add(fromName + ":");
messages.add(message.getBody());
// Add the incoming message to the list view
mHandler.post(new Runnable() {
public void run() {
setListAdapter();
}
});
}
}
}, filter);
}
}
private void setListAdapter
() {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.multi_line_list_item,
messages);
mList.setAdapter(adapter);
}
}
Here is my MyTask class
private MainActivity<XMPPConnection> MainActivity;
private XMPPConnection setConnection;
#Override
protected String doInBackground(String... params) {
String host = "web.vlivetech.com"; //getText(R.id.host);
String port = "5222"; //
String service = "web.vlivetech.com";// getText(R.id.service);
String username ="has12345"; // getText(R.id.userid); //
String password = "123";// getText(R.id.password); //
// Create a connection
ConnectionConfiguration connConfig =
new ConnectionConfiguration(host, Integer.parseInt(port), service);
XMPPConnection connection = new XMPPConnection(connConfig);
try {
connection.connect();
Log.i("XMPPClient", "[SettingsDialog] Connected to " + connection.getHost());
} catch (XMPPException ex) {
Log.e("XMPPClient", "[SettingsDialog] Failed to connect to " + connection.getHost());
MainActivity.setConnection(null);
}
try {
connection.login(username, password);
Log.i("XMPPClient", "Logged in as " + connection.getUser());
// Set the status to available
Presence presence = new Presence(Presence.Type.available);
connection.sendPacket(presence);
**MainActivity.setConnection(connection);**
} catch (XMPPException ex) {
Log.e("XMPPClient", "[SettingsDialog] Failed to log in as " + username);
MainActivity.setConnection(null);
}
return null;
}
private String getText(int id) {
EditText widget = (EditText) this.findViewById(id);
return widget.getText().toString();
}
private EditText findViewById(int id) {
// TODO Auto-generated method stub
return null;
}
}
when i debug my code this will get the connection values but terminate on this line MainActivity.setConnection(connection);
now what i am doing wrong
getText(int host)
is returning null for host, port, service, username and password. That will not bring you very far.
I want to share text on Linkedin for that i have used below code
public class ShareWithLinkedIn extends Activity {
public static final String CONSUMER_KEY = "YOUR_COUSUMER_KEY";
public static final String CONSUMER_SECRET = "YOUR_SECRET_KEY";
public static final String APP_NAME = "SharePhotoImage";
public static final String OAUTH_CALLBACK_SCHEME = "x-oauthflow-linkedin";
public static final String OAUTH_CALLBACK_HOST = "litestcalback";
public static final String OAUTH_CALLBACK_URL = OAUTH_CALLBACK_SCHEME + "://" + OAUTH_CALLBACK_HOST;
static final String OAUTH_QUERY_TOKEN = "oauth_token";
static final String OAUTH_QUERY_VERIFIER = "oauth_verifier";
static final String OAUTH_QUERY_PROBLEM = "oauth_problem";
static final String OAUTH_PREF = "AppPreferences";
static final String PREF_TOKEN = "linkedin_token";
static final String PREF_TOKENSECRET = "linkedin_token_secret";
static final String PREF_REQTOKENSECRET = "linkedin_request_token_secret";
final LinkedInOAuthService oAuthService = LinkedInOAuthServiceFactory.getInstance().createLinkedInOAuthService(CONSUMER_KEY, CONSUMER_SECRET);
final LinkedInApiClientFactory factory = LinkedInApiClientFactory.newInstance(CONSUMER_KEY, CONSUMER_SECRET);
LinkedInRequestToken liToken;
LinkedInApiClient client;
TextView tv = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
tv = new TextView(this);
setContentView(tv);
final SharedPreferences pref = getSharedPreferences(OAUTH_PREF, MODE_PRIVATE);
final String token = pref.getString(PREF_TOKEN, null);
final String tokenSecret = pref.getString(PREF_TOKENSECRET, null);
if (token == null || tokenSecret == null) {
startAutheniticate();
} else {
LinkedInAccessToken accessToken = new LinkedInAccessToken(token, tokenSecret);
showCurrentUser(accessToken);
}
}// end method
void startAutheniticate() {
new Thread() {// added because this will make code work on post API 10
#Override
public void run() {
final LinkedInRequestToken liToken = oAuthService.getOAuthRequestToken(OAUTH_CALLBACK_URL);
final String uri = liToken.getAuthorizationUrl();
final SharedPreferences pref = getSharedPreferences(OAUTH_PREF, MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putString(PREF_REQTOKENSECRET, liToken.getTokenSecret());
editor.commit();
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
startActivity(i);
}
}.start();
}// end method
void finishAuthenticate(final Uri uri) {
new Thread() {
#Override
public void run() {
Looper.prepare();
if (uri != null && uri.getScheme().equals(OAUTH_CALLBACK_SCHEME)) {
final String problem = uri.getQueryParameter(OAUTH_QUERY_PROBLEM);
if (problem == null) {
final SharedPreferences pref = getSharedPreferences(OAUTH_PREF, MODE_PRIVATE);
final String request_token_secret = pref.getString(PREF_REQTOKENSECRET, null);
final String query_token = uri.getQueryParameter(OAUTH_QUERY_TOKEN);
final LinkedInRequestToken request_token = new LinkedInRequestToken(query_token, request_token_secret);
final LinkedInAccessToken accessToken = oAuthService.getOAuthAccessToken(request_token, uri.getQueryParameter(OAUTH_QUERY_VERIFIER));
SharedPreferences.Editor editor = pref.edit();
editor.putString(PREF_TOKEN, accessToken.getToken());
editor.putString(PREF_TOKENSECRET, accessToken.getTokenSecret());
editor.remove(PREF_REQTOKENSECRET);
editor.commit();
showCurrentUser(accessToken);
} else {
Toast.makeText(getApplicationContext(), "Application down due OAuth problem: " + problem, Toast.LENGTH_LONG).show();
finish();
}
}
Looper.loop();
}
}.start();
}// end method
void clearTokens() {
getSharedPreferences(OAUTH_PREF, MODE_PRIVATE).edit().remove(PREF_TOKEN).remove(PREF_TOKENSECRET).remove(PREF_REQTOKENSECRET).commit();
}// end method
void showCurrentUser(final LinkedInAccessToken accessToken) {
new Thread() {
#Override
public void run() {
Looper.prepare();
final LinkedInApiClient client = factory.createLinkedInApiClient(accessToken);
try {
final Person p = client.getProfileForCurrentUser();
// /////////////////////////////////////////////////////////
// here you can do client API calls ...
// client.postComment(arg0, arg1);
// client.updateCurrentStatus(arg0);
// or any other API call (this sample only check for current
// user
// and shows it in TextView)
// /////////////////////////////////////////////////////////
runOnUiThread(new Runnable() {// updating UI thread from
// different thread not a
// good idea...
public void run() {
tv.setText(p.getLastName() + ", " + p.getFirstName());
}
});
// or use Toast
// Toast.makeText(getApplicationContext(),
// "Lastname:: "+p.getLastName() + ", First name: " +
// p.getFirstName(), 1).show();
} catch (LinkedInApiClientException ex) {
clearTokens();
Toast.makeText(getApplicationContext(), "Application down due LinkedInApiClientException: " + ex.getMessage() + " Authokens cleared - try run application again.",
Toast.LENGTH_LONG).show();
finish();
}
Looper.loop();
}
}.start();
}// end method
#Override
protected void onNewIntent(Intent intent) {
finishAuthenticate(intent.getData());
}// end method
}// end class
it shows me login and allow screen which is looking like below when i click that button again same screen will be shown,, but i want like when (i click on that button it should share a text with image url)...
can any body help me to solve this problem
By below code i have done
public class ShareInLinkedIn extends Activity implements OnClickListener {
private LinkedInOAuthService oAuthService;
private LinkedInApiClientFactory factory;
private LinkedInRequestToken liToken;
private LinkedInApiClient client;
public static final String LINKEDIN_PREF = "GamePrefs";
#SuppressLint({ "NewApi", "NewApi", "NewApi" })
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.linkedin);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
oAuthService = LinkedInOAuthServiceFactory.getInstance().createLinkedInOAuthService(Constants.CONSUMER_KEY, Constants.CONSUMER_SECRET, Constants.SCOPE_PARAMS);
System.out.println("oAuthService : " + oAuthService);
factory = LinkedInApiClientFactory.newInstance(Constants.CONSUMER_KEY, Constants.CONSUMER_SECRET);
liToken = oAuthService.getOAuthRequestToken(Constants.OAUTH_CALLBACK_URL);
System.out.println("onCreate:linktoURL : " + liToken.getAuthorizationUrl());
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(liToken.getAuthorizationUrl()));
startActivity(i);
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
try {
linkedInImport(intent);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
private void linkedInImport(Intent intent) {
String verifier = intent.getData().getQueryParameter("oauth_verifier");
System.out.println("liToken " + liToken);
System.out.println("verifier " + verifier);
LinkedInAccessToken accessToken = oAuthService.getOAuthAccessToken(liToken, verifier);
//SharedPreferences settings = getSharedPreferences(LINKEDIN_PREF, MODE_PRIVATE);
// final Editor edit = settings.edit();
// edit.putString(OAuth.OAUTH_TOKEN, accessToken.getToken());
// edit.putString(OAuth.OAUTH_TOKEN_SECRET,
// accessToken.getTokenSecret());
// edit.putString("linkedin_login", "valid");
// edit.commit();
client = factory.createLinkedInApiClient(accessToken);
// client.postNetworkUpdate("LinkedIn Android app test");
Person profile = client.getProfileForCurrentUser(EnumSet.of(ProfileField.ID, ProfileField.FIRST_NAME, ProfileField.LAST_NAME, ProfileField.HEADLINE));
System.out.println("First Name :: " + profile.getFirstName());
System.out.println("Last Name :: " + profile.getLastName());
System.out.println("Head Line :: " + profile.getHeadline());
OAuthConsumer consumer = new CommonsHttpOAuthConsumer(Constants.CONSUMER_KEY, Constants.CONSUMER_SECRET);
consumer.setTokenWithSecret(accessToken.getToken(), accessToken.getTokenSecret());
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost post = new HttpPost("https://api.linkedin.com/v1/people/~/shares");
try {
consumer.sign(post);
post.setHeader("content-type", "text/XML");
String myEntity = "<share><comment>This is a test</comment><visibility><code>anyone</code></visibility></share>";
post.setEntity(new StringEntity(myEntity));
org.apache.http.HttpResponse response = httpclient.execute(post);
// Get the response
BufferedReader rd = new BufferedReader
(new InputStreamReader(response.getEntity().getContent()));
StringBuffer strBfr = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
strBfr.append(line);
}
System.out.println("Response is : "+strBfr.toString());
Toast.makeText(ShareInLinkedIn.this, strBfr.toString(), Toast.LENGTH_LONG).show();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
Constants.java
public class Constants {
public static final String CONSUMER_KEY = "YOUR_CONSUMER_KEY";
public static final String CONSUMER_SECRET = "YOUR_CONSUMER_SECRET_KEY";
public static final String OAUTH_CALLBACK_SCHEME = "x-oauthflow-linkedin";
public static final String OAUTH_CALLBACK_HOST = "litestcalback";
public static final String OAUTH_CALLBACK_URL = OAUTH_CALLBACK_SCHEME + "://" + OAUTH_CALLBACK_HOST;
public static final String SCOPE_PARAMS = "rw_nus+r_basicprofile";
}
AndroidManifiest.xml file
<activity
android:name="com.linkedin.ShareInLinkedIn"
android:launchMode="singleInstance" >
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data
android:host="litestcalback"
android:scheme="x-oauthflow-linkedin" />
</intent-filter>
</activity>
This is done based on selvin's coding, but it doesnt work for me, that is message is not getting posted on the linked wall in android. after login stays in the same page.
This is the code `public class LITestActivity extends Activity {
// /change keysssssssssssssssssssssssssssss!!!!!!!!!!
static final String CONSUMER_KEY = "key";
static final String CONSUMER_SECRET = "secret";
static final String APP_NAME = "abc";
static final String OAUTH_CALLBACK_SCHEME = "x-oauthflow-linkedin";
static final String OAUTH_CALLBACK_HOST = "litestcalback";
static final String OAUTH_CALLBACK_URL = String.format("%s://%s",
OAUTH_CALLBACK_SCHEME, OAUTH_CALLBACK_HOST);
static final String OAUTH_QUERY_TOKEN = "oauth_token";
static final String OAUTH_QUERY_VERIFIER = "oauth_verifier";
static final String OAUTH_QUERY_PROBLEM = "oauth_problem";
final LinkedInOAuthService oAuthService = LinkedInOAuthServiceFactory
.getInstance().createLinkedInOAuthService(CONSUMER_KEY,
CONSUMER_SECRET);
final LinkedInApiClientFactory factory = LinkedInApiClientFactory
.newInstance(CONSUMER_KEY, CONSUMER_SECRET);
static final String OAUTH_PREF = "LIKEDIN_OAUTH";
static final String PREF_TOKEN = "token";
static final String PREF_TOKENSECRET = "token secret";
static final String PREF_REQTOKENSECRET = "requestTokenSecret";
TextView tv = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
tv = new TextView(this);
setContentView(tv);
final SharedPreferences pref = getSharedPreferences(OAUTH_PREF,
MODE_PRIVATE);
final String token = pref.getString(PREF_TOKEN, null);
final String tokenSecret = pref.getString(PREF_TOKENSECRET, null);
if (token == null || tokenSecret == null) {
startAutheniticate();
} else {
showCurrentUser(new LinkedInAccessToken(token, tokenSecret));
}
}
void startAutheniticate() {
final LinkedInRequestToken liToken = oAuthService
.getOAuthRequestToken(OAUTH_CALLBACK_URL);
final String uri = liToken.getAuthorizationUrl();
getSharedPreferences(OAUTH_PREF, MODE_PRIVATE).edit()
.putString(PREF_REQTOKENSECRET, liToken.getTokenSecret())
.commit();
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
i.putExtra("sms_body", "Welcome to Rebuix, http://www.rebuix.com");
startActivity(i);
Toast.makeText(this,
"Successfuly posted: " ,
Toast.LENGTH_LONG).show();
}
void finishAuthenticate(final Uri uri) {
if (uri != null && uri.getScheme().equals(OAUTH_CALLBACK_SCHEME)) {
final String problem = uri.getQueryParameter(OAUTH_QUERY_PROBLEM);
if (problem == null) {
final SharedPreferences pref = getSharedPreferences(OAUTH_PREF,
MODE_PRIVATE);
final LinkedInAccessToken accessToken = oAuthService
.getOAuthAccessToken(
new LinkedInRequestToken(uri
.getQueryParameter(OAUTH_QUERY_TOKEN),
pref.getString(PREF_REQTOKENSECRET,
null)),
uri.getQueryParameter(OAUTH_QUERY_VERIFIER));
pref.edit()
.putString(PREF_TOKEN, accessToken.getToken())
.putString(PREF_TOKENSECRET,
accessToken.getTokenSecret())
.remove(PREF_REQTOKENSECRET).commit();
showCurrentUser(accessToken);
} else {
Toast.makeText(this,
"Appliaction down due OAuth problem: " + problem,
Toast.LENGTH_LONG).show();
finish();
}
}
}
void clearTokens() {
getSharedPreferences(OAUTH_PREF, MODE_PRIVATE).edit()
.remove(PREF_TOKEN).remove(PREF_TOKENSECRET)
.remove(PREF_REQTOKENSECRET).commit();
}
void showCurrentUser(final LinkedInAccessToken accessToken) {
final LinkedInApiClient client = factory
.createLinkedInApiClient(accessToken);
try {
final Person p = client.getProfileForCurrentUser();
// /////////////////////////////////////////////////////////
// here you can do client API calls ...
// client.postComment(arg0, arg1);
// client.updateCurrentStatus(arg0);
// or any other API call (this sample only check for current user
// and shows it in TextView)
// /////////////////////////////////////////////////////////
tv.setText(p.getLastName() + ", " + p.getFirstName());
} catch (LinkedInApiClientException ex) {
clearTokens();
Toast.makeText(
this,
"Appliaction down due LinkedInApiClientException: "
+ ex.getMessage()
+ " Authokens cleared - try run application again.",
Toast.LENGTH_LONG).show();
finish();
}
}
#Override
protected void onNewIntent(Intent intent) {
finishAuthenticate(intent.getData());
}
}`
Try the below URL to integration of social network like facebook, Twitter & LinkedIn