Internet on android, causing twitter4j exception? - java

I'm experimenting with twitter4j on android (new to both) coded up a simple process in java just to test it out. It downloads a users timeline and prints to screen.
I modify the code for android, but I get a TwitterException when i try to download the user timeline. I checked out the debugger and the exception is null; no information given. I've also added the Internet permission to the android manifest on previous advice. Heres the code:
package com.test;
import java.util.List;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import android.app.Activity;
import android.os.Bundle;
public class Test2 extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
List<Status> statuses = null;
Twitter api = new TwitterFactory().getInstance("USERNAME","PASSWORD");
try{
statuses = api.getUserTimeline();
}
catch(TwitterException e){
System.out.println("ERROR");
System.exit(-1);
}
for(Status s: statuses){
System.out.println(s.getText());
}
}
}
I realise this only prints to the console, just to keep it simple.
Thanks for any and all help.

Make sure you have the INTERNET permission in your AndroidManifest.xml file.
Also System.out.println() is not recommended on Android. Please use the android.util.Log class and send your debugging output to LogCat (available via adb logcat, DDMS, or the DDMS perspective in Eclipse).

Please check your timestamp. Each HttpRequest contain current timestamp, if the timestamp is wrong then it throw exception.

Related

Google Cloud Trace Opentelemetry Java example code not showing up on Google Cloud Trace Dashboard

I followed the steps on Google Cloud's Java and OpenTelemetry site (https://cloud.google.com/trace/docs/setup/java-ot) and made a simple hello world Java application locally and am trying to get my traces to show up on Google Cloud Trace using their trace exporter.
All the setup code is the same, and the program compiles and runs successfully. However, I don't see anything on the Trace dashboard. I know it is not an issue with IAM or my service account key because I ran the Python example and it shows up in Cloud Trace dashboard just fine.
Anyone have any guidance on why the Java version could be silently failing?
Thanks
package hello;
import org.joda.time.LocalTime;
import io.opentelemetry.api.GlobalOpenTelemetry;
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.trace.Tracer;
import io.opentelemetry.context.Scope;
import io.opentelemetry.api.OpenTelemetry;
import io.opentelemetry.api.common.AttributeKey;
import io.opentelemetry.api.common.Attributes;
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.trace.StatusCode;
import io.opentelemetry.api.trace.Tracer;
import io.opentelemetry.context.Scope;
import io.opentelemetry.sdk.OpenTelemetrySdk;
import io.opentelemetry.sdk.trace.SdkTracerProvider;
import io.opentelemetry.sdk.trace.export.BatchSpanProcessor;
import io.opentelemetry.exporter.logging.LoggingSpanExporter;
import io.opentelemetry.sdk.trace.export.SimpleSpanProcessor;
import io.opentelemetry.context.Context;
import io.opentelemetry.context.propagation.ContextPropagators;
import io.opentelemetry.api.metrics.LongCounter;
import io.opentelemetry.api.metrics.Meter;
import io.opentelemetry.sdk.metrics.SdkMeterProvider;
import io.opentelemetry.sdk.metrics.export.IntervalMetricReader;
import java.io.IOException;
import java.util.Random;
import com.google.cloud.opentelemetry.trace.TraceConfiguration;
import com.google.cloud.opentelemetry.trace.TraceExporter;
import java.util.Collections;
import static java.util.Collections.singleton;
import java.time.Duration;
public class HelloWorld {
private static final Random random = new Random();
private static OpenTelemetry setupTraceExporter() {
try {
TraceExporter traceExporter = TraceExporter.createWithConfiguration(
TraceConfiguration.builder().setProjectId("my-test-id").build());
// Register the TraceExporter with OpenTelemetry
return OpenTelemetrySdk.builder()
.setTracerProvider(
SdkTracerProvider.builder()
.addSpanProcessor(BatchSpanProcessor.builder(traceExporter).build())
.build())
.buildAndRegisterGlobal();
} catch (IOException e) {
System.out.println("Uncaught Exception");
System.out.println(e);
return null;
}
}
public static void main(String[] args) {
System.out.println("Starting the example application");
/* SET UP */
OpenTelemetry otel = setupTraceExporter();
/* Creating tracer */
Tracer tracer =
otel.getTracer("java foo");
Span span = tracer.spanBuilder("my span").startSpan();
// put the span into the current Context
try (Scope scope = span.makeCurrent()) {
System.out.println("Hello");
Thread.sleep(4000);
} catch (Throwable t) {
span.setStatus(StatusCode.ERROR, "error");
System.out.println(t);
} finally {
span.end();
}
System.out.println("Closing");
//otel.getSdkTracerProvider().shutdown();
}
}
After some debugging, I figured out the answer.
Seems like with this simple example, the BatchSpanProcessor is not a good idea because there is only one span that is getting traced.
SimpleSpanProcessor directly forwards the spans to Cloud Trace no matter what whereas BatchSpanProcessor waits until there is enough data before pushing to Cloud Trace. Hence why I was not seeing anything in Cloud Trace because BatchSpanProcessor hadn't registered enough spans for it to actually upload it to Google Cloud.
Span Processors Documentation
Change the following lines
return OpenTelemetrySdk.builder()
.setTracerProvider(
SdkTracerProvider.builder()
.addSpanProcessor(SimpleSpanProcessor.create(traceExporter))
.build())
.buildAndRegisterGlobal();
Hope this helps others!

SdkManager class is not available in latest android SDK

Downloaded latest android Studio (android-studio-bundle-162.3871768-windows).
We were using com.android.sdklib.SdkManager class in our software but in latest Android Studio I'm not able to find the above mentioned class in any jar present inside the tools\lib folder.
Can anyone suggest what is the better alternative for this?
if you want to get a list of all the targets installed for knowledge, then you can just simply run the SDK manager. But since you want to call the getTargets() method, it means you need it for other purposes. check up the documentation on the android studio web page to find out if it the class you are searching for exists and the location of its jar file.
We can find the soure code of all the android classes in the below link.
https://javalibs.com/artifact/com.android.tools/sdklib?className=com.android.sdklib.tool.SdkManagerCli&source
SdkManagerCli class have equivalent method listPackages()which will list the packages.
We need to import sdklib-25.3.2.jar, repository-25.3.2.jar and common-25.3.2.jar to project.
Below is the working code for listing packages:-
import java.io.File;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.TreeSet;
import com.android.repository.Revision;
import com.android.repository.api.ConsoleProgressIndicator;
import com.android.repository.api.LocalPackage;
import com.android.repository.api.ProgressIndicator;
import com.android.repository.api.RepoManager;
import com.android.repository.impl.meta.RepositoryPackages;
import com.android.sdklib.repository.AndroidSdkHandler;
public class AndroidTesting {
public static void main(String[] args) {
listPackages();
}
private static void listPackages() {
AndroidSdkHandler mHandler = AndroidSdkHandler.getInstance(new
File("filePath")); //for eg:-sdk/platforms for API
ProgressIndicator progress = new ConsoleProgressIndicator();
RepoManager mRepoManager = mHandler.getSdkManager(progress);
mRepoManager.loadSynchronously(cacheExpirationMs, progress,
downloader, settings)(0, progress, null, null);
RepositoryPackages packages = mRepoManager.getPackages();
Collection<LocalPackage> locals = new TreeSet<LocalPackage>();
Collection<LocalPackage> localObsoletes = new
TreeSet<LocalPackage>();
for (LocalPackage local : packages.getLocalPackages().values()) {
if (local.obsolete()) {
localObsoletes.add(local);
} else {
locals.add(local);
}
Revision version = local.getVersion();
System.out.println(local.getDisplayName() + " "
+ local.getVersion() );
}
}
}

Xposed Framework hooking Samsung s7 edge system processes?

Im just getting into developing modules for Xposed Framework.
I get a basic module working, just a module that does nothing but saying that its loaded and prints to log.
Next step was to try hooking the Clock in SystemUI, following rovo89's instructions on GitHub (dont know if I can link?)
The code is as follows:
package com.example.xxx.xposedtest;
import android.graphics.Color;
import android.widget.TextView;
import static de.robv.android.xposed.XposedHelpers.findAndHookMethod;
import de.robv.android.xposed.IXposedHookLoadPackage;
import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XposedBridge;
import de.robv.android.xposed.callbacks.XC_LoadPackage.LoadPackageParam;
import de.robv.android.xposed.XposedHelpers;
public class xposedTest implements IXposedHookLoadPackage {
public void handleLoadPackage(final LoadPackageParam lpparam) throws Throwable {
if(!lpparam.packageName.equals("com.android.systemui")) {
XposedBridge.log("Did not find package")
return;
}
findAndHookMethod("com.android.systemui.statusbar.policy.Clock", lpparam.classLoader, "updateClock", new XC_MethodHook() {
#Override
protected void afterHookedMethod(MethodHookParam param) throws Throwable {
TextView tv = (TextView) param.thisObject;
String text = tv.getText().toString();
tv.setText(text + " :)");
XposedBridge.log("Package loaded: Function ran");
}
});
}
}
The log says "Did not find package". And the hook method ofcourse did not run.
My guess is that Samsung s7 edge has some kind of other implementation, other class/method name.
How do I find out what method to actually hook since Samsung decided to not go AOSP? All information on the subject is appriciated.
The answer was other xposed modules were interfering.
Answering if anyone encounters the same problem

Upload image twitter4j

I introduced myself to Twitter4j yesterday, and are now testing out features for an upcoming program of mine. As the title suggests, I am trying to upload an image to twitter, without any luck. Here's my code:
import static java.awt.Toolkit.getDefaultToolkit;
import static javax.swing.JOptionPane.ERROR_MESSAGE;
import static javax.swing.JOptionPane.showMessageDialog;
import java.awt.Image;
import java.io.File;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.examples.tweets.UploadMultipleImages;
import twitter4j.media.ImageUpload;
import twitter4j.media.ImageUploadFactory;
public final class UpdateStatus {
static File file = new File("/images/Done.jpg");
public static void main(String[] args) {
for(int i=0;i<2;i++){
Twitter twitter = new TwitterFactory().getInstance();
Status status=null;
try {
ImageUpload.upload(file,"22");
} catch (TwitterException e) {
System.err.println("Shit...");
System.exit(3);
}
}
System.out.println("Done");
}
}
The image I'm trying to upload is Done.jpg, and is in a folder in the package. I've used this method for images in other programs, so I am pretty sure it works. Though, this gives me an error message before I run the code, saying "Cannot make a static reference to the non-static method upload(File, String) from the type ImageUpload". Any ideas that could help me? :D
You need to ensure following before testing your code -
Register your app at https://apps.twitter.com/ and get Oauth tokens to be able to connect your app to Twitter and perform desired action.
You will get a consumerKey,consumerAccessToken, accessKey and accessToken.
If you want to post updates, please ensure you configure your app
permissions to have a Read and Write access, deafult access is Read
Only.
After you have the required access tokens, you need to instantiate a Twitter instance using those tokens. This instance can then be used to perform requisite action. See sample code below to upload an image -
ConfigurationBuilder twitterConfigBuilder = new ConfigurationBuilder();
twitterConfigBuilder.setDebugEnabled(true);
twitterConfigBuilder.setOAuthConsumerKey("consumerkey");
twitterConfigBuilder.setOAuthConsumerSecret("consumersecret");
twitterConfigBuilder.setOAuthAccessToken("accesstoken");
twitterConfigBuilder.setOAuthAccessTokenSecret("accesstokensecret");
Twitter twitter = new TwitterFactory(twitterConfigBuilder.build()).getInstance();
String statusMessage = "Watch out this interesting offer I came across today";
File file = new File("/images/Done.jpg");
StatusUpdate status = new StatusUpdate(statusMessage);
status.setMedia(file); // set the image to be uploaded here.
twitter.updateStatus(status);
Hope this helps.
ImageUpload.upload is not a static method, but an instance method.
You need to create an instance of ImageUpload, and call the method from the instance.
Checking the documentation of ImageUpload, it is an interface. So you'll need to instantiate a class that implements ImageUpload.

getting error in CODEC_ID_MPEG1VIDEO and PIX_FMT_YUV420P

I am trying to create a code which will convert images into video. I have surfed a lot and find some method to do it using javacv. now i am getting variable not found error in these lines.
recorder.setCodecID( CODEC_ID_MPEG1VIDEO);
recorder.setPixelFormat( PIX_FMT_YUV420P);
I have imported all the jar files into my library as well but still getting this error. Some quick help would be appreciated. I have gone through the below link for the importing the javacv into my workspace.
How to Import JavaCV libraries to Android Project
package com.example.photoaday;
import static com.googlecode.javacv.cpp.opencv_core.cvReleaseImage;
import static com.googlecode.javacv.cpp.opencv_highgui.cvLoadImage;
import static com.googlecode.javacv.cpp.opencv_highgui.cvShowImage;
import static com.googlecode.javacv.cpp.opencv_highgui.cvWaitKey;
import static com.googlecode.javacv.cpp.opencv_imgproc.CV_GAUSSIAN;
import static com.googlecode.javacv.cpp.opencv_imgproc.cvSmooth;
import com.googlecode.javacv.FFmpegFrameRecorder;
import com.googlecode.javacv.cpp.opencv_core;
import com.googlecode.javacv.cpp.opencv_core.IplImage;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class Recordvideo extends Activity {
// #Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create);
opencv_core.IplImage img = cvLoadImage("/sdcard/folder/img1.jpg");
FFmpegFrameRecorder recorder = new FFmpegFrameRecorder("/sdcard/folder/test.mpeg",200,150);
try {
recorder.setCodecID( CODEC_ID_MPEG1VIDEO);
recorder.setFrameRate(30);
recorder.setPixelFormat( PIX_FMT_YUV420P);
recorder.start();
for (int i=0;i<100;i++)
{
recorder.record(img);
}
recorder.stop();
}
catch (Exception e){
e.printStackTrace();
}
}
}
I assume that your compiler gives error as follows
error: ‘CODEC_ID_MPEG1VIDEO’ was not declared in this scope
error: ‘PIX_FMT_YUV420P’ was not declared in this scope
then solution for error is
change : ‘CODEC_ID_MPEG1VIDEO’ to 'AV_CODEC_ID_MPEG1VIDEO'
change : ‘PIX_FMT_YUV420P’ to 'AV_PIX_FMT_YUV420P'

Categories

Resources