private static String CONSUMER_KEY = "mrnCC41nxtwkdFAmToEhtg";
private static final String CONSUMER_SECRET = "kmmVuahEspGvdl14aCD1GSBZpeHbxvkpAez7aKaaQ";
EditText editPinCode;
LinearLayout lin;
public Logger slr;
LinearLayout container;
public LoginT(){
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.twitter);
editPinCode = new EditText(this);
lin = (LinearLayout)findViewById(R.id.LinearLayout01);
handleEvent = new Handler();
twitterConnection = new TwitterFactory().getInstance();
context = this;
oHelper = new OAuthHelp(this);
getTwitter(context);
}
/**
* Connects to twittter
* #param v
*/
public void getTwitter(Context ctx) { //updated code
handleEvent.post(new Runnable() {
// handleEvent.postAtFrontOfQueue(new Runnable() {
public void run() {
if (oHelper.hasAccessToken())
{
Log.e("run if","run");
oHelper.configureOAuth(twitterConnection);
try
{
i=i+1;
Log.e("run try","run");
twitterConnection.updateStatus(Calendar.MINUTE+i+"Hi this is Arun......");
//twitterConnection.se
Log.e("finish","start");
finish();
Log.e("finish","end");
}
catch (TwitterException e)
{
Log.d("TWEET", "Error Updating status " + e.getMessage());
e.printStackTrace();
}
}
else
{
Log.e("run else","run");
try {
twitterConnection.setOAuthConsumer(CONSUMER_KEY,CONSUMER_SECRET);
requestToken = twitterConnection.getOAuthRequestToken("");
Log.e("REQUEST_TOKEN",requestToken+"");
webViewDialog(requestToken.getAuthorizationURL(), 0);
}
catch (TwitterException e)
{
e.printStackTrace();
}
}
}});
}
/**
* Shows Dialog for authentications
*
* #param authorizationURL
* #param type
*/
private void webViewDialog(final String authorizationURL, final int type) {
Log.e("webViewDialog","webViewDialog");
container = new LinearLayout(this);
container.setMinimumWidth(200);
container.setMinimumHeight(320);
webView = new WebView(this);
webView.setMinimumWidth(200);
webView.setMinimumHeight(380);
webView.getSettings().setJavaScriptEnabled(true);
// webView.dispatchWindowFocusChanged(true);
webView.setWebViewClient(new MyWebViewClient(this,LoginT.this));
webView.loadUrl(authorizationURL);
container.addView(webView);
lin.addView(container);
// Builder webDialog = new AlertDialog.Builder(this);
// webDialog.setView(container).setTitle("Twitter Client").setCancelable(true)
// .show();
}
/**
* Pin code dialog Requests the user to enter pin shown on twitter
*/
public void twitterPinCodeDialog() {
try {
// accessToken = twitterConnection.getOAuthAccessToken(requestToken,ss);
try{
accessToken = twitterConnection.getOAuthAccessToken(requestToken);
}
catch(Exception e1){
Log.w("Excep e1",e1+"");
}
oHelper.storeAccessToken(accessToken);
Log.w("ohelper",oHelper.toString());
twitterConnection.updateStatus("Tweeted Successfully"+new Date().toString());
Log.e(" ","2 "+accessToken);
Log.e(" ","3");
webView.destroy();
webView.removeAllViews();
container.removeAllViews();
this.finish();
// Log.i("Access Token:", accessToken.getToken());
// Log.i("Access Secret:", accessToken.getTokenSecret());
} catch (TwitterException te) {
oHelper.storeAccessToken(accessToken);
try {
twitterConnection.updateStatus("HI.... ");
} catch (TwitterException e) {
e.printStackTrace();
}
}
}
#Override
protected Dialog onCreateDialog(int id)
{
switch (id) {
// case DIALOG_LOADING:
// {
// // dialog = new ProgressDialog(this);
// dialog.setMessage("Please wait while loading...");
// dialog.setIndeterminate(true);
// dialog.setCancelable(true);
// return dialog;
// }
}
return null;
}
//
// #Override
public void dismiss() {
Log.w("dismiss","dismiss");
try{
// webView.destroy();
// webView.removeAllViews();
// container.removeAllViews();
// this.finish();
System.exit(0);
}catch(Exception e){
e.printStackTrace();
}
}
//
#Override
public boolean onSearchRequested() {
Log.e("Search","Search");
return super.onSearchRequested();
}
I use the above Code for making connection for twitter but it only works for one time if I want another time for connection then it never provide me second time connection.
Thankx
Could this be an Activity lifecycle issue? Your call to getTwitter() occurs in onCreate, which only gets called when the Activity is created. If a user navigates away then comes back to your app, it may still be running, so onCreate would not get called again. Have a look at the Activity lifecycle, and add some debug code to each of the lifecycle methods (onResume, onPause etc) to get an idea of when they are called.
Related
how to stop asynctask on android backpress i want to stop this activity so that when it goes back to previous activity this activity is completely closed
this activity does its work in background , as it is supposed to do, my problem is when we click the android back button this activity should completely stop and go back to first activity i did somne search and came to know the asynctask should be stopped on back press
i tried that but ii doesnot seem to work how can this be done in the below code
package com.Blog.blogname;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.Toast;
import com.Blog.blogname.parser.DOMParser;
import com.Blog.blogname.parser.RSSFeed;
public class SplashActivity extends Activity {
//String RSSFEEDURL = "http://feeds.blogname.com/blogname?format=xml";
//String RSSFEEDURL = "http://blogname.blogname.com/feeds/posts/default?alt=rss";
//int position = i.getExtras().getInt("position");
//String[] country = i.getStringArrayExtra("country");
//Toast.makeText(this, i.getStringArrayExtra("country") + "was selected" , Toast.LENGTH_LONG).show();
//String RSSFEEDURL = "http://blogname.blogspot.com//feeds/posts/default/-/Awards?alt=rss";
//String RSSFEEDURL = "http://blogname.blogspot.com//feeds/posts/default/-/country[position]?alt=rss";
RSSFeed feed;
String fileName;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
fileName = "TDRSSFeed.td";
Intent i = getIntent();
int position = i.getExtras().getInt("position");
String[] country = i.getStringArrayExtra("country");
// //public String RSSFEEDURL = "http://blogname.blogspot.com//feeds/posts/default/-/Awards?alt=rss";
Toast.makeText(getApplicationContext(), country[position], Toast.LENGTH_SHORT).show();
//Toast.makeText(getApplicationContext(), country[position], Toast.LENGTH_SHORT).show();
File feedFile = getBaseContext().getFileStreamPath(fileName);
ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (conMgr.getActiveNetworkInfo() == null) {
// No connectivity. Check if feed File exists
if (!feedFile.exists()) {
// No connectivity & Feed file doesn't exist: Show alert to exit
// & check for connectivity
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(
"Unable to reach server, \nPlease check your connectivity.")
.setTitle("TD RSS Reader")
.setCancelable(false)
.setPositiveButton("Exit",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int id) {
finish();
}
});
AlertDialog alert = builder.create();
alert.show();
} else {
// No connectivty and file exists: Read feed from the File
Toast toast = Toast.makeText(this,
"No connectivity!",
Toast.LENGTH_LONG);
toast.show();
//feed = ReadFeed(fileName);
startLisActivity(feed);
}
} else {
// Connected - Start parsing
new AsyncLoadXMLFeed().execute();
}
}
private void startLisActivity(RSSFeed feed) {
Bundle bundle = new Bundle();
bundle.putSerializable("feed", feed);
// launch List activity
Intent intent = new Intent(SplashActivity.this, ListActivity.class);
intent.putExtras(bundle);
startActivity(intent);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
// kill this activity
finish();
}
private class AsyncLoadXMLFeed extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
// Obtain feed
DOMParser myParser = new DOMParser();
Intent i = getIntent();
int position = i.getExtras().getInt("position");
String[] country = i.getStringArrayExtra("country");
//feed = myParser.parseXml(RSSFEEDURL);
//feed = myParser.parseXml("http://blogname.blogspot.com//feeds/posts/default/-/Awards?alt=rss");
feed = myParser.parseXml("http://blogname.blogspot.com//feeds/posts/default/-/" + country[position] + "?alt=rss");
if (feed != null && feed.getItemCount() > 0)
WriteFeed(feed);
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
startLisActivity(feed);
}
}
// Method to write the feed to the File
private void WriteFeed(RSSFeed data) {
FileOutputStream fOut = null;
ObjectOutputStream osw = null;
try {
fOut = openFileOutput(fileName, MODE_PRIVATE);
osw = new ObjectOutputStream(fOut);
osw.writeObject(data);
osw.flush();
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try {
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// Method to read the feed from the File
// private RSSFeed ReadFeed(String fName) {
//
// FileInputStream fIn = null;
// ObjectInputStream isr = null;
//
// RSSFeed _feed = null;
// File feedFile = getBaseContext().getFileStreamPath(fileName);
// if (!feedFile.exists())
// return null;
//
// try {
// fIn = openFileInput(fName);
// isr = new ObjectInputStream(fIn);
//
// _feed = (RSSFeed) isr.readObject();
// }
//
// catch (Exception e) {
// e.printStackTrace();
// }
//
// finally {
// try {
// fIn.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
//
// return _feed;
//
// }
// #Override
// public void onBackPressed()
// {
// finish();
// }
// #Override
// public void onBackPressed(){
// if(condition){
// super.onBackPressed(); //Normal behaviour
// } else {
// startLisActivity(feed);
// }
// }
//private static final int TIME_INTERVAL = 2000; // # milliseconds, desired time passed between two back presses.
//private long mBackPressed;
//#Override
// public void onBackPressed()
// {
// if (mBackPressed + TIME_INTERVAL > System.currentTimeMillis())
// {
// super.onBackPressed();
// return;
// }
// else if(mBackPressed + TIME_INTERVAL < System.currentTimeMillis()){ Toast.makeText(getBaseContext(), "Tap back button in order to exit", Toast.LENGTH_SHORT).show(); }
// else {
// //startLisActivity(feed);
// #Override
// protected void onPostExecute(Void result) {
// super.onPostExecute(result);
//
// startLisActivity(feed);
// }
//}
// mBackPressed = System.currentTimeMillis();
//}
#Override
// public void onBackPressed() {
// //DOMParser().cancel(true);
// AsyncLoadXMLFeed.cancel(true);
// // If you want to finish the activity you can use below code
// finish();
// }
// public void onBackPressed()
// {
//
// .cancel(true);
// }
//public void onBackPressed(){
//
//
// if (AsyncLoadXMLFeed != null) if (AsyncLoadXMLFeed.getStatus() == Status.RUNNING) AsyncLoadXMLFeed.cancel(true);
// finish();
// //overridePendingTransition(R.anim.zoom_enter,R.anim.zoom_exit);
// }
}
Simply call cancel in activities onDestroy()
public SplashActivity extends Activity {
private AsyncLoadXMLFeed loader;
#Override
public void onCreate(Bundle b){
super.onCreate(b);
...
// Connected - Start parsing
loader = new AsyncLoadXMLFeed();
loader.execute();
}
#Override
public void onDestroy(){
super.onDestroy();
// Cancel the task
loader.cancel(true);
}
}
The official android documentation says:
A task can be cancelled at any time by invoking cancel(boolean).
Invoking this method will cause subsequent calls to isCancelled() to
return true. After invoking this method, onCancelled(Object), instead
of onPostExecute(Object) will be invoked after
doInBackground(Object[]) returns. To ensure that a task is cancelled
as quickly as possible, you should always check the return value of
isCancelled() periodically from doInBackground(Object[]), if possible
(inside a loop for instance.)
You need to keep a reference to your running AsyncTask object and when back is pressed (or the Activity is paused) you need to call the cancel() method of the instance object. Your commented out code is trying to call it as a static method, which it is not.
The ProgressDialog has a convenient method that gets called when the user press back.
taskParseKmlDownload = new TaskParseKmlDownload(kmlSummary,
new WeakReference<Context>(this),
this, mMap);
taskParseKmlDownload.execute();
taskParseKmlDownloadProgress = new ProgressDialog(this);
taskParseKmlDownloadProgress.setMessage("Parsing KML File");
taskParseKmlDownloadProgress.show();
taskParseKmlDownloadProgress
.setOnCancelListener(new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
taskParseKmlDownload.cancel(false);
}
});
Then in the task you have to check .isCanceled()
Below I'm simply returning -1 if the user cancels the task.
// check for cancel before next download
if (isCancelled()) {
return RESULT_ABORTED;
}
I am using Androids SaveSharedPreference to allow a user to auto login once they already logged in previously. For a user to gain access, their login information must be sent to my server using webscokets, and once a connection is made they will be able to access their accounts.
In terms of present functionality, the users can log into the app the first time and use all the features. The problem arises as the user closes out, not logs out, and attempts to access again and the error below is thrown and the app crashes:
and then
I have seen that the NullPoint error on line 207 of LoggingIn is at:
result = imService.authenticateUser(
SaveSharedPreference
.getUserName(getApplicationContext()),
SaveSharedPreference
.getPassword(getApplicationContext()));
The remaining code of the class in the onCreate method of the LoggingIn class called once app starts:
protected static final int NOT_CONNECTED_TO_SERVICE = 0;
protected static final int FILL_BOTH_USERNAME_AND_PASSWORD = 1;
public static final String AUTHENTICATION_FAILED = "0";
public static final String FRIEND_LIST = "FRIEND_LIST";
protected static final int MAKE_SURE_USERNAME_AND_PASSWORD_CORRECT = 2;
protected static final int NOT_CONNECTED_TO_NETWORK = 3;
private EditText usernameText;
private EditText passwordText;
private Manager imService;
public static final int SIGN_UP_ID = Menu.FIRST;
public static final int EXIT_APP_ID = Menu.FIRST + 1;
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
// This is called when the connection with the service has been
// established, giving us the service object we can use to
// interact with the service. Because we have bound to a explicit
// service that we know is running in our own process, we can
// cast its IBinder to a concrete class and directly access it.
imService = ((MessagingService.IMBinder) service).getService();
if (imService.isUserAuthenticated() == true) {
// Intent i = new Intent(LoggingIn.this, ListOfFriends.class);
Intent i = new Intent(LoggingIn.this, MainActivity.class);
startActivity(i);
LoggingIn.this.finish();
}
}
public void onServiceDisconnected(ComponentName className) {
// This is called when the connection with the service has been
// unexpectedly disconnected -- that is, its process crashed.
// Because it is running in our same process, we should never
// see this happen.
imService = null;
Toast.makeText(LoggingIn.this, R.string.local_service_stopped,
Toast.LENGTH_SHORT).show();
}
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/*
* Start and bind the imService
*/
startService(new Intent(LoggingIn.this, MessagingService.class));
setContentView(R.layout.loggin_in);
setTitle("Login");
ImageButton loginButton = (ImageButton) findViewById(R.id.button1);
usernameText = (EditText) findViewById(R.id.username);
passwordText = (EditText) findViewById(R.id.password);
// If not logged in already
if (SaveSharedPreference.getUserName(getApplicationContext()).length() == 0) {
loginButton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
if (imService == null) {
Toast.makeText(getApplicationContext(),
R.string.not_connected_to_service,
Toast.LENGTH_LONG).show();
// showDialog(NOT_CONNECTED_TO_SERVICE);
return;
} else if (imService.isNetworkConnected() == false) {
Toast.makeText(getApplicationContext(),
R.string.not_connected_to_network,
Toast.LENGTH_LONG).show();
// showDialog(NOT_CONNECTED_TO_NETWORK);
} else if (usernameText.length() > 0
&& passwordText.length() > 0) {
Thread loginThread = new Thread() {
private Handler handler = new Handler();
#Override
public void run() {
String result = null;
try {
result = imService.authenticateUser(
usernameText.getText().toString(),
passwordText.getText().toString());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if (result == null
|| result.equals(AUTHENTICATION_FAILED)) {
/*
* Authenticatin failed, inform the user
*/
handler.post(new Runnable() {
public void run() {
Toast.makeText(
getApplicationContext(),
R.string.make_sure_username_and_password_correct,
Toast.LENGTH_LONG).show();
// showDialog(MAKE_SURE_USERNAME_AND_PASSWORD_CORRECT);
}
});
} else {
/*
* if result not equal to authentication
* failed, result is equal to friend and
* group list of the user 0: is for friends,
* 1: is for groups
*/
handler.post(new Runnable() {
public void run() {
// If log in successful, then save
// username and password to shared
// preferences:
SaveSharedPreference.setUserName(
getApplicationContext(),
usernameText.getText()
.toString());
SaveSharedPreference.setPassword(
getApplicationContext(),
passwordText.getText()
.toString());
Intent i = new Intent(
LoggingIn.this,
MainActivity.class);
startActivity(i);
LoggingIn.this.finish();
}
});
}
}
};
loginThread.start();
} else {
/*
* Username or Password is not filled, alert the user
*/
Toast.makeText(getApplicationContext(),
R.string.fill_both_username_and_password,
Toast.LENGTH_LONG).show();
// showDialog(FILL_BOTH_USERNAME_AND_PASSWORD);
}
}
});
} else {
// If already logged in, pull the information and send to server to
// auto log in
Thread loginThread = new Thread() {
private Handler handler = new Handler();
#Override
public void run() {
String result = null;
try {
result = imService.authenticateUser(
SaveSharedPreference
.getUserName(getApplicationContext()),
SaveSharedPreference
.getPassword(getApplicationContext()));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if (result == null || result.equals(AUTHENTICATION_FAILED)) {
/*
* Authenticatin failed, inform the user
*/
handler.post(new Runnable() {
public void run() {
Toast.makeText(
getApplicationContext(),
R.string.make_sure_username_and_password_correct,
Toast.LENGTH_LONG).show();
// showDialog(MAKE_SURE_USERNAME_AND_PASSWORD_CORRECT);
}
});
} else {
/*
* if result not equal to authentication failed, result
* is equal to friend and group list of the user 0: is
* for friends, 1: is for groups
*/
handler.post(new Runnable() {
public void run() {
Intent i = new Intent(LoggingIn.this,
MainActivity.class);
startActivity(i);
LoggingIn.this.finish();
}
});
}
}
};
loginThread.start();
}
}
How can I allow the users to automatically login with my service successfully?
I am using following class to open a link in child browser , but unable to track device back button event on Android.
I am using showWebPage method, As there is also close button but i want to track device back button event.
public class ChildBrowser extends Plugin {
protected static final String LOG_TAG = "ChildBrowser";
private static int CLOSE_EVENT = 0;
private static int LOCATION_CHANGED_EVENT = 1;
private String browserCallbackId = null;
private Dialog dialog;
private WebView webview;
private EditText edittext;
private boolean showLocationBar = true;
/**
* Executes the request and returns PluginResult.
*
* #param action The action to execute.
* #param args JSONArry of arguments for the plugin.
* #param callbackId The callback id used when calling back into JavaScript.
* #return A PluginResult object with a status and message.
*/
public PluginResult execute(String action, JSONArray args, String callbackId) {
PluginResult.Status status = PluginResult.Status.OK;
String result = "";
try {
if (action.equals("showWebPage")) {
this.browserCallbackId = callbackId;
// If the ChildBrowser is already open then throw an error
if (dialog != null && dialog.isShowing()) {
return new PluginResult(PluginResult.Status.ERROR, "ChildBrowser is already open");
}
result = this.showWebPage(args.getString(0), args.optJSONObject(1));
if (result.length() > 0) {
status = PluginResult.Status.ERROR;
return new PluginResult(status, result);
} else {
PluginResult pluginResult = new PluginResult(status, result);
pluginResult.setKeepCallback(true);
return pluginResult;
}
}
else if (action.equals("close")) {
closeDialog();
JSONObject obj = new JSONObject();
obj.put("type", CLOSE_EVENT);
PluginResult pluginResult = new PluginResult(status, obj);
pluginResult.setKeepCallback(false);
return pluginResult;
}
else if (action.equals("openExternal")) {
result = this.openExternal(args.getString(0), args.optBoolean(1));
if (result.length() > 0) {
status = PluginResult.Status.ERROR;
}
}
else {
status = PluginResult.Status.INVALID_ACTION;
}
return new PluginResult(status, result);
} catch (JSONException e) {
return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
}
}
/**
* Display a new browser with the specified URL.
*
* #param url The url to load.
* #param usePhoneGap Load url in PhoneGap webview
* #return "" if ok, or error message.
*/
public String openExternal(String url, boolean usePhoneGap) {
try {
Intent intent = null;
if (usePhoneGap) {
intent = new Intent().setClass(this.ctx.getContext(), org.apache.cordova.DroidGap.class);
intent.setData(Uri.parse(url)); // This line will be removed in future.
intent.putExtra("url", url);
// Timeout parameter: 60 sec max - May be less if http device timeout is less.
intent.putExtra("loadUrlTimeoutValue", 60000);
// These parameters can be configured if you want to show the loading dialog
intent.putExtra("loadingDialog", "Wait,Loading web page..."); // show loading dialog
intent.putExtra("hideLoadingDialogOnPageLoad", true); // hide it once page has completely loaded
}
else {
intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
}
this.ctx.startActivity(intent);
return "";
} catch (android.content.ActivityNotFoundException e) {
Log.d(LOG_TAG, "ChildBrowser: Error loading url "+url+":"+ e.toString());
return e.toString();
}
}
/**
* Closes the dialog
*/
private void closeDialog() {
if (dialog != null) {
dialog.dismiss();
}
}
/**
* Checks to see if it is possible to go back one page in history, then does so.
*/
private void goBack() {
if (this.webview.canGoBack()) {
this.webview.goBack();
}
}
/**
* Checks to see if it is possible to go forward one page in history, then does so.
*/
private void goForward() {
if (this.webview.canGoForward()) {
this.webview.goForward();
}
}
/**
* Navigate to the new page
*
* #param url to load
*/
private void navigate(String url) {
InputMethodManager imm = (InputMethodManager)this.ctx.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(edittext.getWindowToken(), 0);
if (!url.startsWith("http") && !url.startsWith("file:")) {
this.webview.loadUrl("http://" + url);
} else {
this.webview.loadUrl(url);
}
this.webview.requestFocus();
}
/**
* Should we show the location bar?
*
* #return boolean
*/
private boolean getShowLocationBar() {
return this.showLocationBar;
}
/**
* Display a new browser with the specified URL.
*
* #param url The url to load.
* #param jsonObject
*/
public String showWebPage(final String url, JSONObject options) {
// Determine if we should hide the location bar.
if (options != null) {
showLocationBar = options.optBoolean("showLocationBar", true);
}
// Create dialog in new thread
Runnable runnable = new Runnable() {
/**
* Convert our DIP units to Pixels
*
* #return int
*/
private int dpToPixels(int dipValue) {
int value = (int) TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP,
(float) dipValue,
ctx.getContext().getResources().getDisplayMetrics()
);
return value;
}
public void run() {
// Let's create the main dialog
dialog = new Dialog(ctx.getContext(), android.R.style.Theme_NoTitleBar);
dialog.getWindow().getAttributes().windowAnimations = android.R.style.Animation_Dialog;
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(true);
dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
public void onDismiss(DialogInterface dialog) {
try {
JSONObject obj = new JSONObject();
obj.put("type", CLOSE_EVENT);
sendUpdate(obj, false);
} catch (JSONException e) {
Log.d(LOG_TAG, "Should never happen");
}
}
});
// Main container layout
LinearLayout main = new LinearLayout(ctx.getContext());
main.setOrientation(LinearLayout.VERTICAL);
// Toolbar layout
RelativeLayout toolbar = new RelativeLayout(ctx.getContext());
toolbar.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, this.dpToPixels(44)));
toolbar.setPadding(this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2));
toolbar.setHorizontalGravity(Gravity.LEFT);
toolbar.setVerticalGravity(Gravity.TOP);
// Action Button Container layout
RelativeLayout actionButtonContainer = new RelativeLayout(ctx.getContext());
actionButtonContainer.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
actionButtonContainer.setHorizontalGravity(Gravity.LEFT);
actionButtonContainer.setVerticalGravity(Gravity.CENTER_VERTICAL);
actionButtonContainer.setId(1);
// Back button
ImageButton back = new ImageButton(ctx.getContext());
RelativeLayout.LayoutParams backLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT);
backLayoutParams.addRule(RelativeLayout.ALIGN_LEFT);
back.setLayoutParams(backLayoutParams);
back.setContentDescription("Back Button");
back.setId(2);
try {
back.setImageBitmap(loadDrawable("www/childbrowser/icon_arrow_left.png"));
} catch (IOException e) {
Log.e(LOG_TAG, e.getMessage(), e);
}
back.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
goBack();
}
});
// Forward button
ImageButton forward = new ImageButton(ctx.getContext());
RelativeLayout.LayoutParams forwardLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT);
forwardLayoutParams.addRule(RelativeLayout.RIGHT_OF, 2);
forward.setLayoutParams(forwardLayoutParams);
forward.setContentDescription("Forward Button");
forward.setId(3);
try {
forward.setImageBitmap(loadDrawable("www/childbrowser/icon_arrow_right.png"));
} catch (IOException e) {
Log.e(LOG_TAG, e.getMessage(), e);
}
forward.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
goForward();
}
});
// Edit Text Box
edittext = new EditText(ctx.getContext());
RelativeLayout.LayoutParams textLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
textLayoutParams.addRule(RelativeLayout.RIGHT_OF, 1);
textLayoutParams.addRule(RelativeLayout.LEFT_OF, 5);
edittext.setLayoutParams(textLayoutParams);
edittext.setId(4);
edittext.setSingleLine(true);
edittext.setText(url);
edittext.setInputType(InputType.TYPE_TEXT_VARIATION_URI);
edittext.setImeOptions(EditorInfo.IME_ACTION_GO);
edittext.setInputType(InputType.TYPE_NULL); // Will not except input... Makes the text NON-EDITABLE
edittext.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
// If the event is a key-down event on the "enter" button
if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
navigate(edittext.getText().toString());
return true;
}
return false;
}
});
// Close button
ImageButton close = new ImageButton(ctx.getContext());
RelativeLayout.LayoutParams closeLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT);
closeLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
close.setLayoutParams(closeLayoutParams);
forward.setContentDescription("Close Button");
close.setId(5);
try {
close.setImageBitmap(loadDrawable("www/childbrowser/icon_close.png"));
} catch (IOException e) {
Log.e(LOG_TAG, e.getMessage(), e);
}
close.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
closeDialog();
}
});
// WebView
webview = new WebView(ctx.getContext());
webview.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
webview.setWebChromeClient(new WebChromeClient());
WebViewClient client = new ChildBrowserClient(edittext);
webview.setWebViewClient(client);
WebSettings settings = webview.getSettings();
settings.setJavaScriptEnabled(true);
settings.setJavaScriptCanOpenWindowsAutomatically(true);
settings.setBuiltInZoomControls(true);
settings.setPluginsEnabled(true);
settings.setDomStorageEnabled(true);
webview.loadUrl(url);
webview.setId(6);
webview.getSettings().setLoadWithOverviewMode(true);
webview.getSettings().setUseWideViewPort(true);
webview.requestFocus();
webview.requestFocusFromTouch();
// Add the back and forward buttons to our action button container layout
actionButtonContainer.addView(back);
actionButtonContainer.addView(forward);
// Add the views to our toolbar
toolbar.addView(actionButtonContainer);
toolbar.addView(edittext);
toolbar.addView(close);
// Don't add the toolbar if its been disabled
if (getShowLocationBar()) {
// Add our toolbar to our main view/layout
main.addView(toolbar);
}
// Add our webview to our main view/layout
main.addView(webview);
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.copyFrom(dialog.getWindow().getAttributes());
lp.width = WindowManager.LayoutParams.FILL_PARENT;
lp.height = WindowManager.LayoutParams.FILL_PARENT;
dialog.setContentView(main);
dialog.show();
dialog.getWindow().setAttributes(lp);
}
private Bitmap loadDrawable(String filename) throws java.io.IOException {
InputStream input = ctx.getAssets().open(filename);
return BitmapFactory.decodeStream(input);
}
};
this.ctx.runOnUiThread(runnable);
return "";
}
/**
* Create a new plugin result and send it back to JavaScript
*
* #param obj a JSONObject contain event payload information
*/
private void sendUpdate(JSONObject obj, boolean keepCallback) {
if (this.browserCallbackId != null) {
PluginResult result = new PluginResult(PluginResult.Status.OK, obj);
result.setKeepCallback(keepCallback);
this.success(result, this.browserCallbackId);
}
}
/**
* The webview client receives notifications about appView
*/
public class ChildBrowserClient extends WebViewClient {
EditText edittext;
/**
* Constructor.
*
* #param mContext
* #param edittext
*/
public ChildBrowserClient(EditText mEditText) {
this.edittext = mEditText;
}
/**
* Notify the host application that a page has started loading.
*
* #param view The webview initiating the callback.
* #param url The url of the page.
*/
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
String newloc;
if (url.startsWith("http:") || url.startsWith("https:") || url.startsWith("file:")) {
newloc = url;
} else {
newloc = "http://" + url;
}
if (!newloc.equals(edittext.getText().toString())) {
edittext.setText(newloc);
}
try {
JSONObject obj = new JSONObject();
obj.put("type", LOCATION_CHANGED_EVENT);
obj.put("location", url);
sendUpdate(obj, true);
} catch (JSONException e) {
Log.d("ChildBrowser", "This should never happen");
}
}
}
}
I have an app that generates music after a user authenticates with OAuth on a webview activity, looking something like this: main player activity-OAuth Activity-back to main player activity. However, the onCreate method is being called twice when going from the OAuth activity, resulting in two audio tracks generated and played at the same time.
Here's part of the code from the MainActivity:
public class MainActivity extends Activity {
int pitch=60;
private static final float VISUALIZER_HEIGHT_DIP = 50f;
Random rn;
boolean isRunning = true;
boolean isPlaying=false;
SeekBar fSlider;
double sliderval;
MediaPlayer mediaPlayer=new MediaPlayer();
ImageButton startStopButton;
ImageButton stopButton;
SeekBar vSlider;
VisualizerView mVisualizerView;
private Visualizer mVisualizer;
ImageButton connectButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// point the slider to the GUI widget
rn = new Random();
fSlider = (SeekBar) findViewById(R.id.frequency);
fSlider.setProgress(0);
vSlider= (SeekBar) findViewById(R.id.seekBar2);
vSlider.setMax(10);
vSlider.setProgress(0);
TextView viewinterval=(TextView) findViewById(R.id.textView2);
viewinterval.setText("");
startStopButton=(ImageButton) findViewById(R.id.imageButton2);
View activity= this.findViewById(R.id.playerActivity);
stopButton=(ImageButton) findViewById(R.id.imageButton1);
RelativeLayout.LayoutParams params= new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, (int)(VISUALIZER_HEIGHT_DIP * getResources().getDisplayMetrics().density));
params.addRule(RelativeLayout.BELOW, R.id.seekBar2);
mVisualizerView = new VisualizerView(this);
mVisualizerView.setLayoutParams(params);
((ViewGroup) activity).addView(mVisualizerView);
connectButton=(ImageButton) findViewById(R.id.imageButton3);
connectButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
mediaPlayer.pause();
Intent intent= new Intent(getApplicationContext(), WebViewActivity.class);
startActivity(intent);
}
});
if(riskscores.length !=0){
viewinterval.setText("generating audio");
new MIDISequence().execute();
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
protected void onPause() {
super.onPause();
if(mediaPlayer.isPlaying()){
mediaPlayer.pause();
}
}
class MIDISequence extends AsyncTask<String,Void,String>{
Here's the code from my OAuth Activity
public class WebViewActivity extends Activity {
private WebView gWebView;
final String REDIRECT_URI = "https://localhost:5000/receive_code";
final String CLIENT_ID = "can't post it here";
final String CLIENT_SECRET = "can't post it here";
final String SCOPE = "basic names genomes analyses";
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.webview);
gWebView = (WebView) findViewById(R.id.webView1);
gWebView.loadUrl("https://api.23andme.com/authorize/?redirect_uri="
+ REDIRECT_URI + "&response_type=code&client_id=" + CLIENT_ID
+ "&scope=" + SCOPE);
Log.d("WEBVIEW", "got to webpage");
gWebView.setWebViewClient(new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if (url.startsWith(REDIRECT_URI)) {
Log.d("WEBVIEW", "onpagefinished is called");
System.out.println("got to override");
if (url.indexOf("code=") != -1) {
//if the query contains code
String queryString = null;
try {
queryString = new URL(url).getQuery();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(queryString);
String[] params = queryString.split("&");
String code = null;
for (String param : params) {
if (param.startsWith("code=")) {
code = param.substring(param.indexOf('=') + 1);
}
}
gWebView.setVisibility(View.GONE);
new PostRequest().execute(code);
// don't go to redirectUri
}
}
}
});
}
class PostRequest extends AsyncTask<String,Void,String>{
#Override
protected String doInBackground(String... params) {
code retrieving client data.....
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
System.out.println("CPE" + e);
} catch(SocketException ex)
{
Log.e("Error : " , "Error on soapPrimitiveData() " + ex.getMessage());
ex.printStackTrace();
return "error occured";
} catch (JSONException e) {
e.printStackTrace();
return "error occured";
} catch (IllegalStateException e) {
e.printStackTrace();
return "error occured";
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "error occured";
}
}
return "request complete";
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.d("Post result", result);
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
}
}
The onCreate method of the MainActivity is called twice for some reason... What is going on here?
There seems to be a mistake in your implementation. The thing is, you are trying to use an Intent object to navigate back to your MainActivity form WebActvitity. This is a problem. You shouldn't be doing that.
Whenever you wanna move back to your previous activity, you should simply be calling finish() in the current Activity.
In our scenario,the by using Intent in your WebActivity you are creating a new instance for your MainActivity which already exists in the stack(background). Simply calling finish() in the WebActivity should close it and your MainActivity should be visible.
Do the following changes,
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.d("Post result", result);
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
Replace the above method like this,
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.d("Post result", result);
finish();
}
Other than the expected cases, I have observed that only those activities (onCreate) are called twice which are creating new Thread or Runnable, AsyncTask in your case. (I believe this to be a bug in Android).
The solution is simple (though you may not like it :p)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_screen);
if(savedInstanceState == null){
// everything else that doesn't update UI
}
}
It seems you are getting multiple instance of your first activity. use this in manifest of 1st activity:
android:launchMode="singleTop"
else call finish() after doing startActivity() for 2nd activity
I need to change the content of progress dialog when sync activity is running it shows "synchronizing data"
when it has completed it goes for another background activity and still shows the same text what I want is to change the text when it goes to other background task?
protected void onPreExecute() {
mDialog = ProgressDialog.show(viewContext, "", "Synchronizing Data",
true);
};
/*
* (non-Javadoc)
*
* #see android.os.AsyncTask#doInBackground(Params[])
*/
#Override
protected Boolean doInBackground(Void... arg0) {
if (type.contains("ferry")) {
return SynchronizeRepositoryFerry(false);
} else {
boolean value = SynchronizeRepositories(false, initialSync);
mDialog.setTitle("Loading Images");//FROM HERE I WANT TO CHANGE DIALOG
com.jumbybay.businessobjects.User user = new com.jumbybay.businessobjects.User();
DatabaseHelper dbHelper = new DatabaseHelper(viewContext);
IUserRepository repository = dbHelper.getUserRepository();
List<com.jumbybay.businessobjects.User> imageList;
try {
int id;
String url = "http://i.zdnet.com/blogs/3-29-androids.jpg";
imageList = repository.Retrieve();
for (int i = 0; i < imageList.size(); i++) {
user = imageList.get(i);
// url = user.getPicture();
id = user.getId();
fetchImage fetch = new fetchImage();
fetch.savesd(id, url);
}
} catch (SQLException e) {
// TODO Auto-generated catch block// url = user.getPicture();
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return value;
}
}
protected void onProgressUpdate(Integer... progress) {
mDialog.setTitle("lOADING IMAGES...");
}
/*
* (non-Javadoc)
*
* #see android.os.AsyncTask#onPostExecute(java.lang.Object)
*/
#Override
protected void onPostExecute(Boolean result) {
this.syncComplete = result;
mDialog.dismiss();
Intent intent = new Intent();
intent.setClass(viewContext, classType);
viewContext.startActivity(intent);
}
have you tried using it like this
mDialog.setTitle("Loading Images");
mDialog.show();