Error in oAuth for Twitter for Android - java

I am using an application to authorize a user in Twitter using Twitter4j library. I want to incorporate a feature, my mobile app opens. It has a login button on click of which Twitter login dialog appears and lets you enter the login information . after the login is complete, another screen opens.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.Toast;
public class AndTweetVJActivity extends Activity {
/** Called when the activity is first created. */
Twitter twitter;
RequestToken requestToken;
public final static String consumerKey = "myKey"; // "your key here";
public final static String consumerSecret = "myKey"; // "your secret key here";
private final String CALLBACKURL = "T4JOAuth://main"; //Callback URL that tells the WebView to load this activity when it finishes with twitter.com. (see manifest)
//Calls the OAuth login method as soon as its started
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
OAuthLogin();
}
/* Creates object of Twitter and sets consumerKey and consumerSecret
* - Prepares the URL accordingly and opens the WebView for the user to provide sign-in details
* - When user finishes signing-in, WebView opens your activity back */
void OAuthLogin() {
try {
twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(consumerKey, consumerSecret);
requestToken = twitter.getOAuthRequestToken(CALLBACKURL);
String authUrl = requestToken.getAuthenticationURL();
this.startActivity(new Intent(Intent.ACTION_VIEW, Uri
.parse(authUrl)));
} catch (TwitterException ex) {
Toast.makeText(this, ex.getMessage(), Toast.LENGTH_LONG).show();
Log.e("in Main.OAuthLogin", ex.getMessage());
}
}
/*
* - Called when WebView calls your activity back.(This happens when the user has finished signing in)
* - Extracts the verifier from the URI received
* - Extracts the token and secret from the URL
*/
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
Uri uri = intent.getData();
try {
String verifier = uri.getQueryParameter("oauth_verifier");
AccessToken accessToken = twitter.getOAuthAccessToken(requestToken,verifier);
String token = accessToken.getToken(), secret = accessToken.getTokenSecret();
//displayTimeLine(token, secret); //after everything, display the first tweet
} catch (TwitterException ex) {
Log.e("Main.onNewIntent", "" + ex.getMessage());
}
}
}
however on running this application, it gives me error in logcat :
11-18 10:36:27.727: E/in Main.OAuthLogin(282): 401:Authentication credentials (https://dev.twitter.com/docs/auth) were missing or incorrect. Ensure that you have set valid conumer key/secret, access token/secret, and the system clock in in sync.
11-18 10:36:27.727: E/in Main.OAuthLogin(282): <?xml version="1.0" encoding="UTF-8"?>
11-18 10:36:27.727: E/in Main.OAuthLogin(282): <hash>
11-18 10:36:27.727: E/in Main.OAuthLogin(282): <error>Desktop applications only support the oauth_callback value 'oob'</error>
11-18 10:36:27.727: E/in Main.OAuthLogin(282): <request>/oauth/request_token</request>
11-18 10:36:27.727: E/in Main.OAuthLogin(282): </hash>
I believe i had not set up callback URL, but i did that as well to https://dev.twitter.com/pages/welcome-anywhere
in my app.

Make sure that you have not register your app in Desktop application category at twitter application registration.

My Bad... My Web server was down and i did not noticed it until 5 minutes ago. thanks for all suggestions. I have already done these things.

Related

Can't connect to MS SQL Server via another WiFi; java.sqlSQLException: Network error IOException: Host unreachable

I've made a SQL Server and managed to form a database. Implemented everything in my Android Studio app and opened the app on my phone.
When I access the database from the same WiFi network where the database is formed, everything works, but when I access the database from another WiFi network I get the exception:
java.sql.SQLException: Network error IOException: Host unreachable
Can you make the server accessible from every other network apart from the network that the database is connected to? Or do I have to do something else to make it accessible from everywhere?
Things I've already done:
Every SQL services are up and running.
Shared Memory, Named Pipes and TCP/IP are enabled.
Remote server connections is Allowed on my database.
New account is created (I don't use the sa account).
I've made an exception in the firewall for the port (1433).
I will add the code from my app if that helps in any way.
import android.Manifest;
import android.content.Intent;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
import android.view.Window;
import android.widget.TextView;
import android.widget.Toast;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class MainActivity extends AppCompatActivity {
TextView moreGames;
String b;
private static String ip = "xxx.xxx.x.x";
private static String port = "1433";
private static String Classes = "net.sourceforge.jtds.jdbc.Driver";
private static String database = "xxxx";
private static String username = "xxxxxx";
private static String password = "xxxx";
private static String url = "jdbc:jtds:sqlserver://" + ip + ":" + port + "/" + database;
private Connection connection = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
moreGames = findViewById(R.id.moreGames);
ActivityCompat.requestPermissions(this, new String[]{(Manifest.permission.INTERNET)}, PackageManager.PERMISSION_GRANTED);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
try {
Class.forName(Classes);
connection = DriverManager.getConnection(url, username, password);
moreGames.setText(R.string.NewGame);
} catch (ClassNotFoundException e){
e.printStackTrace();
Toast.makeText(this, "Error somewhere.", Toast.LENGTH_SHORT).show();
} catch (SQLException e){
b = String.valueOf(e);
Toast.makeText(this, b, Toast.LENGTH_LONG).show();
}

GCM Notification is not working sometimes in Playframework(Play Java)

I am writing code for GCM notification to send to my android app using the registered id with GCM Server and project API key. Sometimes it's not sending any notification and it's only working for some API keys, but not for others.
I am posting sample code here. I have searched the internet but I got only play Scala. But I need for play Java. I am using playframework with Java.
Is there any alternative code in Playframework?
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import play.Logger;
import com.google.android.gcm.server.Message;
import com.google.android.gcm.server.MulticastResult;
import com.google.android.gcm.server.Result;
import com.google.android.gcm.server.Sender;
public class GcmNotification {
public static boolean sendNotification(String notification, String regId) {
// api key
final Sender sender = new Sender("AIzaSyCQAE7VyFHreppcOkv7aXGk8JOxy4Osxdgvx");
Result result = null;
final Message message = new Message.Builder().timeToLive(30)
.delayWhileIdle(true)
.addData("date", new Date().getTime() + "")
.addData("message", notification).build();
final List<String> regids = new ArrayList<String>();
regids.add(regId);
Logger.info("entered2 : " + regids.size());
try {
result = sender.send(message, regids, 1);
} catch (final IOException e) {
e.printStackTrace();
}
return true;
}
}

Connecting database using MySQL connector

I am a beginner to Android Eclipse. However, I have a project to do an Android application. I am unable to connect to the Android emulator using the MySQL connector to create a login page. Am I missing an important file?
Loginpage
package com.example.logininterface;
import com.example.logininterface.R.menu;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
EditText txtUserName;
EditText txtPassword;
Button btnLogin;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtUserName = (EditText)this.findViewById(R.id.txtUname);
txtPassword = (EditText)this.findViewById(R.id.txtPwd);
btnLogin = (Button)this.findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if ((txtUserName.getText().toString()).equals(txtPassword.getText().toString())) {
Toast.makeText(MainActivity.this, "Login Successful", Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(MainActivity.this, "Invalid Login", Toast.LENGTH_LONG).show();
}
}
});
}
}
MySQLConn
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class Main {
public static void main(String[] args) throws Exception
{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mobiledb", "teddy", "password");
PreparedStatement statement = con.prepareStatement("select * from androidlogin");
ResultSet result = statement.executeQuery();
while(result.next())
{
System.out.println(result.getString(1) + "" + result.getString(2));
}
}
}
I don't think accessing any database directly from the Android layer is a good idea. It would be better if you could pass required parameters to a server page (PHP, JSP, etc.) and database connections could be done from server pages.
Coming to your question, localhost means Android in this case, so it will be looking for a MySQL database inside your emulator. Instead, you need to use your computer's IP address. Go to a terminal and type ipconfig or ifconfig if you are on *nix/Macintosh machine to get the IP address.
I suggest to use JSON with PHP to connect to the MySQL database. It is just an opinion.
It is better that you use JSON to communicate with the PHP script and within the PHP script to communicate with your localhost MySQL database. And you may try this to connect to your PHP script.
Example:
public class Login {
...
private static final String LOGIN_URL = "http://XXX.XXX.X.XX/Example/login.php";
...
// Invoke by Intent activity by Login class
class AttemptLogin extends AsyncTask<String, String, Integer> {
...
protected void onPreExecute() {
....
}
protected Integer doInBackground() {
....
// Getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "POST",
params);
....
}
protected void onPostExecute() {
....
}
}
The XXX.XXX.X.XX is the local IP address of your computer, which means when your mobile is connected on the same network as your computer, the IP address is the computer local IP address. Do not put in localhost. It won't work.
Instead of using "Localhost" use 10.0.2.2. Hope it helps!

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

Internet on android, causing twitter4j exception?

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.

Categories

Resources