getDefaultSharedPreferences and an IntentService crash - java

I am trying to run this but It crashes when It gets to getDefaultSharedPreferences().
Why?
Here is the preferences activity. It fires an IntentService when it is destroyed
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.EditTextPreference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
public class CCTDetectorActivity extends PreferenceActivity implements
OnSharedPreferenceChangeListener {
private SharedPreferences settings;
static public String nameOfFile = "name_of_file";
static public String nameOfFileDefaultValue = "detected_f.xml";
static public String portNumber = "port_number";
static public String portNumberDefaultValue = "25015";
static public String keepAlive = "keep_alive";
static public String keepAliveDefaultValue = "3";
static public String nameOfSettings = "settings";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.layout.cct_detector_preferences_ui);
settings = PreferenceManager.getDefaultSharedPreferences(this);
settings.registerOnSharedPreferenceChangeListener(this);
updateViews();
}
#Override
protected void onDestroy() {
Intent intent = new Intent(getBaseContext(), CCTDetectorService.class);
startService(intent);
super.onDestroy();
}
private void updateViews() {
setSummeryfromPreferencesView(nameOfFile, nameOfFileDefaultValue);
setSummeryfromPreferencesView(portNumber, portNumberDefaultValue);
setSummeryfromPreferencesView(keepAlive, keepAliveDefaultValue);
}
private void setSummeryfromPreferencesView(String viewName, String DefValue) {
String value = settings.getString(viewName, DefValue);
EditTextPreference editTextView = (EditTextPreference) findPreference(viewName);
editTextView.setText(value);
editTextView.setSummary(value);
}
public void onSharedPreferenceChanged(SharedPreferences arg0, String arg1) {
updateViews();
}
}
Here is the IntentService that crashes.
The line of the crash is marked with: "here it crashes!"
import android.app.IntentService;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Log;
public class CCTDetectorService extends IntentService {
private File serializedXmlFile;
private DatagramSocket udpSocket;
private boolean m_Listening = true;
private ActiveCCTs activeCCTs = new ActiveCCTs();
private SharedPreferences preferences;
private Serializer serializer = new Persister();
public CCTDetectorService() throws SocketException {
super("CCTDetectorServiceThread");
int port;
String FILENAME;
// here it crashes!
preferences = PreferenceManager.getDefaultSharedPreferences(this);
port = getIntFromSettingsEditText(CCTDetectorActivity.portNumber,
CCTDetectorActivity.portNumberDefaultValue);
activeCCTs.keepAlive = getIntFromSettingsEditText(
CCTDetectorActivity.keepAlive,
CCTDetectorActivity.keepAliveDefaultValue);
FILENAME = preferences.getString(CCTDetectorActivity.nameOfFile,
CCTDetectorActivity.nameOfFileDefaultValue);
serializedXmlFile = new File(FILENAME);
udpSocket = new DatagramSocket(port);
udpSocket.setBroadcast(true);
}
}

You're doing a lot of stuff in the constructor of a Service.
Do not do that. Override #onCreate() and do your setup there. Remember to call super.onCreate().

In case of IntentService, it is better to do initialization in OnHandleIntent .
Also In your Case the Context may not have been initialized. So move the code in constructor to OnHandleIntent

Related

Android - get the value of global variable from every function

I use Android Studio to make an app. I have a file named 'GlobalVariables.java' and this code in it:
public class GlobalVariables extends Application {
public String CallingActivity;
public String getCallVariable() {
return CallingActivity;
}
public void setCallVariable(String Value) {
CallingActivity = Value;
}
}
In the manifest file I have:
<application android:name=".GlobalVariables" .....
I also have a LanguageActivity.java file which has this code:
package com.testApp;
//import android.content.Intent;
//import android.support.v7.app.ActionBarActivity;
import android.app.ListActivity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Toast;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class LanguageActivity extends ListActivity {
// public class CountrycodeActivity extends ListActivity {
public static final String TAG = "MyActivity";
// public static String RESULT_CONTRYCODE = "countrycode";
public String[] countrynames;
private TypedArray imgs;
private List<Country> countryList;
Locale myLocale;
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
populateCountryList();
ArrayAdapter<Country> adapter = new CountryListArrayAdapter(this, countryList);
setListAdapter(adapter);
getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ReadWriteFile RWFile = new ReadWriteFile();
if (position == 0) {
ChangeLanguage("el", getBaseContext());
try {
RWFile.LangWrite("en",getBaseContext());
Log.e(TAG, "LANG === en");
} catch (IOException e) {
e.printStackTrace();
}
}else{
ChangeLanguage("en", getBaseContext());
try {
RWFile.LangWrite("en",getBaseContext());
Log.e(TAG, "LANG === en");
} catch (IOException e) {
e.printStackTrace();
}
}
imgs.recycle(); //recycle images
finish();
}
});
}
private void populateCountryList() {
countryList = new ArrayList<Country>();
countrynames = getResources().getStringArray(R.array.country_names);
//countrycodes = getResources().getStringArray(R.array.country_codes);
imgs = getResources().obtainTypedArray(R.array.country_flags);
for(int i = 0; i < countrynames.length; i++){
countryList.add(new Country(countrynames[i], imgs.getDrawable(i)));
}
}
public class Country {
private String name;
// private String code;
private Drawable flag;
public Country(String name, Drawable flag){
this.name = name;
// this.code = code;
this.flag = flag;
}
public String getName() {
return name;
}
public Drawable getFlag() {
return flag;
}
// public String getCode() {
// return code;
// }
}
public void ChangeLanguage(String value, Context context){
Resources res = context.getResources();
DisplayMetrics dm = res.getDisplayMetrics();
android.content.res.Configuration conf = res.getConfiguration();
conf.locale = new Locale(value.toLowerCase());
res.updateConfiguration(conf, dm);
GlobalVariables mApp = ((GlobalVariables)getApplicationContext());
String Activity = mApp.getCallVariable();
if (Activity.equals("Login")){
final Intent intent = new Intent(LanguageActivity.this, LoginActivity.class);
startActivity(intent);
}else if (Activity.equals("Signup")){
final Intent intent = new Intent(LanguageActivity.this, SignupActivity.class);
startActivity(intent);
}
}
}
When I run the code, the app craches with this error:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
If I change
GlobalVariables mApp = ((GlobalVariables)getApplicationContext());
String Activity = mApp.getCallVariable();
to
String Activity = ((GlobalVariables) this.getApplication()).getCallVariable();
then I get error:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.testApp.GlobalVariables.getCallVariable()' on a null object reference
I did many tries but nothing helped. What will solve my problem anyway?
Why do I do this? I want to know which Activity called ChangeLanguage() to restart it to show the selected language.
Dependency injection will solve your problem. If you use dagger2, solve this kind of problem will be better, because will be easier create singletons. If you want i can post here how you can do this. Comment below this answer if you want me to edit this with dagger2 basics.
Add this to the AndroidManifest.xml:
<application
android:name=".GlobalVariables"/>
Try:
public class GlobalVariables extends Application {
public String CallingActivity;
public staric GlobalVariables instance;
#Override
public void onCreate()
{super.onCreate();
this.instance = this;
}
public String getCallVariable() {
return CallingActivity;
}
public void setCallVariable(String Value) {
CallingActivity = Value;
}
public static GlobalVariables getInstance()
{
return instance;
}
}
String Activity = GlobalVariables.getInstance().getCallVariable();
Try replacing the line
GlobalVariables mApp = ((GlobalVariables)getApplicationContext());
with:
GlobalVariables mApp = new GlobalVariables();
And in line :
String Activity = mApp.getCallVariable();
Replace 'Activity' with 'activity' because Activity is a pre-defined word.
Edit 1: IS this is how you tried:
GlobalVariables mApp = GlobalVariables.getInstance();
mApp.setCallVariable(value);
mApp.getCallVariable();

ADK toolkit Android+Arduino store variable issue

I'm writing a program which is supposed to run "forever". The program is Android application for tablet which exchanges data with Arduino. I have already implemented the code for Arduino and Android, and it exchanges data very well. However, after 2 cycles of work, my instance of AdkManager becomes NULL. As I've read before, Android will null variables from time to time because it has limited resources. However here's the problem - the AdkManager has confirmed bug that once it has been closed, it can't be reopened. Thus I can't re-initiate the AdkManager instance and I need to store it somehow. So far I've been using Application extension. The code is below:
MyApplication:
package org.udoo.androidadkdemobidirect;
import android.app.Application;
import android.content.Context;
import android.hardware.usb.UsbManager;
import me.palazzetti.adktoolkit.AdkManager;
/**
* Created by admin on 8/18/16.
*/
public class MyApplication extends Application {
private String someVariable;
public String getSomeVariable() {
return someVariable;
}
public void setSomeVariable(String someVariable) {
this.someVariable = someVariable;
}
public static class sAdkManager{
private static sAdkManager ourInstance = null;
public static sAdkManager getInstance() {
if (ourInstance==null)
ourInstance = new sAdkManager();
return ourInstance;
}
private static AdkManager mAdkManager = null;
public void write(String s){
mAdkManager.writeSerial(s);
}
public String read(){
return mAdkManager.readSerial();
}
public void open(){
mAdkManager.open();
}
public void close(){
mAdkManager.close();
}
public boolean checkNull(){
return mAdkManager==null;
}
public static void init(Context context){
if(mAdkManager==null) {
mAdkManager = new AdkManager((UsbManager) context.getSystemService(Context.USB_SERVICE));
context.registerReceiver(mAdkManager.getUsbReceiver(), mAdkManager.getDetachedFilter());
}
}
private sAdkManager() {
}
}
}
MainActivity:
package org.udoo.androidadkdemobidirect;
import me.palazzetti.adktoolkit.AdkManager;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.hardware.usb.UsbManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.TextView;
import android.widget.ToggleButton;
//import org.udoo.androidadkdemobidirect.sAdkManager;
public class MainActivity extends Activity{
// private static final String TAG = "UDOO_AndroidADKFULL";
private static String mAdkManager=null;
private ToggleButton buttonLED;
private TextView distance;
private AdkReadTask mAdkReadTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//
//// register a BroadcastReceiver to catch UsbManager.ACTION_USB_ACCESSORY_DETACHED action
// registerReceiver(mAdkManager.getUsbReceiver(), mAdkManager.getDetachedFilter());
buttonLED = (ToggleButton) findViewById(R.id.toggleButtonLed);
distance = (TextView) findViewById(R.id.textViewIntro);
// mAdkManager.open();
TextView tv = (TextView) findViewById(R.id.ppm);
if (mAdkManager==null){
tv.setText("ADK is null. init()");
mAdkManager = new String ("sometext");
}
else{
tv.setText("ADK is not null.");
}
if (MyApplication.sAdkManager.getInstance().checkNull()) {
distance.setText("Null before init");
MyApplication.sAdkManager.init(this);
}
if (MyApplication.sAdkManager.getInstance().checkNull()) {
distance.setText("Null after init");
}
MyApplication.sAdkManager.getInstance().open();
mAdkReadTask = new AdkReadTask();
mAdkReadTask.execute();
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void onDestroy() {
MyApplication.sAdkManager.getInstance().close();
// unregisterReceiver(mAdkManager.getUsbReceiver());
super.onDestroy();
}
// ToggleButton method - send message to SAM3X
public void blinkLED(View v){
if (buttonLED.isChecked()) {
TextView tvdbg = (TextView) findViewById(R.id.ppm);
tvdbg.setText("send 1");
// writeSerial() allows you to write a single char or a String object.
//mAdkManager.writeSerial("1");
MyApplication.sAdkManager.getInstance().write("1");
// mAdkManager.writeSerial("8");
} else {
//mAdkManager.writeSerial("0");
MyApplication.sAdkManager.getInstance().write("0");
}
}
/*
* We put the readSerial() method in an AsyncTask to run the
* continuous read task out of the UI main thread
*/
private class AdkReadTask extends AsyncTask<Void, String, Void> {
private boolean running = true;
public void pause(){
running = false;
}
protected Void doInBackground(Void... params) {
// Log.i("ADK demo bi", "start adkreadtask");
while(running) {
// if (mAdkManager.serialAvailable())
// publishProgress(mAdkManager.readSerial()) ;
publishProgress(MyApplication.sAdkManager.getInstance().read());
}
return null;
}
protected void onProgressUpdate(String... progress) {
distance.setText("You put "+((int)progress[0].charAt(0)-48) + " iqos butts\tRFID OK");
next();
// Log.i(TAG, "received: " + (int)progress[0].charAt(0));
}
}
private void next() {
final Intent intent = new Intent(this, BRActivity.class );
new android.os.Handler().postDelayed(
new Runnable() {
public void run() {
mAdkReadTask.pause();
mAdkReadTask = null;
startActivity(intent);
}
},
3000);
}
}
There are just 2 Activities for now - MainActivity and BRActivity. BRActivity is just a view with "return" button which comes back to MainActivity.
Also what I find interesting - I output the readSerial in TextView to see what I got in reader thread. However on cycle#2 i don't get any output to TextView, but Activity still changes to the next one.
[EDIT]
Apparently the problem was solved when the thread was nulling. However, I still don't get the text update, but I magically get to another screen. Please advice.

React Native: write in AsyncStorage with java

So I have this text on the java-side that arrives from an Intent, which I'd like to save to AsyncStorage to being able to access it through React afterwards.
Any chance I can achieve this?
I have:
package com.myapp;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.content.Intent;
import com.facebook.react.LifecycleState;
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.ReactRootView;
import com.facebook.react.modules.core.DefaultHardwareBackBtnHandler;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.soloader.SoLoader;
public class MainActivity extends Activity implements DefaultHardwareBackBtnHandler {
private ReactInstanceManager mReactInstanceManager;
private ReactRootView mReactRootView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mReactRootView = new ReactRootView(this);
mReactInstanceManager = ReactInstanceManager.builder()
.setApplication(getApplication())
.setBundleAssetName("index.android.bundle")
.setJSMainModuleName("index.android")
.addPackage(new MainReactPackage())
.setUseDeveloperSupport(BuildConfig.DEBUG)
.setInitialLifecycleState(LifecycleState.RESUMED)
.build();
mReactRootView.startReactApplication(mReactInstanceManager, "BrowseItLater", null);
setContentView(mReactRootView);
// This code is from http://developer.android.com/training/sharing/receive.html
Intent intent = getIntent();
String action = intent.getAction();
String type = intent.getType();
if (Intent.ACTION_SEND.equals(action) && type != null) {
handleSendText(intent);
}
}
void handleSendText(Intent intent) {
String sharedText = intent.getStringExtra(Intent.EXTRA_TEXT);
if (sharedText != null) {
// How can I handle this ????
}
}
// ...
}
Or is there any other solution to make MainActivity.java communicate with JS?
After quite some fight I finally found a solution. It doesn't use AsyncStorage as I read in the source code AsyncStorage could actually be located differently (SQLite, or something else) depending on the phone. Would be dirty to duplicate this logic.
Instead, I created a module like the doc suggests and passed the inputText as an argument to the .addPackage(new EphemeralStoragePackage(inputText)) call in MainActivity.java.
The module exposes a method readOnceAsync to the JS world, which I can later call with:
NativeModules.EphemeralStorage.readOnceAsync((text :string) => {
if (text.length) {
this._addValue(text); // this method is in charge of storing in AsyncStorage
}
})
Here's the detail:
// android/app/src/main/java/com/appname/modules/ephemeralstorage/EphemeralStorageModule.java
package com.browseitlater.modules.ephemeralstorage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.Callback;
import java.util.Map;
public class EphemeralStorageModule extends ReactContextBaseJavaModule {
private String inputText;
public EphemeralStorageModule(ReactApplicationContext reactContext, String _inputText) {
super(reactContext);
this.inputText = _inputText;
}
#Override
public String getName() {
return "EphemeralStorage";
}
public String getInputText() {
return inputText;
}
#ReactMethod
public void readOnceAsync(Callback successCallback) {
successCallback.invoke(getInputText());
this.inputText = null;
}
}
And
// android/app/src/main/java/com/appname/modules/ephemeralstorage/EphemeralStoragePackage.java
package com.browseitlater.modules.ephemeralstorage;
import android.app.Activity;
import java.util.*;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
public class EphemeralStoragePackage implements ReactPackage {
private String inputText;
public EphemeralStoragePackage(String _inputText) {
super();
this.inputText = _inputText;
}
#Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
List<NativeModule> modules = new ArrayList<>();
modules.add(new EphemeralStorageModule(reactContext, getInputText()));
return modules;
}
#Override
public List<Class<? extends JavaScriptModule>> createJSModules() {
return Collections.emptyList();
}
#Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return Collections.emptyList();
}
public String getInputText() {
return inputText;
}
}
Finally in MainActivity.java, my onCreate method looks like:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mReactRootView = new ReactRootView(this);
Intent intent = getIntent();
String action = intent.getAction();
String type = intent.getType();
String inputText = intent.getStringExtra(Intent.EXTRA_TEXT);
mReactInstanceManager = ReactInstanceManager.builder()
.setApplication(getApplication())
.setBundleAssetName("index.android.bundle")
.setJSMainModuleName("index.android")
.addPackage(new MainReactPackage())
.addPackage(new EphemeralStoragePackage(inputText))
.setUseDeveloperSupport(BuildConfig.DEBUG)
.setInitialLifecycleState(LifecycleState.RESUMED)
.build();
mReactRootView.startReactApplication(mReactInstanceManager, "BrowseItLater", null);
setContentView(mReactRootView);
}
If you don't want to write a native module, you can do this in MainActivity.java
Declare a global variable inside MainActivity class (don't forget to import com.facebook.react.modules.storage.ReactDatabaseSupplier):
private ReactDatabaseSupplier mReactDatabaseSupplier;
Inside onCreatemethod initialize the global variable:
mReactDatabaseSupplier = ReactDatabaseSupplier.getInstance(getApplicationContext());
Declare a private method to save the key/value pair inside AsyncStorage
private void saveKeyValuePair(String key, String value) {
String sql = "INSERT OR REPLACE INTO catalystLocalStorage VALUES (?, ?);";
SQLiteStatement statement = mReactDatabaseSupplier.get().compileStatement(sql);
try {
mReactDatabaseSupplier.get().beginTransaction();
statement.clearBindings();
statement.bindString(1, key);
statement.bindString(2, value);
statement.execute();
mReactDatabaseSupplier.get().setTransactionSuccessful();
} catch (Exception e) {
Log.w("YOUR_TAG", e.getMessage(), e);
} finally {
try {
mReactDatabaseSupplier.get().endTransaction();
} catch (Exception e) {
Log.w("YOUR_TAG", e.getMessage(), e);
}
}
}
Then you can save key/value pairs like this (inside onCreate, for example):
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mReactDatabaseSupplier = ReactDatabaseSupplier.getInstance(getApplicationContext());
saveKeyValuePair("myAsyncStorageKey", "myValueInAsyncStorageKey");
}
This is a simple way to save in AsyncStorage of a React Native application. Consider writing a native module.

after logged in ,remain in home_screen until logout

I want to send the username and password to the server and it returns a response whether the username and password matches. I do not want to ask for login each time my app starts, instead I want to remain in the home_screen until I logout from my android app. How can I do this? any example will be thankfull..
package com.example.test5;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnClickListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity implements OnClickListener{
private EditText username;
private EditText password;
private Button login;
static String u;
static String p;
Context context = MainActivity.this;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
username = (EditText)findViewById(R.id.editText1);//Visibility
password = (EditText)findViewById(R.id.editText2);//Visibility
login = (Button)findViewById(R.id.button1);//Visibility
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
u = username.getText().toString();
p = password.getText().toString();
Toast.makeText(MainActivity.this, "Checking User Login",Toast.LENGTH_SHORT).show();
new MyAsyncTask_Login(context).execute(u,p);
}
});
}
#Override
public void onClick(DialogInterface dialog, int which) {
}
}
my asynctask class
package com.example.test5;
import java.io.StringReader;
import java.util.LinkedList;
import java.util.List;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.XmlResourceParser;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.widget.Toast;
public class MyAsyncTask_Login extends AsyncTask<String, Void, String>{
public static final String MyPREFERENCES = "MyPrefs" ; //editor: never used
public static final String userName = "name";
public static final String Password = "password";
SharedPreferences sharedpreferences; //editor: never used
private Context context;
public MyAsyncTask_Login(Context context) {
this.context = context;
}
#Override
protected String doInBackground(String... params) {
String response = new Login_WebService().checkLogin(params[0], params[1]);
return response;
}
#Override
protected void onPostExecute(String result) {
String strResponse = result;
try {
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser parser = factory.newPullParser();
parser.setInput(new StringReader(strResponse));
List<String> tags = new LinkedList<String>();
tags.add("valid");
for (int type = parser.next(); type != XmlResourceParser.END_DOCUMENT; type = parser.next()) {
if (type == XmlResourceParser.START_TAG) {
String name = parser.getName();
if (tags.contains(name)) {
type = parser.next();
if (parser.getText().trim().equals("1")) {
Toast.makeText(context, "logged in succesfully.",Toast.LENGTH_SHORT).show();
try {
String user = MainActivity.u;
String pass = MainActivity.p;
Intent i = new Intent(context,Home_page.class);
context.startActivity(i);
}
catch (Exception e) {
Toast.makeText(context, e.toString(),Toast.LENGTH_SHORT).show();
}
}
else {
Toast.makeText(context, "Invalid User",Toast.LENGTH_SHORT).show();
}
}
}
}
}
catch (Exception e) {
}
}
}
You can do like this:
Save your login data in shared Preferences.
When the user login:
protected void doInBackground(Activity... params) {
Activity activity = (Activity) params[0];
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);//Pass activity in params o
Editor editor = prefs.edit();
editor.putString("username",u);
editor.putString("password",p);
editor.commit();
}
in on create when the user restart the app read the shared preferences:
u = prefs.getString("username", "");
p = prefs.getString("password", "");
if(u.equals("") || p.equals(""))
//user needs new login
else
//user already login
To make logout put "" in sharedpreferences.

Twitter: "This page contains too many server redirects" error

I'm trying to share some data using twitter in android app, so what ever the basic information like redirecting url, application given in the "Twitter app registration page", everything works fine but after giving the username and password in the LOGIN PAGE of twitter it doesn't redirects to the next page, instead getting "this page contains too many server redirects" error message.
My redirect url looks like this "https://www.example.com/".
Any suggestions?
public class constants {
public static final String CONSUMER_KEY = "key";
public static final String CONSUMER_SECRET= "secret";
public static final String REQUEST_URL = "http://api.twitter.com/oauth/request_token";
public static final String ACCESS_URL = "http://api.twitter.com/oauth/access_token";
public static final String AUTHORIZE_URL = "http://api.twitter.com/oauth/authorize";
public static final String OAUTH_CALLBACK_URL = "x-latify-oauth-twitter";
private static final String CALLBACK_SCHEME = null;
public static final Object OAUTH_CALLBACK_SCHEME = CALLBACK_SCHEME + "://callback";
}
MainActivity
import java.util.Date;
import oauth.signpost.OAuth;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import oauth.signpost.commonshttp.CommonsHttpOAuthProvider;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.provider.SyncStateContract.Constants;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private SharedPreferences prefs;
private final Handler mTwitterHandler = new Handler();
private TextView loginStatus;
final Runnable mUpdateTwitterNotification = new Runnable() {
public void run() {
Toast.makeText(getBaseContext(), "Tweet sent !", Toast.LENGTH_LONG).show();
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.prefs = PreferenceManager.getDefaultSharedPreferences(this);
loginStatus = (TextView)findViewById(R.id.ls);
Button tweet = (Button) findViewById(R.id.tweet);
Button clearCredentials = (Button) findViewById(R.id.cc);
tweet.setOnClickListener(new View.OnClickListener() {
* to the twitter login page. Once the user authenticated, he'll authorize the Android application to send
* tweets on the users behalf.
*/
public void onClick(View v) {
if (TwitterUtils.isAuthenticated(prefs)) {
sendTweet();
} else {
Intent i = new Intent(getApplicationContext(), PrepareRequestTokenActivity.class);
i.putExtra("tweet_msg",getTweetMsg());
startActivity(i);
}
}
});
clearCredentials.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
clearCredentials();
updateLoginStatus();
}
});
}
#Override
protected void onResume() {
super.onResume();
updateLoginStatus();
}
public void updateLoginStatus() {
loginStatus.setText("Logged into Twitter : " + TwitterUtils.isAuthenticated(prefs));
}
private String getTweetMsg() {
return "Tweeting from Android App at " + new Date().toLocaleString();
}
public void sendTweet() {
Thread t = new Thread() {
public void run() {
try {
TwitterUtils.sendTweet(prefs,getTweetMsg());
mTwitterHandler.post(mUpdateTwitterNotification);
} catch (Exception ex) {
ex.printStackTrace();
}
}
};
t.start();
}
private void clearCredentials() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
final Editor edit = prefs.edit();
edit.remove(OAuth.OAUTH_TOKEN);
edit.remove(OAuth.OAUTH_TOKEN_SECRET);
edit.commit();
}
}
import oauth.signpost.OAuthConsumer;
import oauth.signpost.OAuthProvider;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
public class OAuthRequestTokenTask extends AsyncTask<Void, Void, Void> {
final String TAG = getClass().getName();
private Context context;
private OAuthProvider provider;
private OAuthConsumer consumer;
/**
*
* We pass the OAuth consumer and provider.
*
* #param context
* Required to be able to start the intent to launch the browser.
* #param provider
* The OAuthProvider object
* #param consumer
* The OAuthConsumer object
*/
public OAuthRequestTokenTask(Context context,OAuthConsumer consumer,OAuthProvider provider) {
this.context = context;
this.consumer = consumer;
this.provider = provider;
}
/**
*
* Retrieve the OAuth Request Token and present a browser to the user to authorize the token.
*
*/
#Override
protected Void doInBackground(Void... params) {
try {
Log.i(TAG, "Retrieving request token from Google servers");
final String url = provider.retrieveRequestToken(consumer, constants.OAUTH_CALLBACK_URL);
Log.i(TAG, "Popping a browser with the authorize URL : " + url);
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)).setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_FROM_BACKGROUND);
context.startActivity(intent);
} catch (Exception e) {
Log.e(TAG, "Error during OAUth retrieve request token", e);
}
return null;
}
}
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.SyncStateContract.Constants;
import android.util.Log;
import oauth.signpost.OAuth;
import oauth.signpost.OAuthConsumer;
import oauth.signpost.OAuthProvider;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import oauth.signpost.commonshttp.CommonsHttpOAuthProvider;
public class PrepareRequestTokenActivity extends Activity {
final String TAG = getClass().getName();
private OAuthConsumer consumer;
private OAuthProvider provider;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
this.consumer = new CommonsHttpOAuthConsumer(constants.CONSUMER_KEY, constants.CONSUMER_SECRET);
this.provider = new CommonsHttpOAuthProvider(constants.REQUEST_URL,constants.ACCESS_URL,constants.AUTHORIZE_URL );
} catch (Exception e) {
Log.e(TAG, "Error creating consumer / provider",e);
}
Log.i(TAG, "Starting task to retrieve request token.");
new OAuthRequestTokenTask(this,consumer,provider).execute();
}
/**
* Called when the OAuthRequestTokenTask finishes (user has authorized the request token).
* The callback URL will be intercepted here.
*/
#Override
public void onNewIntent(Intent intent) {
super.onNewIntent(intent);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
final Uri uri = intent.getData();
if (uri != null && uri.getScheme().equals(constants.OAUTH_CALLBACK_SCHEME)) {
Log.i(TAG, "Callback received : " + uri);
Log.i(TAG, "Retrieving Access Token");
new RetrieveAccessTokenTask(this,consumer,provider,prefs).execute(uri);
finish();
}
}
public class RetrieveAccessTokenTask extends AsyncTask<Uri, Void, Void> {
private Context context;
private OAuthProvider provider;
private OAuthConsumer consumer;
private SharedPreferences prefs;
public RetrieveAccessTokenTask(Context context, OAuthConsumer consumer,OAuthProvider provider, SharedPreferences prefs) {
this.context = context;
this.consumer = consumer;
this.provider = provider;
this.prefs=prefs;
}
/**
* Retrieve the oauth_verifier, and store the oauth and oauth_token_secret
* for future API calls.
*/
protected Void doInBackground(Uri...params) {
final Uri uri = params[0];
final String oauth_verifier = uri.getQueryParameter(OAuth.OAUTH_VERIFIER);
try {
provider.retrieveAccessToken(consumer, oauth_verifier);
final Editor edit = prefs.edit();
edit.putString(OAuth.OAUTH_TOKEN, consumer.getToken());
edit.putString(OAuth.OAUTH_TOKEN_SECRET, consumer.getTokenSecret());
edit.commit();
String token = prefs.getString(OAuth.OAUTH_TOKEN, "");
String secret = prefs.getString(OAuth.OAUTH_TOKEN_SECRET, "");
consumer.setTokenWithSecret(token, secret);
context.startActivity(new Intent(context,MainActivity.class));
executeAfterAccessTokenRetrieval();
Log.i(TAG, "OAuth - Access Token Retrieved");
} catch (Exception e) {
Log.e(TAG, "OAuth - Access Token Retrieval Error", e);
}
return null;
}
private void executeAfterAccessTokenRetrieval() {
String msg = getIntent().getExtras().getString("tweet_msg");
try {
TwitterUtils.sendTweet(prefs, msg);
} catch (Exception e) {
Log.e(TAG, "OAuth - Error sending to Twitter", e);
}
}
}
twitterUtils.java
import oauth.signpost.OAuth;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.http.AccessToken;
import android.content.SharedPreferences;
import android.provider.SyncStateContract.Constants;
public class TwitterUtils {
public static boolean isAuthenticated(SharedPreferences prefs) {
String token = prefs.getString(OAuth.OAUTH_TOKEN, "");
String secret = prefs.getString(OAuth.OAUTH_TOKEN_SECRET, "");
AccessToken a = new AccessToken(token,secret);
Twitter twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(constants.CONSUMER_KEY, constants.CONSUMER_SECRET);
twitter.setOAuthAccessToken(a);
try {
twitter.getAccountSettings();
return true;
} catch (TwitterException e) {
return false;
}
}
public static void sendTweet(SharedPreferences prefs,String msg) throws Exception {
String token = prefs.getString(OAuth.OAUTH_TOKEN, "");
String secret = prefs.getString(OAuth.OAUTH_TOKEN_SECRET, "");
AccessToken a = new AccessToken(token,secret);
Twitter twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(constants.CONSUMER_KEY, constants.CONSUMER_SECRET);
twitter.setOAuthAccessToken(a);
twitter.updateStatus(msg);
}
}
Change Your Call Back URL and write below Call back URL instead of your URL.
public static final String CALLBACK_URL = "x-oauthflow-twitter://callback";
And see below link for more information.
Twitter Integration in Android

Categories

Resources