How do put each AsyncTask class in a separate file? - java

I have a few asynstask that are definined inside of my main activity. I tried to make the code more modular by putting each one of these classes on a separate file. Unfortunately I keep getting some errors such as not being able to get the intents to work. How do I connect this code with my main activity. By the way if I place this code as is(without the imports) in the mainActivity it works just fine. Thanks
package com.example.food4thought;
import java.net.URL;
import twitter4j.TwitterException;
import twitter4j.auth.RequestToken;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
// Starts an intent that loads up a web browser and asks the user to log in to twitter
// and get a pin#
public class TwitterLogin extends AsyncTask<URL, Integer, RequestToken> {
protected RequestToken doInBackground(URL... arg0) {
try {
requestToken = twitter.getOAuthRequestToken();
Log.i("Got Request Token", "food4thought");
} catch (TwitterException e) {
Log.i("Failed to get Request Token", "food4thought");
}
//Log.i(requestToken.getAuthorizationURL(), "food4thought");
//requestToken.getAuthorizationURL();
//log_in.setText();
try {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(requestToken.getAuthorizationURL()));
startActivity(browserIntent);
}
catch(NullPointerException e) {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "Unable to log in, No access to the Internet.", Toast.LENGTH_LONG).show();
}
});
}
return null;
}
}

To do that you need to understand what dependencies your AsyncTask has.
To fire Intents you need Context intance. I also see some twitter variable.
So you need declare appropriate fields and to pass those objects to your TwitterLogin constructor.
Something like that:
public class TwitterLogin extends AsyncTask<URL, Integer, RequestToken> {
private Context context;
//other fields here
public TwitterLogin(Context context, ...){ // other variables here
this.context = context;
//other fields assignment
}
}
Later you can fire Intent:
context.startActivity(browserIntent);
What's important to understand is that all those methods like startActivity are not some "global functions", rather they are methods of some class instance, and you can't just call those methods from AsycTask instance.

Related

Howto getExtras from a local broadcast Intent in react-native

in my React-Native opened project,
I want to receive the data (extra text) sent by another local service app named "scanservice" on its intent output (broadcast) on a Action named "scanservice.data" ,
and I do not know how to start & write that : someone can help me please?
I have tried without success HeadlessJs, Linking solutions.
I put some more info I got and I please ask for some corrections since I am null in Java writting :
I want to make a native Android module (in java) (as described on RN site : https://reactnative.dev/docs/native-modules-android)
to catch the text ('extra_text') sent by an intent of another app, named "manuf".
The class 'scan_intent.java' I wrote here has many mistakes (with "//error":
package com.intent_scan;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import org.w3c.dom.Text;
public class ScanIntent extends ReactContextBaseJavaModule {
//constructor
// normaly : "public class ScanIntent extends BroadcastReceiver" : how to add this ?
public ScanIntent(ReactApplicationContext reactContext) {
super(reactContext);
}
#Override
public String getName() {
return "ScanIntent";
}
//Custom function that we are going to export to JS
#ReactMethod
public void onReceive(Context context, Intent intent, String extra_text){
if ("manuf.scanservice.data".equals(intent.getAction()))
{
getReactApplicationContext().registerReceiver //error on registerR...
try {
Bundle extras = intent.getExtras();
if (extras != null) {
extra_text = extras.getString("text"); //error : this value will be returned ?
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}}
thank you !

Unable to communicate between Android client and Node.js socket.io server

I've looked at many tutorials on this yet none of them seem to work so no idea whether it's the server, client or potentially something on my network that's stopping it I don't know, so I come here for help.
Just for reference this is the tutorial that this is mainly based on: https://socket.io/blog/native-socket-io-and-android/
So this is my server. All it's supposed to do at the moment is detect when a user connects and then detect users sending messages and send them back to all the clients.
index.js
const express = require("express");
const app = express();
const path = require("path");
const server = require("http").createServer(app);
const io = require("socket.io")(server);
server.listen(3000, () => {
console.log("Server listening at 3000");
});
app.use(express.static(path.join(__dirname, "public")));
io.on("connection", (socket) => {
console.log("User connected");
socket.on("new message", (data) => {
console.log("New message" + data)
socket.emit("new message", {
message: data
});
})
});
My Android client is made up of 3 classes. But to try and keep this shorter I'll only include 2 of them as if the problem can be found in these it's fixable in the 3rd.
This is what's launched at the start and simply pressing the button brings you to the main 'chat' part, but on clicking the button the server should log the connection but nothing appears in the console. So I can only assume the socket connection isn't working for some reason. Also you can ignore the nickname, I've not implemented that yet, been trying to get the main part working first.
MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import io.socket.client.Socket;
public class MainActivity extends AppCompatActivity {
private EditText nickname;
private Button enterChat;
private Socket mSocket;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nickname = findViewById(R.id.nickname);
enterChat = findViewById(R.id.enterChat);
ChatApplication app = (ChatApplication) getApplication();
mSocket = app.getSocket();
mSocket.connect();
enterChat.setOnClickListener(v -> {
mSocket.emit("connection");
Intent i = new Intent(MainActivity.this, ChatActivity.class);
i.putExtra("name", nickname.getText().toString());
startActivity(i);
});
}
}
This is just to be able to get the Socket from any other activity.
ChatApplication.java
import android.app.Application;
import java.net.URISyntaxException;
import io.socket.client.IO;
import io.socket.client.Socket;
public class ChatApplication extends Application {
private Socket mSocket;
{
try {
//My IPv4 address here
mSocket = IO.socket("http://xxx.xxx.x.xxx:3000");
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
public Socket getSocket() {
return mSocket;
}
}
Any help appreciated :)
Found the problem, I need to add this to the AndroidManifest.xml
<application
...
android:usesCleartextTraffic="true"
...
</application>

Cannot resolve symbol (variables)

I am very new to Android, it would be great if you could help me with the error "Cannot resolve symbol ..." in the variables:
- value 1
- banner_id
- full_id
My code is the following:
package com.example.sienstranslation.siensapp;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.android.gms.appdatasearch.GetRecentContextCall;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class Main3Activity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
Intent intent=getIntent();
double precio = intent.getExtras().getDouble("precio");
String precio_rounded = String.format("%.2f", precio);
TextView txtCambio = (TextView) findViewById(R.id.textView4);
txtCambio.setText("Precio Total: "+ precio_rounded + " €");
}
void MakePostRequest() {
String posting_url ="http://ipaddress/app.php";
// its your url path ok
StringRequest postRequest = new StringRequest(Request.Method.POST, posting_url ,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
value1= jsonResponse.getString("precio_rounded");
} catch (JSONException e) {
e.printStackTrace();
banner_id = null;
full_id = null;
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
value1= null;
}
}
) {
// here is params will add to your url using post method
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("app", getString(R.string.app_name));
//params.put("2ndParamName","valueoF2ndParam");
return params;
}
};
Volley.newRequestQueue(this).add(postRequest);
}
Thank you very much for your time
At first , Declare banner_id & full_id ;
public class Main3Activity extends AppCompatActivity {
public int banner_id,full_id;
Then Clean-Rebuild Your Project .
It is a bad idea to start directly with Android ... when you don't have any clue about java itself. In your program, you are using those three variables without ever declaring them before. That is what the compiler is telling you. That is super basic stuff.
So I seriously recommend you to step back; and study those java basics for some more time. Otherwise your programming experience will be nothing else but a (probably short) series of very frustrating moments.
This is not meant to be rude; but it looks like you intend to build a skyscraper; but you actually have no idea how to dig the hole for the basement. That is simply not a very rewarding or efficient approach to get things done.
And you see, your follow-on comments to the answers ... just prove my point. Your current approach is nothing but trial-and-error. And just to be precise: the Android java programming model is itself something that can drive experienced java programmers nuts.
You must declare all variables before they can be used. The basic form of a variable declaration is shown here:
data type variable [ = value][, variable [= value] ...] ;

Volley: No authentication challenges found

I'm using Volley in an Android App to fetch data from the Misfit API (http://build.misfit.com). I tried to construct an intermittent activity, after someone logged in, to get all the data from the API. In that activity, I perform a JsonObject GET request, that should give me some information about the user of the app. Here's the code so far:
package com.iss_fitness.myapplication;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
import learn2crack.weboauth2.R;
public class LoadingScreenActivity extends Activity {
//Introduce an delay
private final int WAIT_TIME = 500;
private static final String QUERY_URL = "https://api.misfitwearables.com/move/resource/v1/user/me/profile";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
System.out.println("LoadingScreenActivity screen started");
setContentView(R.layout.loading_screen);
findViewById(R.id.mainSpinner1).setVisibility(View.VISIBLE);
// Instantiate the RequestQueue.
final RequestQueue queue = Volley.newRequestQueue(this);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
executeJson();
System.out.println("Going to Profile Data");
/* Create an Intent that will start the ProfileData-Activity. */
Intent mainIntent = new Intent(LoadingScreenActivity.this, DataView.class);
LoadingScreenActivity.this.startActivity(mainIntent);
LoadingScreenActivity.this.finish();
}
}, WAIT_TIME);
}
private Response.ErrorListener createRequestErrorListener() {
return new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println(error);
}
};
}
private void executeJson() {
SharedPreferences prefs = this.getSharedPreferences("AppPref", MODE_PRIVATE);
final String token = prefs.getString("token", null);
RequestQueue queue = Volley.newRequestQueue(this);
Map<String, String> params = new HashMap<String, String>();
System.out.println(token);
params.put("access_token", token);
CustomRequest jsonRequest = new CustomRequest(Request.Method.GET, QUERY_URL, params,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
System.out.println(response);
}
}, this.createRequestErrorListener());
System.out.println(jsonRequest);
queue.add(jsonRequest);
}
}
I'm quite new to Android development, so please bear with me, I'll try to describe the code. I've implemented a help class as suggested for JsonObjectRequest, as, as I understood, you can't override the getparams method when defining a request locally. the executeJson() method is the interesting one: I get the user access token from my SharedPreferences (Where it's correctly stored), put that in a String Map and give that to the CustomRequest, where, inside the help class, it gets thrown into a getparams method that simply returns the params. The responselistener sadly never gets called, as the errorlistener reports the following:
com.android.volley.NoConnectionError: java.io.IOException: No authentication challenges found
According to the API reference of Misfit, that should work.
Now, I know that a GET request requires "headers" and not "params" but does that make any difference?
Okay, I found a solution. The helper class contained an overriding getparams method, but no getheaders method. GET request requires getheaders, post requires getparams.

Is it possible to do a post on the Facebook user's wall and did not authorize, in each case?

Actually I have a problem - I did login to Facebook in my application. I can also do wall posts authorized by the user, but that I needed each time to call the authorization - it takes some time and leads to the fact that on the screen (for a short time), there is "the box" with a white background ( https://dl.dropbox.com/u/41114685/1.JPG ) that is generated (induced) Facebook. That's why I'm interested in whether it is possible to do a post on the user's wall does not cause, each time a method for authentication (to make posts out method onComplete())?
I hope for your help.
package expir.java.file;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
public class FacebookAuthorizeAndPost implements DialogListener{
FacebookAuthorizeAndPost(Activity activity){
this.activity = activity;
}
public void facebookAuthorize(){
facebookClient = new Facebook(APP_ID);
facebookClient.authorize(activity, new String[]{"publish_stream"}, Facebook.FORCE_DIALOG_AUTH, this);
}
public void onComplete(Bundle values) {
if (values.isEmpty())
{
return;
}
if (!values.containsKey("post_id"))
{
try
{
Bundle cont = new Bundle();
cont.putString("message", "bla-bla-bla");
cont.putString("name", "Testing facebook");
cont.putString("link", "www.????????.com");
cont.putString("description", "This is a funny real test!!! This is a funny real test!!! This is a funny real test!!! This is a funny real test!!!");
cont.putString("picture", "http://code.google.com/p/android-developer-scripts/logo?cct=1294556390");
//facebookClient.dialog(activity, "feed", cont, this);
facebookClient.request("me/feed", cont, "POST");
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
}
}
public void onFacebookError(FacebookError e) {
//
}
public void onError(DialogError e) {
//
}
public void onCancel() {
//
}
public Activity activity;
private final String APP_ID = "??????????????????";
private Facebook facebookClient;
}
You can use isSessionValid() method of Facebook class to check if a valid non-expired session exists, if it doesn't then call the authorize() method otherwise proceed with posting on user's wall.
Also please refer to this post here: http://blog.doityourselfandroid.com/2011/02/28/30-minute-guide-integrating-facebook-android-application/
I have just posted an example of this on another question a couple of mins ago.
See here - logging into facebook

Categories

Resources