I just developed on twitter integration app for android 2.3 using twitter4j, but now I want to use this app for android 4.0 and I have to change my app because it dosen't work,
I want to import mu currentUset variables like: screen_name, user_id, and profile_image_url too! And then i just want to import my followers and followings.
Can someone help me please? I was desesperated! I was goggling but I don't have any answer about this.
add this code in your main_activity
private TwitterApp mTwitter;
private static final String CONSUMER_KEY = "your consumer key";
private static final String CONSUMER_SECRET = "your consumer secret key";
private enum FROM {
TWITTER_POST, TWITTER_LOGIN
};
private enum MESSAGE {
SUCCESS, DUPLICATE, FAILED, CANCELLED
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mTwitter = new TwitterApp(this, CONSUMER_KEY, CONSUMER_SECRET);
}
public void onClick(View v) {
mTwitter.setListener(mTwLoginDialogListener);
mTwitter.resetAccessToken();
if (mTwitter.hasAccessToken() == true) {
try {
mTwitter.updateStatus(TwitterApp.MESSAGE);
postAsToast(FROM.TWITTER_POST, MESSAGE.SUCCESS);
} catch (Exception e) {
if (e.getMessage().toString().contains("duplicate")) {
postAsToast(FROM.TWITTER_POST, MESSAGE.DUPLICATE);
}
e.printStackTrace();
}
mTwitter.resetAccessToken();
} else {
mTwitter.authorize();
}
}
private void postAsToast(FROM twitterPost, MESSAGE success) {
switch (twitterPost) {
case TWITTER_LOGIN:
switch (success) {
case SUCCESS:
Toast.makeText(this, "Login Successful", Toast.LENGTH_LONG)
.show();
break;
case FAILED:
Toast.makeText(this, "Login Failed", Toast.LENGTH_LONG).show();
default:
break;
}
break;
case TWITTER_POST:
switch (success) {
case SUCCESS:
Toast.makeText(this, "Posted Successfully", Toast.LENGTH_LONG)
.show();
break;
case FAILED:
Toast.makeText(this, "Posting Failed", Toast.LENGTH_LONG)
.show();
break;
case DUPLICATE:
Toast.makeText(this,
"Posting Failed because of duplicate message...",
Toast.LENGTH_LONG).show();
default:
break;
}
break;
}
}
private TwDialogListener mTwLoginDialogListener = new TwDialogListener() {
#Override
public void onError(String value) {
postAsToast(FROM.TWITTER_LOGIN, MESSAGE.FAILED);
Log.e("TWITTER", value);
mTwitter.resetAccessToken();
}
#Override
public void onComplete(String value) {
try {
mTwitter.updateStatus(TwitterApp.MESSAGE);
postAsToast(FROM.TWITTER_POST, MESSAGE.SUCCESS);
} catch (Exception e) {
if (e.getMessage().toString().contains("duplicate")) {
postAsToast(FROM.TWITTER_POST, MESSAGE.DUPLICATE);
}
e.printStackTrace();
}
mTwitter.resetAccessToken();
}
};
you can proceed from Here
Hope It will work for you
You can use Twitter Helper for integrating Twitter into your Android app. Its very simple.
Related
I use a ErrorDecoder to return the right exception rather than a 500 status code.
Is there a way to retrieve the original message inside the decoder. I can see that it is inside the FeignException, but not in the decode method. All I have is the 'status code' and a empty 'reason'.
public class CustomErrorDecoder implements ErrorDecoder {
private final ErrorDecoder errorDecoder = new Default();
#Override
public Exception decode(String s, Response response) {
switch (response.status()) {
case 404:
return new FileNotFoundException("File no found");
case 403:
return new ForbiddenAccessException("Forbidden access");
}
return errorDecoder.decode(s, response);
}
}
Here the original message : "message":"Access to the file forbidden"
feign.FeignException: status 403 reading ProxyMicroserviceFiles#getUserRoot(); content:
{"timestamp":"2018-11-28T17:34:05.235+0000","status":403,"error":"Forbidden","message":"Access to the file forbidden","path":"/root"}
Also I use my FeignClient interface like a RestController so I don't use any other Controler populated with the proxy that could encapsulate the methods calls.
#RestController
#FeignClient(name = "zuul-server")
#RibbonClient(name = "microservice-files")
public interface ProxyMicroserviceFiles {
#GetMapping(value = "microservice-files/root")
Object getUserRoot();
#GetMapping(value = "microservice-files/file/{id}")
Object getFileById(#PathVariable("id") int id);
}
Here is a solution, the message is actually in the response body as a stream.
package com.clientui.exceptions;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.io.CharStreams;
import feign.Response;
import feign.codec.ErrorDecoder;
import lombok.*;
import java.io.*;
public class CustomErrorDecoder implements ErrorDecoder {
private final ErrorDecoder errorDecoder = new Default();
#Override
public Exception decode(String s, Response response) {
String message = null;
Reader reader = null;
try {
reader = response.body().asReader();
//Easy way to read the stream and get a String object
String result = CharStreams.toString(reader);
//use a Jackson ObjectMapper to convert the Json String into a
//Pojo
ObjectMapper mapper = new ObjectMapper();
//just in case you missed an attribute in the Pojo
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
//init the Pojo
ExceptionMessage exceptionMessage = mapper.readValue(result,
ExceptionMessage.class);
message = exceptionMessage.message;
} catch (IOException e) {
e.printStackTrace();
}finally {
//It is the responsibility of the caller to close the stream.
try {
if (reader != null)
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
switch (response.status()) {
case 404:
return new FileNotFoundException(message == null ? "File no found" :
message);
case 403:
return new ForbiddenAccessException(message == null ? "Forbidden
access" : message);
}
return errorDecoder.decode(s, response);
}
#Getter
#Setter
#NoArgsConstructor
#AllArgsConstructor
#ToString
public static class ExceptionMessage{
private String timestamp;
private int status;
private String error;
private String message;
private String path;
}
}
If you want to get the response payload body, with the Feign exception, just use this method:
feignException.contentUTF8();
Example:
try {
itemResponse = call(); //method with the feign call
} catch (FeignException e) {
logger.error("ResponseBody: " + e.contentUTF8());
}
It is suggested to use input stream instead of reader and map it to your object.
package com.clientui.exceptions;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.io.CharStreams;
import feign.Response;
import feign.codec.ErrorDecoder;
import lombok.*;
import java.io.*;
public class CustomErrorDecoder implements ErrorDecoder {
private final ErrorDecoder errorDecoder = new Default();
#Override
public Exception decode(String s, Response response) {
String message = null;
InputStream responseBodyIs = null;
try {
responseBodyIs = response.body().asInputStream();
ObjectMapper mapper = new ObjectMapper();
ExceptionMessage exceptionMessage = mapper.readValue(responseBodyIs, ExceptionMessage.class);
message = exceptionMessage.message;
} catch (IOException e) {
e.printStackTrace();
// you could also return an exception
return new errorMessageFormatException(e.getMessage());
}finally {
//It is the responsibility of the caller to close the stream.
try {
if (responseBodyIs != null)
responseBodyIs.close();
} catch (IOException e) {
e.printStackTrace();
}
}
switch (response.status()) {
case 404:
return new FileNotFoundException(message == null ? "File no found" :
message);
case 403:
return new ForbiddenAccessException(message == null ? "Forbidden access" : message);
}
return errorDecoder.decode(s, response);
}
#Getter
#Setter
#NoArgsConstructor
#AllArgsConstructor
#ToString
public static class ExceptionMessage{
private String timestamp;
private int status;
private String error;
private String message;
private String path;
}
}
If you're like me and really just want the content out of a failed Feign call without all these custom decoders and boilerplate, there is a hacky way do this.
If we look at FeignException when it is being created and a response body exists, it assembles the exception message like so:
if (response.body() != null) {
String body = Util.toString(response.body().asReader());
message += "; content:\n" + body;
}
Therefore if you're after the response body, you can just pull it out by parsing the Exception message since it is delimited by a newline.
String[] feignExceptionMessageParts = e.getMessage().split("\n");
String responseContent = feignExceptionMessageParts[1];
And if you want the object, you can use something like Jackson:
MyResponseBodyPojo errorBody = objectMapper.readValue(responseContent, MyResponseBodyPojo.class);
I do not claim this is a smart approach or a best practice.
The original message is within the Response body, as already answered. However, we can reduce the amount of boilerplate using Java 8 Streams to read it:
public class CustomErrorDecoder implements ErrorDecoder {
private final ErrorDecoder errorDecoder = new Default();
#Override
public Exception decode(String s, Response response) {
String body = "4xx client error";
try {
body = new BufferedReader(response.body().asReader(StandardCharsets.UTF_8))
.lines()
.collect(Collectors.joining("\n"));
} catch (IOException ignore) {}
switch (response.status()) {
case 404:
return new FileNotFoundException(body);
case 403:
return new ForbiddenAccessException(body);
}
return errorDecoder.decode(s, response);
}
}
Some refactoring and code style on accepted answer:
#Override
#SneakyThrows
public Exception decode(String methodKey, Response response) {
String message;
try (Reader reader = response.body().asReader()) {
String result = StringUtils.toString(reader);
message = mapper.readValue(result, ErrorResponse.class).getMessage();
}
if (response.status() == 401) {
return new UnauthorizedException(message == null ? response.reason() : message);
}
if (response.status() == 403) {
return new ForbiddenException(message == null ? response.reason() : message);
}
return defaultErrorDecoder.decode(methodKey, response);
}
I have a java and .Net solution, but now i need to implement in Dart please help me out.
This is may java source
private Handler handler;
private int iCounter =1;
public StartQuickClient(int InstanceId)
{
try
{
handler = MarketData.GetInstance();
handler.setEventHandler(this);
handler.setAddress("122.184.137.44");
handler.setPort(9898);
handler.setUserCredentials("PREM", "xxxxx");
if (handler.connect())
{
System.out.println("Connect initiated "+ InstanceId);
}
else
{
System.out.println("Connect failed ");
}
}
catch (Exception e)
{
}
}
public static void main(String[] args) {
Random rnd = new Random();
int InstanceId = rnd.nextInt(9999);
StartQuickClient startQuickClient = new StartQuickClient(InstanceId);
}
This is the connect method:
public boolean connect()
{
try {
if (quickEvent == null) {
throw new Exception("No event handler is set, will not initiate the connection");
}
if (configuration.SERVER_ADDRESS == null) {
throw new Exception("Blank Server Address");
}
if (configuration.SERVER_PORT <= 0) {
throw new Exception("Blank Server Port");
}
tcpConnection = new TcpConnection(this, configuration);
if (isNewVersionAuthentication) {
tcpConnection.enableNewversionAuthentication();
}
tcpConnection.connect();
} catch (Exception e) {
e.printStackTrace();
mLog.error("No event handler is set and Blank Server Address,Port will not initiate the connection :" + e.getMessage());
return false;
}
return true;
}
please help me out if any one knows, i am new for dart,need any plug or how to do
I am trying to get a message from the MQTT Broker using the Android service, but it does not work.
The library used is the Paho MQTT library, and the source code is as follows.
final MqttConnectOptions hIoTConnectionOptions = new MqttConnectOptions();
hIoTConnectionOptions.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1);
hIoTConnectionOptions.setAutomaticReconnect(true);
hIoTConnectionOptions.setCleanSession(false);`
try {
hIoTAndroid = new MqttClient(ip_addr, clientID, new MemoryPersistence());
IMqttToken conToken = hIoTAndroid.connectWithResult(hIoTConnectionOptions);
hIoTAndroid.setCallback(MqttMessagingService.this);
conToken.setActionCallback(new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
Log.d(TAG, "onSuccess");
hIoTAndroid.setCallback(MqttMessagingService.this);
try {
IMqttToken subToken = hIoTAndroid.subscribeWithResponse(subtopic, 1);
subToken.setActionCallback(new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
Log.i(TAG, "Successfully subscribe to: " + subtopic);
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
Log.d(TAG, "Couldn't subscribe to: " + subtopic);
}
});
} catch (MqttException | NullPointerException ex) {
ex.printStackTrace();
}
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
Log.d(TAG, "Failed Connection");
}
});
} catch (MqttException ex) {
Log.d(getClass().getCanonicalName(), "Connection attempt failed with reason code = " + ex.getReasonCode() + ":" + ex.getCause());
}
#Override
public void connectComplete(boolean reconnect, String serverURI) {
Log.d(TAG, "Connection is established....");
}
#Override
public void connectionLost(Throwable cause) {
Log.d(TAG, "The Connection was lost,,");
}
#Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
Log.i(TAG, new String(message.getPayload()));
}
#Override
public void deliveryComplete(IMqttDeliveryToken token) {
Log.d(TAG, "Sent Message !");
}
The publish and deliveryComplete functions work fine, but the subscribe function and messagArrived do not work. Why?
I have write this simple code for getting tweets from twitter
public static void main(String[] args) throws TwitterException {
// TODO code application logic here
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey("**********")
.setOAuthConsumerSecret("**************")
.setOAuthAccessToken("***************")
.setOAuthAccessTokenSecret("**************");
TwitterFactory tf= new TwitterFactory(cb.build());
twitter4j.Twitter tw= tf.getInstance();
List<Status> statuses = tw.getHomeTimeline();
for(Status status1 : statuses){
System.out.println(status1.getUser().getName()+ " : "+ status1.getText());
}
But I want to get about 4000 tweets in urdu language. I don't know how to do. please help me
With that code you will only get Tweets from the Timeline of the register user, from Twitter4j:
ResponseList getHomeTimeline() Returns the 20 most recent
statuses, including retweets, posted by the authenticating user and
that user's friends. This is the equivalent of /timeline/home on the
Web."
If you want to get at least 4000 tweets in urdu you could do several things, for example you could get the sample stream from Twitter:
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey("**********")
.setOAuthConsumerSecret("**************")
.setOAuthAccessToken("***************")
.setOAuthAccessTokenSecret("**************");
TwitterStream twitterStream = new TwitterStreamFactory(cb.build())
.getInstance();
StatusListener listener = new StatusListener() {
#Override
public void onStatus(Status status) {
System.out.println("#"+status.getUser().getScreenName()+": "+status.getText());
// HERE YOU STORE YOUR TWEETS
}
#Override
public void onException(Exception ex) {
ex.printStackTrace();
}
#Override
public void onDeletionNotice(StatusDeletionNotice arg0) {
// TODO Auto-generated method stub
}
#Override
public void onScrubGeo(long arg0, long arg1) {
}
#Override
public void onStallWarning(StallWarning arg0) {
// TODO Auto-generated method stub
System.out.println(arg0);
}
#Override
public void onTrackLimitationNotice(int arg0) {
// TODO Auto-generated method stub
System.out.println(arg0);
}
};
twitterStream.addListener(listener);
twitterStream.sample("ur");
Until you get the 4000 tweets that you want.
You can use twitter search instead of just getting specific user's tweets. What I have done for getting tweets in Turkish language is just using twitter's advanced search feature. In my situation adding lang:tr after specified search phrase returned tweets in Turkish language to me. You can use lang:ur instead of lang:tr for getting tweets in Urdu Language.
Here is my code:
public class TwitterDataGetter implements Runnable {
private Thread twitterDataGetterThread;
final static Logger logger = Logger.getLogger(TwitterDataGetter.class);
public TwitterDataGetter() {
try {
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true);
cb.setOAuthConsumerKey("your consumer key");
cb.setOAuthConsumerSecret("your consumer secret");
cb.setOAuthAccessToken("your access token");
cb.setOAuthAccessTokenSecret("your access token secret");
cb.setIncludeEntitiesEnabled(true);
this.twitter = new TwitterFactory(cb.build()).getInstance();
logger.info("Twitter API Configuration Successful");
} catch (Exception e) {
logger.error("Twitter API Configuration Error", e);
}
}
public void getTweet(String keyword){
List<Status> statuses = null;
Query query;
QueryResult result;
try {
query = new Query(keyword + " lang:tr");
query.setCount(100);
do {
final long startTime = System.nanoTime();
result = twitter.search(query);
statuses = result.getTweets();
for (Status status : statuses) {
System.out.println(status.getText());
}
final long duration = System.nanoTime() - startTime;
if((5500 - duration/1000000) > 0){
Thread.sleep((5500 - duration/1000000));
}
} while ((query = result.nextQuery()) != null);
} catch (TwitterException e) {
logger.error("TwitterException", e);
} catch (InterruptedException e) {
logger.error("InterruptedException", e);
throw new RuntimeException(e);
}
}
#Override
public void run() {
while(true){
this.getTweet("");
}
}
public void start(){
if(twitterDataGetterThread == null){
twitterDataGetterThread = new Thread(this, "Twitter Thread");
}
twitterDataGetterThread.start();
logger.info("Twitter Thread started");
}
}
Calling getTweet(String keyword) method with empty string returns latest tweets in your language without filtering them with any keyword.
Hope it helps.
PS: you can also check search results for your language from this link https://twitter.com/search?f=tweets&vertical=default&q=lang%3Aur
I want to create a group to make the current device tablet as the access point, however in the callback method onGroupInfoAvailable() I got a null pointer of group. Why?
manager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
channel = manager.initialize(this, getMainLooper(), null);
manager.createGroup(channel, new ActionListener() {
#Override
public void onSuccess() {
manager.requestGroupInfo(channel, new GroupInfoListener() {
public void onGroupInfoAvailable(WifiP2pGroup group) {
if(group != null)
Toast.makeText(SasetBladderPadActivity.this, "Group Passphrase: "
+ group.getPassphrase(), Toast.LENGTH_LONG).show();
else
Toast.makeText(SasetBladderPadActivity.this, "Group is null ",
Toast.LENGTH_LONG).show();
}
});
}
#Override
public void onFailure(int arg0) {
// TODO Auto-generated method stub
Toast.makeText(SasetBladderPadActivity.this, "Create group failed: " + arg0, \
Toast.LENGTH_LONG).show();
}
});
I think you need to implement the grouplistener and then #override the ongroupinfoavailable method. On success is just the asyn call. Actual callback needs to be modified.
Yes, the group is created but not shown. I will suggest to do it with the trick of implementing countdowntimer(or you may use any other timer) to start the requestGroupInfo() after a second. The modified code will be:
manager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
channel = manager.initialize(this, getMainLooper(), null);
manager.createGroup(channel, new ActionListener() {
#Override
public void onSuccess() {
new CountDownTimer(1000, 1000) {
public void onTick(long millisUntilFinished) {}
public void onFinish() {
manager.requestGroupInfo(channel, new GroupInfoListener() {
public void onGroupInfoAvailable(WifiP2pGroup group) {
if(group != null)
Toast.makeText(SasetBladderPadActivity.this, "Group Passphrase: "
+ group.getPassphrase(), Toast.LENGTH_LONG).show();
else
Toast.makeText(SasetBladderPadActivity.this, "Group is null ",
Toast.LENGTH_LONG).show();
}
});
}
}.start();
}
#Override
public void onFailure(int arg0) {
...