Waiting for result in IntentService - android

Is there a way to wait for the result when using IntentService?
Scenario.
Service App is running --> receives login credentials from another app --> Service app then checks database (for some reason I always get Connection time out. And I know this is bad but for POC and a quick hack this will do for now) --> Wait for validation query then results.
Is this possible?
I tried using AsynTask inside the Service but still to no avail, I always get Connection timeout error.
DEMOSERVICE
#Override
public IBinder onBind(Intent intent) {
return new IDemoService.Stub() {
#Override
/**
* Login validation implementation
*/
public boolean login(String id, String password)
throws RemoteException {
UserLoginTask userLoginTask = new UserLoginTask(id, password);
try {
return userLoginTask.execute((Void) null).get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
};
}
USERLOGINTASK
private class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
private String uId;
private String uPassword;
public UserLoginTask(String id, String password) {
uId = id;
uPassword = password;
}
#Override
protected Boolean doInBackground(Void... arg0) {
Connection conn;
try {
int count = 0;
Class.forName("org.postgresql.Driver");
String url = "jdbc:postgresql://xxx.xxx.x.xxx/test_db?user=postgres&password=password";
conn = DriverManager.getConnection(url);
if (conn != null) {
Statement st = conn.createStatement();
String sql = "Select count(*) as cnt from tbl_persons where id = '"
+ uId.toUpperCase(Locale.getDefault()).trim()
+ "' AND pwd='" + uPassword.trim() + "';";
Log.d("DemoService", "Login sql - " + sql);
ResultSet rs = st.executeQuery(sql);
while (rs.next()) {
count = rs.getInt("cnt");
}
rs.close();
st.close();
conn.close();
if (count == 0)
return false;
return true;
}
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
}

Related

How do I use this already built database class to throw queries to my DB like "SELECT * FROM TABLE" on Android?

So I'm back on Android Development, still getting to know stuff again, and this is the first time I make an app that connects to a database in a server.
So far I have used this code to be able to connect to the server and it works by showing that the "connection is true"
The only thing I want to know now is how I can use this same class to throw queries to do things like "SELECT * FROM TABLE" etc.
I know that it bad practice to do what I'm doing by connecting direct to a db, but this is just a very small app that will not do important stuff but just so I can understand things better in Android.
package com.example.databasetest;
import java.sql.Connection;
import java.sql.DriverManager;
public class Database {
private Connection connection;
private final String host = "xxxxx";
private final String database = "xxxx";
private final int port = "xxxx";
private final String user = "xxxx";
private final String pass = "xxxx";
private String url = "jdbc:postgresql://%s:%d/%s";
private boolean status;
public Database() {
this.url = String.format(this.url, this.host, this.port, this.database);
connect();
//this.disconnect();
System.out.println("connection status:" + status);
}
private void connect() {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
Class.forName("org.postgresql.Driver");
connection = DriverManager.getConnection(url, user, pass);
status = true;
System.out.println("connected:" + status);
} catch (Exception e) {
status = false;
System.out.print(e.getMessage());
e.printStackTrace();
}
}
});
thread.start();
try {
thread.join();
} catch (Exception e) {
e.printStackTrace();
this.status = false;
}
}
public Connection getExtraConnection(){
Connection c = null;
try {
Class.forName("org.postgresql.Driver");
c = DriverManager.getConnection(url, user, pass);
} catch (Exception e) {
e.printStackTrace();
}
return c;
}
}
This is my MainActivity:
package com.example.databasetest
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val db = Database()
}
}
Edit:
Ok, so I tried to replicate the "private void connect()" function into a "public void load()" function which sends sql queries to the db.
public void load() {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
Connection con;
Statement stmt;
String sql = "SELECT * FROM INVENTORY";
Class.forName("org.postgresql.Driver");
con = DriverManager.getConnection(url, user, pass);
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()){
int id = rs.getInt("ID");
String description = rs.getString("DESCRIPTION");
String amount = rs.getString("AMOUNT");
String local = rs.getString("LOCAL");
System.out.print("ID: "+id);
System.out.print("Description: "+description);
System.out.print("Amount: "+amount);
System.out.print("Local: "+local);
con.close();
}
} catch (Exception e) {
status = false;
System.out.print(e.getMessage());
e.printStackTrace();
}
}
});
thread.start();
try {
thread.join();
} catch (Exception e) {
e.printStackTrace();
this.status = false;
}
}
The problem now is that in the Logcat this warning appears:
"I/Choreographer: Skipped 83 frames! The application may be doing too much work on its main thread."
It worked for one time, but then now it just gives me this error. The database doesn't even have that much info, it has like 12 rows.
How can I multithread (?) this function when accessing the database?
This is where I call db.load() in my MainActivity:
override fun onOptionsItemSelected(item: MenuItem): Boolean {
val id = findViewById<EditText>(R.id.ID)
return when (item.itemId) {
R.id.load -> {
val db = Database()
db.load()
true
}
You have got the instance of Connection, does the Connection contain a method to execute SQL queries (or sth. like that)?
public class Database {
...
public Cursor query(String sql) { //cursor is nullable
// TODO connection.xxxx
}
}
In the class MainActivity, you can access the method query to get the Cursor...
[Update]
public class Database {
private Connection connection;
private final String host = "xxxxx";
private final String database = "xxxx";
private final int port = 9999;//needs int
private final String user = "xxxx";
private final String pass = "xxxx";
private final String SQL_DRIVER = "org.postgresql.Driver";
private String url = "jdbc:postgresql://%s:%d/%s";
private boolean status;
public Database() {
this.url = String.format(this.url, this.host, this.port, this.database);
System.out.println("the final url is " + this.url);
}
public Connection getConnection() {
Connection c = null;
try {
Class.forName(SQL_DRIVER);
c = DriverManager.getConnection(url, user, pass);
status = true;
System.out.println("connected:" + status);
} catch (Exception e) {
status = false;
System.out.print(e.getMessage());
e.printStackTrace();
}
return c;
}
public void load() {
Thread thread = new Thread(new Runnable() {
Connection con;
#Override
public void run() {
try {
Statement stmt;
String sql = "SELECT * FROM INVENTORY";
Class.forName(SQL_DRIVER);
con = DriverManager.getConnection(url, user, pass);
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
status = true;
while (rs.next()) {
int id = rs.getInt("ID");
String description = rs.getString("DESCRIPTION");
String amount = rs.getString("AMOUNT");
String local = rs.getString("LOCAL");
System.out.print("ID: " + id);
System.out.print("Description: " + description);
System.out.print("Amount: " + amount);
System.out.print("Local: " + local);
}
} catch (Exception e) {
try {
con.close();
} catch (SQLException exp) {
exp.printStackTrace();
}
status = false;
System.out.print(e.getMessage());
e.printStackTrace();
}
}
});
thread.start();
// try to comment
//try {
// thread.join();
//} catch (Exception e) {
// e.printStackTrace();
// this.status = false;
//}
}
}

Send gcm Notifications to specific user

I am working on GCM.
I am able to send notifications to all registered android devices from my local server.
I have saving regid and userid in database. my requirement is send notifications to particular devices.how to do that?
am using java on server side. Any answers will save me..i posted server side code
server side code
public class GCMNotification extends HttpServlet {
private static final long serialVersionUID = 1L;
// Put your Google API Server Key here
private static final String GOOGLE_SERVER_KEY = "AIzaSyDzlDr2viv-EghBFZGpjwXcDoqh24Wt9yE";
static final String MESSAGE_KEY = "message";
static final String TITLE_KEY = "title";
static final String IMAGE_KEY= "image";
static final String ORDER_KEY= "order";
private List<String> androidTargets = new ArrayList<String>();
public GCMNotification() {
super();
// androidTargets.add(re);
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
//doPost(request, response);
Connection con=null;
try {
Class.forName("com.mysql.jdbc.Driver");
//Get a connection to the particular database
con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/my_db","root","root1");
String sql;
sql = "SELECT regid, fname, email FROM my_db.Persons";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("regid");
String first = rs.getString("fname");
String last = rs.getString("email");
androidTargets.add(id);
}
rs.close();
stmt.close();
con .close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
//MulticastResult result = null;
//Result result1=null;
Writer writer=null;
Connection con=null;
PrintWriter out = response.getWriter();
String share = request.getParameter("shareRegId");
// GCM RedgId of Android device to send push notification
String reg = "";
String emailId="";
String fname="";
if (share != null && !share.isEmpty()) {
reg = request.getParameter("regId");
emailId=request.getParameter("email");
fname=request.getParameter("name");
System.out.println("regId: " + reg);
System.out.println("mailid " + emailId);
System.out.println("name "+ fname);
try {
//Load the Driver for connection
Class.forName("com.mysql.jdbc.Driver");
//Get a connection to the particular database
con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/my_db","root","root1");
PreparedStatement pst=con.prepareStatement("insert into my_db.Persons(regid,email,fname) values(?,?,?)");
pst.setString(1,reg);
pst.setString(2,emailId);
pst.setString(3,fname);
int i = pst.executeUpdate();
if(i!=0){
pw.println("<br>Record has been inserted");
}
else{
pw.println("failed to insert the data");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
MulticastResult result1=null;
String userMessage = request.getParameter("message");
String imageUrl = request.getParameter("image");
String order1=request.getParameter("odt");
String titl=request.getParameter("tit");
Sender sender = new Sender(GOOGLE_SERVER_KEY);
Message message = new Message.Builder().timeToLive(10000)
.delayWhileIdle(false)
.addData(TITLE_KEY, titl)
.addData(MESSAGE_KEY,userMessage)
.addData(IMAGE_KEY, imageUrl)
.addData(ORDER_KEY, order1)
.build();
try {
// use this for multicast messages. The second parameter
HashSet<String> set = new HashSet<String>(androidTargets);
// Create ArrayList from the set.
ArrayList<String> result = new ArrayList<String>(set);
System.out.println("reg2:"+result);
// of sender.send() will need to be an array of register ids.
result1 = sender.send(message, result,1);
/* if (result1.getResults() != null) {
int canonicalRegId = result1.getCanonicalIds();
if (canonicalRegId != 0) {
}
} else {
int error = result1.getFailure();
System.out.println("Broadcast failure: " + error);
}*/
} catch (Exception e) {
e.printStackTrace();
}
request.setAttribute("pushStatus", result1.toString());
request.getRequestDispatcher("index.jsp")
.forward(request, response);
}
}
Simply add a where clause to your sql query to filter out the exact user you want to deal with. If you want to filter the user by the email then use something like this..
sql = "SELECT regid, fname, email FROM my_db.Persons where email = 'abc#gmail.com'";

Why AsyncTask make infinity loop

i always found the answer to my Questions in StackoverFlow but not this time, so i'm trying to ask it, and i hope that you can help me, and Thanks even if you coudn't.
I'm trying to use the mysql query
Select * From `Table`
and returning a resultset from asynctask using .get() the problem is that after executing the query and getting the returned value when the asynctask tries to get back in the program he loop infinity,
PS:when i use other query like "Select * From Table Where something = other thing" it works perfectly.
here 2 methodes in my class DataBaseManager which got 2 params: Conn type connexion and member type ResultSet
/* asynctask pour la connexion*/public void Selmem(String ...a){
final class Select_member extends AsyncTask<String, Integer, ResultSet> {
#Override
protected ResultSet doInBackground(String... params) {
try {
ResultSet member2;
String myDriver = "com.mysql.jdbc.Driver";
Class.forName(myDriver).newInstance();
conn = DriverManager.getConnection(params[0], "root", "");
if(params.length==6)
member2=select_member(params[1],params[2],params[3],params[4],params[5]);
else
member2=select_member(params[1],params[2],params[3]);
conn.close();
return(member2);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.i("printf","NOT SELECTED");
return null;
}
// TODO Auto-generated method stub
}
}
try {
if(a.length==6)
member=new Select_member().execute(a[0],a[1],a[2],a[3],a[4],a[5]).get();
else
member=new Select_member().execute(a[0],a[1],a[2],a[3]).get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public ResultSet select_member(String ...a){
String sql;
PreparedStatement prest;
try {
if(a.length==5)
{
sql="SELECT * FROM `"+a[0]+"` WHERE "+a[1]+" = '"+a[2]+"' and `"+a[3]+"` = '"+a[4]+"'";
prest= conn.prepareStatement(sql);
}
else if (a[2].equals(""))
{
sql="SELECT * FROM `"+a[0]+"`";
prest= conn.prepareStatement(sql);
}
else
{
sql="SELECT * FROM `"+a[0]+"` WHERE `"+a[1]+"` = '"+a[2]+"'";
prest= conn.prepareStatement(sql);
}
prest= conn.prepareStatement(sql);
ResultSet member1;
member1 = prest.executeQuery();
ResultSet member2=member1;
if(member1.next())
return member2;
else
return null;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
this is where i Call my Class to try to Select from my database, ps: the program dosen't even get to my loop (so i don't think that my loop is the problem i used the debugger to see where is the problem)
public class Deniere_Op extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_deniere__op);
Intent activite=getIntent();
DataBaseManager base=new DataBaseManager();
String login=activite.getExtras().getString("login");
base.Selmem("jdbc:mysql://10.0.2.2:3306/db_app",login , "", "");
if(base.member==null)
{
Toast.makeText(getApplicationContext(), "Aucune Transaction",Toast.LENGTH_LONG).show();
}
else
{int i=0;
do{i++;
for(int j=1;j<=6;j++)
{String concat=new String();
concat=concat.valueOf(i)+concat.valueOf(j);
String message;
try {
message = base.member.getString(j);
String a="textview"+concat;
int resID=getResources().getIdentifier(a, "id",getPackageName());
TextView text=(TextView) findViewById(resID);
text.setText(message);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
base.member.next();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}while(base.member!=null);
}
}
I hope that this can make you understand my problem and helps you to help me :D :D.
the logcat hope it will help

Get access token from google plus Android

Can anyone tell me what am I doing wrong? I need to get the access token from Google Plus..
I put this in my onConnected() method but I am not getting the access token, instead I am getting error...
Code:
try {
String token = GoogleAuthUtil.getToken(this, mPlusClient.getAccountName() + "", "oauth2:" + Scopes.PLUS_PROFILE +
"https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email");
Log.d("AccessToken", token);
} catch (UserRecoverableAuthException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (GoogleAuthException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Error:
08-07 10:10:24.199: E/GoogleAuthUtil(17203): Calling this from your main thread can lead to deadlock and/or ANRs
Can anyone tell me what would be the correct way to get the Google Plus access token from the user?
You need to put the request for a token in a background thread. I've posted some example code showing how to do it in this question:
"Calling this from your main thread can lead to deadlock and/or ANRs while getting accesToken" from GoogleAuthUtil(Google Plus integration in Android)
You can access token in onConnected() method. add this code onConnected() methods scope.
final String SCOPES = "https://www.googleapis.com/auth/userinfo.profile";
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
String ace = "";
try {
ace = GoogleAuthUtil.getToken(getApplicationContext(),
Plus.AccountApi.getAccountName(mGoogleApiClient),
"oauth2:" + SCOPES);
}
catch (IOException e) {
e.printStackTrace();
}
catch (GoogleAuthException e) {
e.printStackTrace();
}
Log.i("", "mustafa olll " + ace);
return null;
}
}.execute();
You need to fetch it using async task.
public void onConnected(Bundle connectionHint) {
// Reaching onConnected means we consider the user signed in.
Log.i(TAG, "onConnected");
// Update the user interface to reflect that the user is signed in.
mSignInButton.setEnabled(false);
mSignOutButton.setEnabled(true);
mRevokeButton.setEnabled(true);
// Retrieve some profile information to personalize our app for the user.
Person currentUser = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient);
AsyncTask<Void, Void, String > task = new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
String token = null;
final String SCOPES = "https://www.googleapis.com/auth/plus.login ";
try {
token = GoogleAuthUtil.getToken(
getApplicationContext(),
Plus.AccountApi.getAccountName(mGoogleApiClient),
"oauth2:" + SCOPES);
} catch (IOException e) {
e.printStackTrace();
} catch (GoogleAuthException e) {
e.printStackTrace();
}
return token;
}
#Override
protected void onPostExecute(String token) {
Log.i(TAG, "Access token retrieved:" + token);
}
};
task.execute();
System.out.print("email" + email);
mStatus.setText(String.format(
getResources().getString(R.string.signed_in_as),
currentUser.getDisplayName()));
Plus.PeopleApi.loadVisible(mGoogleApiClient, null)
.setResultCallback(this);
// Indicate that the sign in process is complete.
mSignInProgress = STATE_DEFAULT; }
Your access token will be stored into token variable.
Here is the code you can use. If someone has better suggestion then please post:
/**
* Successfully connected (called by PlusClient)
*/
#Override
public void onConnected(Bundle connectionHint) {
/* First do what ever you wanted to do in onConnected() */
....
....
/* Now get the token using and async call*/
GetGooglePlusToken token = new GetGooglePlusToken(this.getActivity(), mPlusClient);
token.execute();
}
class GetGooglePlusToken extends AsyncTask<Void, Void, String> {
Context context;
private GoogleApiClient mGoogleApiClient;
private String TAG = this.getClass().getSimpleName();
public GetGooglePlusToken(Context context, GoogleApiClient mGoogleApiClient) {
this.context = context;
this.mGoogleApiClient = mGoogleApiClient;
}
#Override
protected String doInBackground(Void... params) {
String accessToken1 = null;
try {
Bundle bundle = new Bundle();
String accountname = Plus.AccountApi.getAccountName(mGoogleApiClient);
String scope = "oauth2:" + Scopes.PLUS_LOGIN + " " + "https://www.googleapis.com/auth/userinfo.email" + " https://www.googleapis.com/auth/plus.profile.agerange.read";
accessToken1 = GoogleAuthUtil.getToken(context,
accountname,
scope);
return accessToken1;
} catch (IOException transientEx) {
// network or server error, the call is expected to succeed if you try again later.
// Don't attempt to call again immediately - the request is likely to
// fail, you'll hit quotas or back-off.
//TODO: HANDLE
Log.e(TAG, "transientEx");
transientEx.printStackTrace();
accessToken1 = null;
} catch (UserRecoverableAuthException e) {
// Recover
Log.e(TAG, "UserRecoverableAuthException");
e.printStackTrace();
accessToken1 = null;
} catch (GoogleAuthException authEx) {
// Failure. The call is not expected to ever succeed so it should not be
// retried.
Log.e(TAG, "GoogleAuthException");
authEx.printStackTrace();
accessToken1 = null;
} catch (Exception e) {
Log.e(TAG, "RuntimeException");
e.printStackTrace();
accessToken1 = null;
throw new RuntimeException(e);
}
Log.wtf(TAG, "Code should not go here");
accessToken1 = null;
return accessToken1;
}
#Override
protected void onPostExecute(String response) {
Log.d(TAG, "Google access token = " + response);
}
}

OAuth1a retrieveRequestToken throw null

i have some trouble with the OAuth signing.
on the point i expect to get the retrieveRequestToken i got the following error:
01-05 17:26:02.775: W/System.err(24358): oauth.signpost.exception.OAuthCommunicationException: Communication with the service provider failed: null
i have no idea why i get this. Any suggestions here?
My Code:
connectionDec = new ConnectionDetector(getApplicationContext());
// Check if Internet present
if (!connectionDec.isConnectingToInternet())
{
// Internet Connection is not present
// alert.showAlertDialog(MainActivity.this,
// "Internet Connection Error",
// "Please connect to working Internet connection", false);
// stop executing code by return
return;
}
CommonsHttpOAuthConsumer consumer =
new CommonsHttpOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
CommonsHttpOAuthProvider provider =
new CommonsHttpOAuthProvider(REQUEST_TOKEN_URL, ACCESS_TOKEN_URL,
AUTHORIZE_URL);
provider.setOAuth10a(true);
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String token = sharedPreferences.getString("token", null);
String tokenSecret = sharedPreferences.getString("token_secret", null);
if (token == null || tokenSecret == null)
{
Map requestHeaders = provider.getRequestHeaders();
requestHeaders.put("User-Agent", USER_AGENT);
requestHeaders.put("Accept-Encoding", "gzip");
try
{
String authUrl = provider.retrieveRequestToken(consumer, CALLBACK_URL);
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl)));
}
catch (OAuthMessageSignerException e)
{
e.printStackTrace();
}
catch (OAuthNotAuthorizedException e)
{
e.printStackTrace();
}
catch (OAuthExpectationFailedException e)
{
e.printStackTrace();
}
catch (OAuthCommunicationException e)
{
e.printStackTrace();
}
}
else
{
}
any tipps and helps ... thank you
PS: It is Discogs and not Twitter
Greets Mad
OK, i have answered the question myself ... i have implement a asynctask like the following and it works:
public class StartUpActivity extends Activity implements OnClickListener
{
private static String CONSUMER_KEY = "consumerkey";
private static String CONSUMER_SECRET = "yourconsumersecret";
private static String REQUEST_TOKEN_URL = "http://api.discogs.com/oauth/request_token";
private static String AUTHORIZE_URL = "http://www.discogs.com/oauth/authorize";
private static String ACCESS_TOKEN_URL = "http://api.discogs.com/oauth/access_token";
private static String USER_AGENT = "youruseragent";
private static String CALLBACK_URL = "http://www.callback.com";
private ConnectionDetector connectionDec;
private SharedPreferences sharedPreferences;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.start_up_layout);
connectionDec = new ConnectionDetector(getApplicationContext());
// Check if Internet present
if (!connectionDec.isConnectingToInternet())
{
// Internet Connection is not present
// alert.showAlertDialog(MainActivity.this,
// "Internet Connection Error",
// "Please connect to working Internet connection", false);
// stop executing code by return
return;
}
}
class ProgressTask extends AsyncTask<Integer, Integer, Void>{
#Override
protected void onPreExecute() {
// initialize the progress bar
// set maximum progress to 100.
}
#Override
protected void onCancelled() {
// stop the progress
}
#Override
protected Void doInBackground(Integer... params) {
// get the initial starting value
int start=params[0];
// increment the progress
try {
CommonsHttpOAuthConsumer consumer = new CommonsHttpOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
CommonsHttpOAuthProvider provider =
new CommonsHttpOAuthProvider(REQUEST_TOKEN_URL, ACCESS_TOKEN_URL, AUTHORIZE_URL);
provider.setOAuth10a(true);
// Check if token and tokensecret are already stored at app preferences
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String token = sharedPreferences.getString("token", null);
String tokenSecret = sharedPreferences.getString("token_secret", null);
if (token == null || tokenSecret == null)
{
Map<String, String> requestHeaders = provider.getRequestHeaders();
requestHeaders.put("User-Agent", USER_AGENT);
requestHeaders.put("Accept-Encoding", "gzip");
try
{
String authUrl = provider.retrieveRequestToken(consumer, CALLBACK_URL);
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl)));
}
catch (OAuthMessageSignerException e)
{
e.printStackTrace();
}
catch (OAuthNotAuthorizedException e)
{
e.printStackTrace();
}
catch (OAuthExpectationFailedException e)
{
e.printStackTrace();
}
catch (OAuthCommunicationException e)
{
e.printStackTrace();
}
}
else
{
}
}
catch (Exception e) {
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
// increment progress bar by progress value
}
#Override
protected void onPostExecute(Void result) {
// async task finished
}
}
}

Categories

Resources