Twitter App in Processing - api

I'm having a massive problem with a Twitter App I'm trying to create. I've been at this problem for 2 weeks straight, 14 hours a day and I cannot get my head around how to fix. I'm a newbie so I'm sure it's just a simple matter.
I need my twitter stream to display five tweets at a time. Then I need for it to remove the oldest tweet and replace it with a new one. Now I was told the best method for this is to use the Linkedlist, which makes perfect sense. However, whenever I attempt to incorporate this, it just won't work.
If someone could help me out I'd be endlessly grateful as I'm at my wits end at this point.
Here's the code:
import com.francisli.processing.http.*;
import java.util.LinkedList;
//LinkedList myList;
HashMap overall = new HashMap();
HttpClient client;
LinkedList myList;
PImage prhomoPix;
int results_to_show = 5;
int updateTime = 10000;
int updateDiff = 0;
void setup()
{
myList = new LinkedList();
for (int i = 0; i < 5; i++)
{
myList.add(client);
}
size(1143, 800);
prhomoPix = loadImage("PrhomoAppBg.jpg");
background(0);
image(prhomoPix, 0, 0);
fill(0, 0, 0, 80);
noStroke();
rect(20, 135, 370, 670);
fill(0, 0, 0, 80);
noStroke();
rect(755, 135, 370, 670);
textAlign(CENTER, CENTER);
}
void responseReceived(HttpRequest request, HttpResponse response)
{
if(response.statusCode == 200)
{
JSONObject allresults;
allresults = response.getContentAsJSONObject();
//JSONObject timeline_tweets = response.getContentAsJSONObject();
for (int i = 0; i < 5; i++)
{
text(allresults.get("results").get(i).get("text").stringValue(), 25, 50+(i*120), 330, 330);
}
frameRate(2);
//}
//for (int i=0; i < results_to_show; i++)
//{
// text(allresults.get("results").get(i).get("text").stringValue(), 25, 50+(i*120), 330, 330);
// }
}
else
{
text("UH-OH" + response.getContentAsString(), 50, 50);
}
}
void tweetUpdate()
{
if(millis() > (updateTime + updateDiff))
{
client = new HttpClient(this, "search.twitter.com");//what webservice we are using, this is the priate OAuth one. "this" means it is not cpying setting from anywhere else
client.GET("search.json?q=dublin&rpp="+results_to_show+"&result_type=recent");
//println(myList);
updateDiff = millis();
}
}
void draw()
{
myList.remove(client);
myList.add(client);
tweetUpdate();
}
Once again thanks so much!

To be honest with you, Java is really not my field, but these tutorials looked quite self explanatory. Hope they help.
http://examples.javacodegeeks.com/core-java/util/linkedlist/

You have to repaint whole screen in draw() method.
I guess, people told you to save tweets in LinkedList, not HttpClient.
Update list of tweets in responseReceived() method.
Eventually, your draw would look something like this:
void draw() {
// repaint
background(0);
// draw picture
image(prhomoPix, 0, 0);
// repaint all tweets
for(int i=0; i< tweetsList.size(); ++i {
drawTweet(tweetsList);
}
tweetUpdate(); // update list of tweets from server
}
tweetUpdate()
void tweetUpdate() {
client = new HttpClient(this, "search.twitter.com");
client.GET("search.json?q=dublin&rpp="+results_to_show+"&result_type=recent");
}

Related

Is there a way to use a bitmap or glide rather than a drawable image in MPAndroidChart?

int[] moodIconRes = {
R.drawable.ic_emoticon_01, R.drawable.ic_emoticon_02, R.drawable.ic_emoticon_03,
R.drawable.ic_emoticon_04, R.drawable.ic_emoticon_05, R.drawable.ic_emoticon_06,
R.drawable.ic_emoticon_07, R.drawable.ic_emoticon_08, R.drawable.ic_emoticon_09,
R.drawable.ic_emoticon_10, R.drawable.ic_emoticon_11, R.drawable.ic_emoticon_12
};
Right now I am using it as a drawable.
private void setData1(HashMap<Integer, Integer> hashMap) {
ArrayList entries = new ArrayList<>();
int totalCount = 0; // 총 기분 수 (전체, 올해, 이번달마다 달라지는 값이므로 호출마다 초기화)
maxMoodIndex = -1; // 제일 많은 기분 종류
maxCount = -1; // 제일 많은 기분의 개수
colors.clear(); // 파이차트를 구성할 색깔배열 clear (전체, 올해, 이번달마다 달라지는 값이므로 clear 필요)
for(int i = 0; i < 12; i++) {
int count = 0;
if(hashMap.containsKey(i)) {
count = hashMap.get(i);
setMoodCount(i, count);
totalCount += count;
addColor(i); // 기분 종류에 맞게 색깔 설정
entries.add(new PieEntry(
count,
"",
ContextCompat.getDrawable(requireContext(), moodIconRes[i])
));
} else {
setMoodCount(i, count); // 개수 0
}
}
I wonder if there is a way to call it in the form of a bitmap or r.id.imageview rather than a drawable image in this part. I'd appreciate it if someone could give me an idea.
You can use BitmapDrawable
Drawable d = new BitmapDrawable(getResources(), bitmap);

Entity Framework not adding multiple objects

Im trying to add some dummy content into my database. I have a sample object called "obj", and I'm using a for loop to insert data like the code below:
public async Task<Post> Add(Post obj)
{
if (db != null)
{
obj.Id = 0;
for (int i = 0; i < 100; i++)
{
await db.Post.AddAsync(obj);
}
await db.SaveChangesAsync();
return obj;
}
return null;
}
However, it does add only 1 record into database, could you please explain what's wrong here?
Can you create object of post inside the loop and try again?
for (int i = 0; i < 100; i++)
{
Post obj = new Post();
await db.Post.AddAsync(obj);
}
If you run the below commands before calling saved changes you can see what changes EF Core has queued up.
var post = new Post();
for (int i = 0; i < 10; i++)
{
await db.Posts.AddAsync(dev);
}
db.ChangeTracker.DetectChanges();
Debug.WriteLine(db.ChangeTracker.DebugView.LongView);
await db.SaveChangesAsync();
This will write to Debug that one post is currently being tracked.
for (int i = 0; i < 10; i++)
{
var post = new Post();
await db.Posts.AddAsync(dev);
}
db.ChangeTracker.DetectChanges();
Debug.WriteLine(db.ChangeTracker.DebugView.LongView);
await db.SaveChangesAsync();
This will right to the Debug window the 10 posts are currently being tracked.
In your code when you AddAsync(obj), obj isn't a new object and EF Core is already tracking obj.
Moving Post obj = new Post() into the loop creates a new object for EF Core to track. If these objects aren't being added to the DB my guess would be that they don't meet a requirement for the Post model.
Either way playing around with
db.ChangeTracker.DetectChanges();
Debug.WriteLine(db.ChangeTracker.DebugView.LongView);
should help you be able to track down exactly what's going on.
I do hope you find this information helpful :)
You can try to use AddRange.
public async Task<Post> Add(Post obj)
{
if (db != null)
{
List<Post>=new List<Post>();
obj.Id = 0;
for (int i = 0; i < 100; i++)
{
l.Add(obj);
}
await db.Post.AddRangeAsync(l);
await db.SaveChangesAsync();
return obj;
}
return null;
}

Create js sprite freezing on first frame

Pulling my hair out with this one, hope its not something silly. Below is a snippet of code from a program. When leftwalker.x == 150 he should gotoAndPlay the standstill animation but it only plays the first frame, the previous animation runs fine. Any ideas?
var data =
{
images: ["images/ste_basic_wand.png"],
frames: {width:64, height:64},
animations:
{
// start, end, next, speed
walkright: [143,151,"walkright",1.18],
walkleft: [118,125,"walkleft",1.18],
stand:[39,45,"stand",0.08],
standstill:[26,27, "standstill", 1.2]
}
};
var spriteSheet = new createjs.SpriteSheet(data);
leftwalker = new createjs.Sprite(spriteSheet);
leftwalker.name = "lefty";
leftwalker.framerate = 30;
leftwalker.x = 100;
leftwalker.y = 100;
leftwalker.currentFrame = 0;
leftwalker.scaleY = leftwalker.scaleX = 2;
leftwalker.gotoAndPlay("walkright");
stage.addChild(leftwalker);
createjs.Ticker.setFPS(10);
createjs.Ticker.addEventListener("tick", tick);
}
function tick(event) {
if(container.x < 150)
{
container.x += 5;
}
if(leftwalker.x < 150)
{
leftwalker.x += 2;
}
if(leftwalker.x == 150)
{
leftwalker.gotoAndPlay("standstill");
}
// if (circle.x > stage.canvas.width) { circle.x = 0; }
stage.update(event); // important!!
}
The reason this happens is because you are calling gotoAndPlay("standstill") during the tick. Once you reach 150, your sprite stops moving, so it is perpetually at x=150. This means each tick will tell it to gotoAndPlay the same frame, resulting it in being "stuck".
Figured out a way around it, still not sure why but easaljs didn't like the code
if(leftwalker.x == 150)
{
leftwalker.gotoAndPlay("standstill");
}
When I change it so the char isn't stuck on point 150 (move him to 151) the animation begins. I also slowed the animation on the standing still down to make it seem more real but this isn't related to the fix I didn't post this code.
if(leftwalker.x == 150)
{
leftwalker.gotoAndPlay("standstill");
if(leftwalker.x < 180)
{
leftwalker.x += 1;
}
}

Instagram & Processing - Real time view

I'm working on a small app similar to instaprint and need some help. I'm using the source code from Globalgram by Andrew Haskin, it searches instagram for a particular hashtag and displays the most recent image posted with that hashtag. The problem is it only does it once, I need it to continuously search for the hashtag and display an image when a new one is added, so a refresh, I've been tinkering with it but to no avail. Any help would be greatly appreciated
Code Below :
import com.francisli.processing.http.*;
PFont InstagramFont;
PImage backgroundimg;
PImage brand;
PImage userphoto;
PImage profilepicture;
String username;
String tag;
String[] tagStrings;
com.francisli.processing.http.HttpClient client;
void setup() {
size(580, 900);
smooth();
backgroundimg = loadImage("iso_background.jpg");
brand = loadImage("iso.jpg");
InstagramFont = loadFont("Helvetica-Bold-36.vlw");
client = new com.francisli.processing.http.HttpClient(this, "api.instagram.com");
client.useSSL = true;
//// instantiate a new HashMap
HashMap params = new HashMap();
//// put key/value pairs that you want to send in the request
params.put("access_token", "------ACCESS TOKEN HERE------");
params.put("count", "1");
client.GET("/v1/tags/coffee/media/recent.json", params);
}
void responseReceived(com.francisli.processing.http.HttpRequest request, com.francisli.processing.http.HttpResponse response) {
println(response.getContentAsString());
//// we get the server response as a JSON object
com.francisli.processing.http.JSONObject content = response.getContentAsJSONObject();
//// get the "data" value, which is an array
com.francisli.processing.http.JSONObject data = content.get("data");
//// get the first element in the array
com.francisli.processing.http.JSONObject first = data.get(0);
//// the "user" value is another dictionary, from which we can get the "full_name" string value
println(first.get("user").get("full_name").stringValue());
//// the "caption" value is another dictionary, from which we can get the "text" string value
//println(first.get("caption").get("text").stringValue());
//// get profile picture
println(first.get("user").get("profile_picture").stringValue());
//// the "images" value is another dictionary, from which we can get different image URL data
println(first.get("images").get("standard_resolution").get("url").stringValue());
com.francisli.processing.http.JSONObject tags = first.get("tags");
tagStrings = new String[tags.size()];
for (int i = 0; i < tags.size(); i++) {
tagStrings[i] = tags.get(i).stringValue();
}
username = first.get("user").get("full_name").stringValue();
String profilepicture_url = first.get("user").get("profile_picture").stringValue();
profilepicture = loadImage(profilepicture_url, "png");
String userphoto_url = first.get("images").get("standard_resolution").get("url").stringValue();
userphoto = loadImage(userphoto_url, "png");
//noLoop();
}
void draw() {
background(255);
imageMode(CENTER);
image(brand, 100, height/1.05);
if (profilepicture != null) {
image(profilepicture, 60, 70, 90, 90);
}
imageMode(CENTER);
if (userphoto != null) {
image(userphoto, width/2, height/2.25, 550, 550);
}
textFont(InstagramFont, 20);
if (username != null) {
text(username, 110, 115);
fill(0);
}
textFont(InstagramFont, 15);
if ((tagStrings != null) && (tagStrings.length > 0)) {
String line = tagStrings[0];
for (int i = 1; i < tagStrings.length; i++) {
line += ", " + tagStrings[i];
}
text(line, 25, 720, 550, 50);
fill(0);
}
}
AFAIK it should be the
client.GET("/v1/tags/coffee/media/recent.json", params);
line that actually polls Instagram. Try wrapping that in a function like this:
void getGrams() {
client.GET("/v1/tags/coffee/media/recent.json", params);
}
then call that once in setup() and then again when you want to ...
I'd start with trying to do it on mousePressed() or keyPressed(), so that it only fires once when you really want it to
Don't try to do it in draw() without a timer (something like if(frameCount % 5000 == 0) which will fire every five seconds ((which may be too fast still but you get the idea))

Detect collisions between objects in arrays

So I need to detect the collision of multiple objects that are stored in two different arrays or arrayLists. I have confirmed that the collision detection method itself is functioning properly. The problem is that the objects colliding are supposed to disappear and be removed from the array, and I'm not sure how to go about this.
public class GamePanel extends PApplet{
private boolean myRunningStatus;
private final int HEIGHT = 700;
private final int WIDTH = 1200;
private final int SHOT_SPEED = -20;
private int numStars = 0, numEnemies = 0;
private Hero hero;
private Enemy[] enemies;
private List <Star> stars;
public GamePanel(){
myRunningStatus = true;
createEnemies();
createStars();
createHero();
updateEnemies();
}
public void createEnemies(){
enemies = new Enemy[10];
for (int i=0; i<enemies.length; i++){
enemies[i] = new Enemy(random(1, WIDTH), random(1, HEIGHT), 5, 20);
}
}
public void createHero(){
hero = new Hero(mouseX, mouseY);
}
public void createStars(){
stars = new ArrayList <Star>();
}
public Star generateStar(){
Star star = new Star(hero.getHeroX(), hero.getHeroY());
return star;
}
public void setup(){
background(255);
size(WIDTH, HEIGHT);
hero.render(this);
}
public void draw(){
if(myRunningStatus){
background(255);
hero.render(this);
for(int i=0; i<enemies.length; i++){
enemies[i].render(this);
enemies[i].move();
}
for(int i=0; i<stars.size(); i++){
if(stars.get(i) != null){
stars.get(i).render(this);
stars.get(i).move(SHOT_SPEED);
if(stars.get(i).getYPos() < 0){
stars.remove(i);
}
}
}
}
}
//this is the method I'm using to find the collisions between the objects and remove them
public void updateEnemies(){
for(int i=0; i<enemies.length; i++){
for(int j=0; j<stars.size(); j++){
if(enemies[i].starHit(stars.get(j))){
stars.set(j, null);
enemies[i] = null;
}
}
}
}
public void mouseMoved(){
if(myRunningStatus){
hero.setHeroX(mouseX);
hero.setHeroY(mouseY);
}
}
public void mouseClicked(){
for (int i=0; i<10;){
stars.add(i, generateStar());
break;
}
}
Instead of setting things equal to null, it would be better to remove them outright from the list. I would use an ArrayList for both enemies and stars, then call list.remove(i) during collision detection. Don't forget that this will change the size of the list, so you'll have to do i-- every time you remove an element to compensate.
Also, this confused me. You set elements of enemies equal to null:
if(enemies[i].starHit(stars.get(j))){
stars.set(j, null);
enemies[i] = null;
}
But don't check for it here, so shouldn't you be getting NPEs?
for(int i=0; i<enemies.length; i++){
enemies[i].render(this);
enemies[i].move();
}