Import yahoo contacts into android application - android

Hey anybody can tell me how can i import all yahoo contacts into my android application please , show me proper way dont give me yahoo api etc if u have source code kindly post it
thank you

just create a layout with webview , and use this code to get contacts.
you need oauth libraries,. and replace consumer key and scret with yours.
public class YahooContacts extends BaseActivity {
private final String TAG = "yahoo_auth";
private static final String CONSUMER_KEY = "you_consumer_key";
private static final String CONSUMER_SECRET = "your_consumer_secret";
private static final String CALLBACK_SCHEME = "http";
private static final String CALLBACK_HOST = "www.blablablao.com";
private static final String CALLBACK_URL = CALLBACK_SCHEME + "://"
+ CALLBACK_HOST;
private String AUTH_TOKEN = null;
private String AUTH_TOKEN_SECRET = null;
private String AUTH_URL = null;
private String USER_TOKEN = null;
private String ACCESS_TOKEN = null;
private String ACCESS_TOKEN_SECRET = null;
private String mUSER_GUID = null;
private WebView mWebview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.yahoo_layout);
mWebview = (WebView) findViewById(R.id.webview);
new getContactsTask().execute();
}
class getContactsTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
getAuthorizationToken();
getUserAutherization();
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
}
private void getAuthorizationToken() {
String requestPath = "https://api.login.yahoo.com/oauth/v2/get_request_token?oauth_consumer_key="
+ CONSUMER_KEY
+ "&oauth_nonce="
+ System.currentTimeMillis()
+ "x"
+ "&oauth_signature_method=PLAINTEXT"
+ "&oauth_signature="
+ CONSUMER_SECRET
+ "%26"
+ "&oauth_timestamp="
+ System.currentTimeMillis()
+ "&oauth_version=1.0"
+ "&xoauth_lang_pref=en-us"
+ "&oauth_callback=" + CALLBACK_URL;
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(requestPath);
try {
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httpget, responseHandler);
String[] data = responseBody.split("&");
AUTH_TOKEN = data[0].replace("oauth_token=", "");
AUTH_TOKEN_SECRET = data[1].replace("oauth_token_secret=", "");
AUTH_URL = data[3].replace("xoauth_request_auth_url=", "");
VIPLogger.info(TAG, "authToken" + AUTH_TOKEN);
VIPLogger.info(TAG, "authToken secret" + AUTH_TOKEN_SECRET);
} catch (Exception e) {
e.printStackTrace();
}
}
private void getUserAutherization() {
mWebview.getSettings().setJavaScriptEnabled(true);
mWebview.setWebViewClient(lWebviewClient);
mWebview.loadUrl("https://api.login.yahoo.com/oauth/v2/request_auth?oauth_token="
+ AUTH_TOKEN);
}
private void getAccessToken() {
String requestPath = "https://api.login.yahoo.com/oauth/v2/get_token?oauth_consumer_key="
+ CONSUMER_KEY
+ "&oauth_nonce="
+ System.currentTimeMillis()
+ "x"
+ "&oauth_signature_method=PLAINTEXT"
+ "&oauth_signature="
+ CONSUMER_SECRET
+ "%26"
+ AUTH_TOKEN_SECRET
+ "&oauth_timestamp="
+ System.currentTimeMillis()
+ "&oauth_version=1.0"
+ "&oauth_token="
+ AUTH_TOKEN
+ "&oauth_verifier="
+ USER_TOKEN;
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(requestPath);
try {
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httpget, responseHandler);
String[] data = responseBody.split("&");
ACCESS_TOKEN = data[0].replace("oauth_token=", "");
ACCESS_TOKEN_SECRET = data[1].replace("oauth_token_secret=", "");
mUSER_GUID = data[5].replace("xoauth_yahoo_guid=", "");
VIPLogger.info(TAG, "user guid: " + responseBody);
VIPLogger.info(TAG, "Access token: " + ACCESS_TOKEN);
getAllContacts();
} catch (Exception e) {
e.printStackTrace();
VIPLogger.error(TAG,
"error while fetching user guid and access token");
}
}
WebViewClient lWebviewClient = new WebViewClient() {
public void onPageStarted(WebView view, String url,
android.graphics.Bitmap favicon) {
if (url.contains("vipitservice")) {
mWebview.stopLoading();
int lastIndex = url.lastIndexOf("=") + 1;
VIPLogger.info(TAG, url.substring(lastIndex, url.length()));
USER_TOKEN = url.substring(lastIndex, url.length());
mWebview.setVisibility(View.GONE);
getAccessToken();
}
};
};
private void getAllContacts() {
HttpClient httpclient = new DefaultHttpClient();
String host_url = "http://social.yahooapis.com/v1/user/" + mUSER_GUID+ "/contacts";
String nonce = ""+System.currentTimeMillis();
String timeStamp = ""+(System.currentTimeMillis()/1000L);
try{
String params =
""+encode("oauth_consumer_key")+"=" + encode(CONSUMER_KEY)
+ "&"+encode("oauth_nonce")+"="+encode(nonce)
+ "&"+encode("oauth_signature_method")+"="+encode("HMAC-SHA1")
+ "&"+encode("oauth_timestamp")+"="+encode(timeStamp)
+ "&"+encode("oauth_token")+"="+ACCESS_TOKEN
+ "&"+encode("oauth_version")+"="+encode("1.0")
;
String baseString = encode("GET")+"&"+encode(host_url)+"&"+encode(params);
String signingKey = encode(CONSUMER_SECRET)+"&"+encode(ACCESS_TOKEN_SECRET);
VIPLogger.info(TAG, "base string: " + baseString);
String lSignature = computeHmac(baseString, signingKey);
VIPLogger.info(TAG, "signature: " + lSignature);
lSignature = encode(lSignature);
VIPLogger.info(TAG, "signature enacoded: " + lSignature);
String lRequestUrl = host_url
+ "?oauth_consumer_key="+CONSUMER_KEY
+ "&oauth_nonce="+nonce
+ "&oauth_signature_method=HMAC-SHA1"
+ "&oauth_timestamp="+timeStamp
+ "&oauth_token="+ACCESS_TOKEN
+ "&oauth_version=1.0"
+ "&oauth_signature="+lSignature
;
//VIPLogger.info(TAG, lRequestUrl.substring(1202));
HttpGet httpget = new HttpGet(lRequestUrl);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httpget, responseHandler);
VIPLogger.info(TAG, "contacts response: " + responseBody);
}catch(Exception e){
e.printStackTrace();
VIPLogger.error(TAG, "error while fetching user contacts");
}
}
public String computeHmac(String baseString, String key) {
try {
Mac mac = Mac.getInstance("HmacSHA1");
SecretKeySpec signingKey = new SecretKeySpec(key.getBytes("UTF-8"),
"HMAC-SHA1");
mac.init(signingKey);
byte[] digest = mac.doFinal(baseString.getBytes());
String result = Base64.encodeToString(digest, Base64.DEFAULT);
return result;
} catch (Exception e) {
e.printStackTrace();
VIPLogger.error(TAG, "error while generating sha");
}
return null;
}
public String encodeURIComponent(final String value) {
if (value == null) {
return "";
}
try {
return URLEncoder.encode(value, "utf-8")
// OAuth encodes some characters differently:
.replace("+", "%20").replace("*", "%2A")
.replace("%7E", "~");
// This could be done faster with more hand-crafted code.
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
public String encode(String input) {
StringBuilder resultStr = new StringBuilder();
for (char ch : input.toCharArray()) {
if (isUnsafe(ch)) {
resultStr.append('%');
resultStr.append(toHex(ch / 16));
resultStr.append(toHex(ch % 16));
} else {
resultStr.append(ch);
}
}
return resultStr.toString().trim();
}
private char toHex(int ch) {
return (char) (ch < 10 ? '0' + ch : 'A' + ch - 10);
}
private boolean isUnsafe(char ch) {
if (ch > 128 || ch < 0)
return true;
return " %$&+,/:;=?#<>#%".indexOf(ch) >= 0;
}
}

Related

Concatenation inside try catch

try {
final List<NetworkType> dataReceived = getData();
int i = 0;
//Array Iteration
for(final NetworkType networkType : dataReceived) {
i++;
if (i > 3) {
Toast.makeText(getApplicationContext(), "Done!!", Toast.LENGTH_SHORT);
} else {
String mCell1CID = networkType.getCell1CID();
String mCell1LAC = networkType.getCell1LAC();
String mCell1MCC = networkType.getCell1MCC();
String mCell1MNC = networkType.getCell1MNC();
String mCell1CI = networkType.getCell1CI();
String mCell1TAC = networkType.getCell1TAC();
//API requestBody
String url = "https://www.googleapis.com/geolocation/v1/geolocate?key=AIzaSyA8NAA3dUpECFn2j6pdcQT3wgqUM98UZ2Q";
String cellID = null;
String locationAreaCode = null;
if (mCell1CID.equals("") && mCell1LAC.equals("")) {
cellID = mCell1CI;
locationAreaCode = mCell1TAC;
} else if (mCell1CI.equals("") && mCell1TAC.equals("")) {
cellID = mCell1CID;
locationAreaCode = mCell1LAC;
} else {
Log.d("GeoL", "3");
}
String requestBody =
"{" +
"\"cellTowers\":[" +
"{" +
"\"cellId\" :" + cellID + "," +
"\"locationAreaCode\" :" + locationAreaCode + "," +
"\"mobileCountryCode\" :" + "\"" + mCell1MCC + "\"" + "," +
"\"mobileNetworkCode\" :" + "\"" + mCell1MNC + "\"" +
"}" +
"]" +
"}";
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
JsonObjectRequest jsObjRequest = new JsonObjectRequest
(Request.Method.POST, url, requestBody, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
JSONObject jsonObject;
try {
jsonObject = new JSONObject(String.valueOf(response));
JSONObject latitude = jsonObject.getJSONObject("location");
String lat = latitude.getString("lat");
String lng = latitude.getString("lng");
String acc = jsonObject.getString("accuracy");
if (!dataReceived.listIterator().hasNext()){
String print;
print = String.format("%s%s", print, print(lat.toString(), lng.toString(), acc.toString()));
writeToFile(print, getApplicationContext());
} else {
String print;
print = String.format("%s%s,", print, print(lat.toString(), lng.toString(), acc.toString()));
writeToFile(print, getApplicationContext());
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Response", "error" + error.toString());
}
});
queue.add(jsObjRequest);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
I need to concat the received value to the print variable.
But this the error which i receive
print needs to be initialized is what I receive.
also if declared outside the try/catch block it requires it to be final.
What to do?
just use String print = null; when you declare print
You are providing a value that is not initialized to the String.format
You need to initialize the variable "print" with what you want to be used in the String.format (for example an empty String) :
String print= ""
Or use String Builder:
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("1");
stringBuilder.append("2");
String finalString = stringBuilder.toString();

Android: Generate Oauth1 Signature in Volley Request

I am trying to add Oauth1 Authorization in my android app using volley
in the postman when i add the details like oauth_consumer_key, oauth_consumer_secret , token_key token_secret like the picture below
it generate a header like below picture and response received successfully.
Postman generated header
Authorization:OAuth oauth_consumer_key="4e77abaec9b6fcda9kjgkjgh44c2e1",oauth_token="2da9439r34104293b1gfhse2feaffca9a1",oauth_signature_method="HMAC-SHA1",oauth_timestamp="1482470443",oauth_nonce="cCbH5b",oauth_version="1.0",oauth_signature="A1QPwTATVF4x3cN0%2FN46CZrtSKw%3D"
Problem
I googled a lot to create oauth signature like postmasn created to attach volley ServerConnectionChannel but failed.
oauth_signature="A1QPwTATVF4x3cN0%2FN46CZrtSKw%3D"
Current code
public void doSendJsonRequest(final ERequest ERequest) {
requestMethod = String.valueOf(ERequest.method);
requestUrl = String.valueOf(ERequest.mReqUrl);
if(requestMethod.equals(Request.Method.GET)){
requestMethod = "GET";
}else if(requestMethod.equals(Request.Method.POST)){
requestMethod = "POST";
}else if(requestMethod.equals(Request.Method.PUT)){
requestMethod = "PUT";
}else if(requestMethod.equals(Request.Method.DELETE)){
requestMethod = "DELETE";
}
Long tsLong = System.currentTimeMillis()/1000;
final String ts = tsLong.toString();
final String kk = requestMethod+"&" + encode(requestUrl)+"&";
final String kk = encode("GET"+"&"
+ requestUrl+"&"
+ OAUTH_CONSUMER_KEY + "=\"4e77abaec9b6fcda9b11e89a9744c2e1\"&"
+OAUTH_NONCE + "=\"" + getNonce()+ "\"&"
+OAUTH_SIGNATURE_METHOD + "=\""+OAUTH_SIGNATURE_METHOD_VALUE+"\"&"
+OAUTH_TIMESTAMP + "=\"" + ts + "\"&"
+OAUTH_TOKEN +"=\"2da943934104293b167fe2feaffca9a1\"");
RequestQueue queue = VolleyUtils.getRequestQueue();
try {
JSONObject jsonObject = ERequest.jsonObject;
EJsonRequest myReq = new EJsonRequest(ERequest.method, ERequest.mReqUrl, jsonObject, createReqSuccessListener(ERequest), createReqErrorListener(ERequest)) {
public Map < String, String > getHeaders() throws AuthFailureError {
// Long tsLong = System.currentTimeMillis()/1000;
// String ts = tsLong.toString();
String strHmacSha1 = "";
String oauthStr = "";
strHmacSha1 = generateSignature(kk, oAuthConsumerSecret, oAuthTokenSecret);
strHmacSha1 = toSHA1(strHmacSha1.getBytes());
Log.e("SHA !",strHmacSha1);
oauthStr ="OAuth "+ OAUTH_CONSUMER_KEY + "=\"4e77abaec9b6fcda9b11e89a9744c2e1\","
+OAUTH_TOKEN +"=\"2da943934104293b167fe2feaffca9a1\","
+OAUTH_SIGNATURE_METHOD + "=\""+OAUTH_SIGNATURE_METHOD_VALUE+"\","
+OAUTH_TIMESTAMP + "=\"" + ts + "\","
+OAUTH_NONCE + "=\"" + getNonce()+ "\","
+OAUTH_VERSION + "=\"" + OAUTH_VERSION_VALUE + "\","
+OAUTH_SIGNATURE + "=\"" + strHmacSha1+ "\"";
Log.e("VALUE OF OAuth str",oauthStr);
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/json");
params.put("Authorization",oauthStr);
// params.put("Authorization",getConsumer().toString());
return params;
}
};
myReq.setRetryPolicy(new DefaultRetryPolicy(
DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 4,
BABTAIN_MAX_RETRIES,
BABTAIN_BACKOFF_MULT));
myReq.setHeader("Cache-Control", "no-cache");
//myReq.setHeader("Content-Type", "application/json");
queue.add(myReq);
} catch (Exception e) {
e.printStackTrace();
}
private String generateSignature(String signatueBaseStr, String oAuthConsumerSecret, String oAuthTokenSecret) {
byte[] byteHMAC = null;
try {
Mac mac = Mac.getInstance("HmacSHA1");
SecretKeySpec spec;
if (null == oAuthTokenSecret) {
String signingKey = encode(oAuthConsumerSecret) + '&';
spec = new SecretKeySpec(signingKey.getBytes(), "HmacSHA1");
} else {
String signingKey = encode(oAuthConsumerSecret) + '&' + encode(oAuthTokenSecret);
spec = new SecretKeySpec(signingKey.getBytes(), "HmacSHA1");
}
mac.init(spec);
byteHMAC = mac.doFinal(signatueBaseStr.getBytes());
} catch (Exception e) {
e.printStackTrace();
}
String base64 = Base64.encodeToString(byteHMAC, Base64.DEFAULT);
return base64.trim();
}
private String toSHA1(byte[] convertme) {
MessageDigest md = null;
try {
md = MessageDigest.getInstance("SHA-1");
}
catch(NoSuchAlgorithmException e) {
e.printStackTrace();
}
return byteArrayToHexString(md.digest(convertme));
}
private String byteArrayToHexString(byte[] b) {
String result = "";
for (int i=0; i < b.length; i++)
result += Integer.toString( ( b[i] & 0xff ) + 0x100, 16).substring( 1 );
return result;
}
this code create a signature like :oauth_signature="42a611860e29e893a435b555e7a9559a704f4e94" and it failed to get autherization.
getting error like : BasicNetwork.performRequest: Unexpected response code 401 for url
?How to generate oauth_signature like postman provided using volley..
?how can i improve this code ?Is any libraries or default function to do that
?How we add oauth1 signature in volley..
Please Help.. Thank you
I just found a github example for generating signature corresponding to nonce in Oauth1 and successfully integrate into my project
here is the link : https://github.com/rameshvoltella/WoocommerceAndroidOAuth1

Sending String value as parameter is getting Force Close error in Android

i want to send text to my model class in android
and model class is as
public class ChatMessage {
int id;
String OriginalMsgThreadId;
String SenderUserInfoId;
String ReceiverUserInfoId;
String MessageStatus;// Pending-Sent-Recieved-Read
int isPending;
String MessageText;
String MediaURL;
String MediaMIMEType;
float MediaSize;
String MediaName;
String Latitude;
String Longitude;
String ThumbImage;
String SendTimeStamp;
String ReceiveTimeStamp;
public ChatMessage() {
}
public ChatMessage(String originalMsgThreadId, String senderUserInfoId, String receiverUserInfoId, String messageStatus, int isPending, String messageText, String mediaURL, String mediaMIMEType, float mediaSize, String mediaName, String latitude, String longitude, String thumbImage, String sendTimeStamp, String receiveTimeStamp) {
OriginalMsgThreadId = originalMsgThreadId;
SenderUserInfoId = senderUserInfoId;
ReceiverUserInfoId = receiverUserInfoId;
MessageStatus = messageStatus;
this.isPending = isPending;
MessageText = messageText;
MediaURL = mediaURL;
MediaMIMEType = mediaMIMEType;
MediaSize = mediaSize;
MediaName = mediaName;
Latitude = latitude;
Longitude = longitude;
ThumbImage = thumbImage;
SendTimeStamp = sendTimeStamp;
ReceiveTimeStamp = receiveTimeStamp;
}
}
and the function where i am calling ChatMessage is as
private boolean sendChatMessage(){
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
String currentDateandTime = sdf.format(new Date());
String messageText=chatText.getText().toString();
ChatMessage chatMessage = new ChatMessage(orgMsgThreadId, loginUserInfoId, receiverUserInfoId, "Sent", 1, messageText, "", "", 0 , "", "", "", "", currentDateandTime, currentDateandTime);
long messageId = db.SendMessage(chatMessage);
chatMessageAdapter.add(chatMessage);
SyncMessageToServer(chatMessage);
if(messageId != 0) {
return true;
}
else {
return false;
}
}
and here is my SyncMessageToServer method
public boolean SyncMessageToServer(ChatMessage chatMessage){
boolean sentStatus = false;
String msgText=chatMessage.getMessageText();
String fileUrl=chatMessage.getMediaURL();
int isPending = chatMessage.getIsPending();
Toast.makeText(getApplicationContext(), " = ---loginUserInfoId = " + chatMessage.getSenderUserInfoId() + " receiverUserInfoId = " + receiverUserInfoId, Toast.LENGTH_LONG).show();
chatText.setText("");
JSONObject json = null;
String str = "";
HttpResponse response;
HttpClient myClient = new DefaultHttpClient();
HttpPost myConnection = new HttpPost("http://192.168.1.2/AndroidApp/SendMessage?messageText="+msgText+"&senderUserInfoId="+loginUserInfoId+"&recieverUserInfoId="+receiverUserInfoId+"&url="+fileUrl+"&isGroupMsg="+false);
try {
response = myClient.execute(myConnection);
str = EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (ClientProtocolException e) {
Toast.makeText(getApplicationContext(),"message sending Failed!", Toast.LENGTH_LONG).show();
//e.printStackTrace();
} catch (IOException e) {
//e.printStackTrace();
}
try{
JSONArray jArray = new JSONArray(str);
// GetMessage(receiverUserInfoId);
} catch ( JSONException e) {
//e.printStackTrace();
}
return true;
}
if i am writing "How are you" then its getting force close error
but if i am writing "HowAreYou" then its running smoothly
what am i doing wrong here?
Use following code
public class ChatMessage {
int id = 0;
String OriginalMsgThreadId = "";
String SenderUserInfoId = "";
String ReceiverUserInfoId = "";
String MessageStatus = "";// Pending-Sent-Recieved-Read
int isPending = 0;
String MessageText = "";
String MediaURL = "";
String MediaMIMEType = "";
float MediaSize = 0.0f;
String MediaName = "";
String Latitude = "";
String Longitude = "";
String ThumbImage = "";
String SendTimeStamp = "";
String ReceiveTimeStamp = "";
public ChatMessage(String originalMsgThreadId, String senderUserInfoId,
String receiverUserInfoId, String messageStatus, int isPending,
String messageText, String mediaURL, String mediaMIMEType,
float mediaSize, String mediaName, String latitude,
String longitude, String thumbImage, String sendTimeStamp,
String receiveTimeStamp) {
this.OriginalMsgThreadId = originalMsgThreadId;
this.SenderUserInfoId = senderUserInfoId;
this.ReceiverUserInfoId = receiverUserInfoId;
this.MessageStatus = messageStatus;
this.isPending = isPending;
this.MessageText = messageText;
this.MediaURL = mediaURL;
this.MediaMIMEType = mediaMIMEType;
this.MediaSize = mediaSize;
this.MediaName = mediaName;
this.Latitude = latitude;
this.Longitude = longitude;
this.ThumbImage = thumbImage;
this.SendTimeStamp = sendTimeStamp;
this.ReceiveTimeStamp = receiveTimeStamp;
}
}
I have edited my SyncMessageToServer method
public boolean SyncMessageToServer(ChatMessage chatMessage){
boolean sentStatus = false;
String msgText=chatMessage.getMessageText();
String fileUrl=chatMessage.getMediaURL();
int isPending = chatMessage.getIsPending();
Toast.makeText(getApplicationContext(), " = ---loginUserInfoId = " + chatMessage.getSenderUserInfoId() + " receiverUserInfoId = " + receiverUserInfoId, Toast.LENGTH_LONG).show();
chatText.setText("");
JSONObject json = null;
String str = "";
HttpClient myClient = new DefaultHttpClient();
HttpPost myConnection = new HttpPost("http://192.168.1.2/AndroidApp/SendMessage");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("messageText", msgText));
nameValuePairs.add(new BasicNameValuePair("senderUserInfoId", loginUserInfoId));
nameValuePairs.add(new BasicNameValuePair("recieverUserInfoId", receiverUserInfoId));
nameValuePairs.add(new BasicNameValuePair("url", fileUrl));
nameValuePairs.add(new BasicNameValuePair("isGroupMsg", "false"));
myConnection.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = myClient.execute(myConnection);
str =EntityUtils.toString(response.getEntity()).toString();
} catch (ClientProtocolException e) {
Toast.makeText(getApplicationContext(),"message sending Failed!", Toast.LENGTH_LONG).show();
//e.printStackTrace();
} catch (IOException e) {
//e.printStackTrace();
}
try{
JSONArray jArray = new JSONArray(str);
// GetMessage(receiverUserInfoId);
} catch ( JSONException e) {
//e.printStackTrace();
}
return true;
}

Can't log in Facebook Chat via XMPP on Android

I've wrote a Android in App in which I want to Integrate a Chat via XMPP.
I've logged in Facebook with permission for XMPPLogin. But when I want to login in Facebook from XMPP I receive this XML Response:
RCV (1095775528): <failure xmlns='urn:ietf:params:xml:ns:xmpp-sasl'><not-authorized/></failure></stream:stream>
causing this Error:
SASL authentication failed using mechanism X-FACEBOOK-PLATFORM:
at org.jivesoftware.smack.SASLAuthentication.authenticate(SASLAuthentication.java:341)
at org.jivesoftware.smack.XMPPConnection.login(XMPPConnection.java:242)
at org.jivesoftware.smack.Connection.login(Connection.java:371)
at com.example.messenger.ChatActivity.testLogin(ChatActivity.java:240)
at com.example.messenger.ChatActivity.access$0(ChatActivity.java:189)
at com.example.messenger.ChatActivity$1$1.run(ChatActivity.java:70)
at java.lang.Thread.run(Thread.java:856)
This is how I use the Login
private void testLogin(){
ConnectionConfiguration config = new ConnectionConfiguration("chat.facebook.com", 5222, "chat.facebook.com");
Log.i("XMPP Client", "ConnectionConfig");
config.setSASLAuthenticationEnabled(true);
config.setSecurityMode(ConnectionConfiguration.SecurityMode.enabled);
config.setDebuggerEnabled(true);
Log.i("XMPP Client", "config Complete");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
config.setTruststoreType("AndroidCAStore");
config.setTruststorePassword(null);
config.setTruststorePath(null);
} else {
config.setTruststoreType("BKS");
String path = System.getProperty("javax.net.ssl.trustStore");
if (path == null)
path = System.getProperty("java.home") + File.separator + "etc"
+ File.separator + "security" + File.separator
+ "cacerts.bks";
config.setTruststorePath(path);
}
Log.i("XMPP Client", "config if else complete");
xmpp = new XMPPConnection(config);
SASLAuthentication.registerSASLMechanism("X-FACEBOOK-PLATFORM",SASLXFacebookPlatformMechanism.class);
SASLAuthentication.supportSASLMechanism("X-FACEBOOK-PLATFORM", 0);
Log.i("XMPP Client", "new Connection and sasl auth done");
try {
xmpp.connect();
Log.i("XMPPClient","Connected to " + xmpp.getHost());
} catch (XMPPException e1) {
Log.i("XMPPClient","Unable to " + xmpp.getHost());
e1.printStackTrace();
}
Log.i("XMPP Client", "xmpp connect done");
try {
String apiKey = Session.getActiveSession().getApplicationId();
String sessionKey = Session.getActiveSession().getAccessToken();
String sessionSecret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
Log.i("XMPP Client", Session.getActiveSession().getApplicationId());
xmpp.login(apiKey + "|" + sessionKey, sessionSecret , "Messenger");
Log.i("XMPPClient"," its logined ");
Log.i("Connected",""+xmpp.isConnected());
if ( xmpp.isConnected()){
Presence presence = new Presence(Presence.Type.available);
xmpp.sendPacket(presence);
}
} catch (XMPPException e) {
e.printStackTrace();
}
}
and this is my SASLXFacebookPlatformMechanism Class
package com.example.messenger;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Map;
import org.apache.harmony.javax.security.auth.callback.CallbackHandler;
import org.apache.harmony.javax.security.sasl.Sasl;
import org.jivesoftware.smack.SASLAuthentication;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.sasl.SASLMechanism;
import org.jivesoftware.smack.util.Base64;
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];
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();
}
}
Thank you for you Help :)

How to display image based on weather from drawable

i would like to display an image based on the weather.
The image that I'm getting from is from drawable.
For example :
if the code = 30, it will display rainy day icon
I'm retrieving it from
<yweather:condition text="Light Rain with Thunder" code="4" temp="25" date="Thu, 18 Jul 2013 7:58 am SGT" />
Here is my code
MainActivity.java
public class MainActivity extends Activity {
TextView weather;
ImageView image;
class MyWeather{
String conditiontext;
String conditiondate;
String numberOfForecast;
String forecast;
public String toString(){
return "\n- "
+ "Weather:" + image + "\n"
+ "Condition: " + conditiontext + "\n"
+ conditiondate +"\n"
+ "\n"
+ "number of forecast: " + numberOfForecast + "\n"
+ forecast;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
weather = (TextView)findViewById(R.id.weather);
image = (ImageView)findViewById(R.id.image);
Thread myThread = new Thread(new Runnable(){
#Override
public void run() {
String weatherString = QueryYahooWeather();
Document weatherDoc = convertStringToDocument(weatherString);
final MyWeather weatherResult = parseWeather(weatherDoc);
runOnUiThread(new Runnable(){
#Override
public void run() {
weather.setText(weatherResult.toString());
}});
}});
myThread.start();
}
private MyWeather parseWeather(Document srcDoc){
MyWeather myWeather = new MyWeather();
//<yweather:condition.../>
Node conditionNode = srcDoc.getElementsByTagName("yweather:condition").item(0);
if(conditionNode.getTextContent().equals("11")){
image.setImageResource(R.drawable.logo);
}
else {
image.setImageResource(R.drawable.old);
}
myWeather.conditiontext = conditionNode.getAttributes()
.getNamedItem("text")
.getNodeValue()
.toString();
myWeather.conditiondate = conditionNode.getAttributes()
.getNamedItem("date")
.getNodeValue()
.toString();
//Added to get elements of <yweather:forecast.../>
NodeList forecastList = srcDoc.getElementsByTagName("yweather:forecast");
myWeather.forecast = "";
if(forecastList.getLength() > 0){
myWeather.numberOfForecast = String.valueOf(forecastList.getLength());
for(int i = 0; i < forecastList.getLength(); i++){
Node forecastNode = forecastList.item(i);
myWeather.forecast +=
forecastNode
.getAttributes()
.getNamedItem("date")
.getNodeValue()
.toString() + " " +
forecastNode
.getAttributes()
.getNamedItem("text")
.getNodeValue()
.toString() +
" High: " + forecastNode
.getAttributes()
.getNamedItem("high")
.getNodeValue()
.toString() +
" Low: " + forecastNode
.getAttributes()
.getNamedItem("low")
.getNodeValue()
.toString() + "\n";
}
}else{
myWeather.numberOfForecast = "No forecast";
}
return myWeather;
}
private Document convertStringToDocument(String src){
Document dest = null;
DocumentBuilderFactory dbFactory =
DocumentBuilderFactory.newInstance();
DocumentBuilder parser;
try {
parser = dbFactory.newDocumentBuilder();
dest = parser.parse(new ByteArrayInputStream(src.getBytes()));
} catch (ParserConfigurationException e1) {
e1.printStackTrace();
Toast.makeText(MainActivity.this,
e1.toString(), Toast.LENGTH_LONG).show();
} catch (SAXException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this,
e.toString(), Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this,
e.toString(), Toast.LENGTH_LONG).show();
}
return dest;
}
private String QueryYahooWeather(){
String qResult = "";
String queryString = "http://weather.yahooapis.com/forecastrss?w=1062617&u=c";
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(queryString);
try {
HttpEntity httpEntity = httpClient.execute(httpGet).getEntity();
if (httpEntity != null){
InputStream inputStream = httpEntity.getContent();
Reader in = new InputStreamReader(inputStream);
BufferedReader bufferedreader = new BufferedReader(in);
StringBuilder stringBuilder = new StringBuilder();
String stringReadLine = null;
while ((stringReadLine = bufferedreader.readLine()) != null) {
stringBuilder.append(stringReadLine + "\n");
}
qResult = stringBuilder.toString();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this,
e.toString(), Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this,
e.toString(), Toast.LENGTH_LONG).show();
}
return qResult;
}
}
Still not working?
I made the project myself, and if you do it like this it will work. :)
The R.id and drawables are not the same, you need to change those to make it work
TextView weather;
ImageView forecast;
private static Handler mHandler = new Handler();
class MyWeather{
String conditiontext;
String conditiondate;
String numberOfForecast;
String forecast;
public String forecastToString(){
return "\n- "
+ "Weather: " +"you wanted to have something here, I just dont understand what. " + "\n"
+ "Condition: " + conditiontext + "\n"
+ conditiondate +"\n"
+ "\n"
+ "number of forecast: " + numberOfForecast + "\n"
+ forecast;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
weather = (TextView)findViewById(R.id.textView1);
forecast = (ImageView)findViewById(R.id.imageView1);
Thread myThread = new Thread(new Runnable(){
#Override
public void run() {
String weatherString = QueryYahooWeather();
Document weatherDoc = convertStringToDocument(weatherString);
final MyWeather weatherResult = parseWeather(weatherDoc);
runOnUiThread(new Runnable(){
#Override
public void run() {
weather.setText(weatherResult.forecastToString());
}});
}});
myThread.start();
}
private MyWeather parseWeather(Document srcDoc){
MyWeather myWeather = new MyWeather();
//<yweather:condition.../>
Node conditionNode = srcDoc.getElementsByTagName("yweather:condition").item(0);
String weatherCode = conditionNode.getAttributes()
.getNamedItem("code")
.getNodeValue()
.toString();
if(weatherCode.equals("28")){
mHandler.post(new Runnable() {
#Override
public void run() {
// This gets executed on the UI thread so it can safely modify
// Views
forecast.setImageResource(R.drawable.ic_launcher);
}
});
}
...
I found some problem in your code there is two image view
Image = (ImageView)findViewById(R.id.image);
Problem - : name of the image missing
ImageView foreImage = new ImageView(this);
foreImage.setImageResource(R.drawable.logo);
//Why are you using dynamic imageview
You should use Handler Thread for display image.

Categories

Resources