I have a small app that i have been working on. I wanted a fresh install to run from on my Galaxy Nexus rooted running 4.2.1. I uninstalled the app, then tried to reinstall it via eclipse. It installs fine, no errors in logcat, console ect... but when you click to run the app, it just closes right on opening. I have tried this on 2 different phones, same thing.
On the Galaxy Nexus, if I restore my ROM back before I uninstalled, I can run it from eclipse all I want. It's only after uninstall and reinstall that I get the force close. It is installed on the ROM backup.
Any ideas?! How can I find out what is going on here?
EDIT:::
Activity is only declared once in manifest...
Tried changing the version number... no effect
added some Log.e() to the MainActivity:
protected void onCreate(Bundle savedInstanceState) {
Log.e(TAG,"STARTING APP");
super.onCreate(savedInstanceState);
// show no back arrow
Log.e(TAG,"AFTER ONCREATE");
setContentView(R.layout.activity_firstload);
Log.e(TAG,"AFTER SETCONTENTVIEW");
getPrefs();
Log.e(TAG,"GET PREFS");
finish();
Log.e(TAG,"AFTER FINISH");
}
The only tag that shows in the LogCat is "AFTER FINISH"
If I get rid of finish, the MainActivity stays open. All that main activity does is check for Preferences. Here is my GetPrefs()
private void getPrefs() {
// Get the xml/preferences.xml preferences
Log.e(TAG,"GET PREFS 1");
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(getBaseContext());
lp = prefs.getString("defaultreport", "");
Log.v(TAG, lp);
if (lp.equals("esac")) {
// Toast.makeText(MainActivity.this, "ESAC", Toast.LENGTH_SHORT)
// .show();
Intent i = new Intent(MainActivity.this, ESACActivity.class);
startActivity(i);
} else if (lp.equals("sac")) {
// Toast.makeText(MainActivity.this, "SAC", Toast.LENGTH_SHORT)
// .show();
Intent i = new Intent(MainActivity.this, SACActivity.class);
startActivity(i);
} else if (lp.equals("msar")) {
// Toast.makeText(MainActivity.this, "MSAR", Toast.LENGTH_SHORT)
// .show();
Intent i = new Intent(MainActivity.this, MSARActivity.class);
startActivity(i);
}
}
AH>>> May have found something. The preferences initially are set to "" (null) so what would it load?! So I need a screen asking which they'd like to set on FIRST RUN I guess...
EDIT EDIT::: Needed to check for first run in Prefs...
if (prefs.getString("defaultreport", null) == null)
{
startActivity(new Intent(this, Preferences.class));
return;
}
Your string that decides what to run is set to nothing if there is no preference.
lp = prefs.getString("defaultreport", "");
And since you have no option for that case nothing will run and the initial activity will close without starting any other.
Related
I have used SharedPreferences to check whether it is already logged in or not. But after I logged in and then uninstall the app, it always gives true value while reinstalling the app and login page is not shown. Why is it? Isn't it true that when the app is uninstalled, the value in sharedPreference should have gone too? It works in unsigned apk (ie when you install the app directly through android studio) but as soon as I use signed apk, the problem appears. It is happening in nokia 5 and some other devices but works perfectly fine in other android devices. How can I solve it?
public class MainActivity extends AppCompatActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences pref = getSharedPreferences("ActivityPREF", Context.MODE_PRIVATE);
**//always gives true value here...**
Log.e("loginStatus", pref.getBoolean("activity_executed", false) + "");
if (pref.getBoolean("activity_executed", false)) {
Log.e("loginStatus", pref.getBoolean("activity_executed", false) + "");
Intent intent = new Intent(this, LiveTrack.class);
startActivity(intent);
finish();
} else {
Log.e("loginStatus", "notlogin");
}
}
}
It is the problem with some of the devices.Try deleting the data files manually when user quits the app.
File sharedPreferenceFile = new File("/data/data/"+ getPackageName()+ "/shared_prefs/");
File[] listFiles = sharedPreferenceFile.listFiles();
for (File file : listFiles) {
file.delete();
}
Also make sure you havent turned on the allowBackup as true because from android-23 by default backup stores app's data including preferences to cloud.Later when you uninstall then reinstall newer version you will to use restored preferences.
<application ...
android:allowBackup="false">
</application>
I have my code below on the onCreate of my Activity.
SharedPreferences globalPreferences = getSharedPreferences(PREF_KEY, Context.MODE_PRIVATE);
boolean hasFinishedIntroduction = globalPreferences.getBoolean(PREF_FINISHED_INTRO), false);
Log.d(TAG, "Has finished introduction: " + hasFinishedIntroduction);
if(!hasFinishedIntroduction){
startActivity(new Intent(this, IntroductionActivity.class));
finish();
}
boolean hasLoggedInUsingFacebook = globalPreferences.getBoolean(PREF_LOGGED_IN_FACEBOOK), false);
boolean hasLoggedInUsingGoogle = globalPreferences.getBoolean(PREF_LOGGED_IN_GOOGLE), false);
Log.d(TAG, "Has logged in using Facebook: " + hasLoggedInUsingFacebook);
Log.d(TAG, "Has logged in using Google: " + hasLoggedInUsingGoogle);
if(!hasLoggedInUsingFacebook && !hasLoggedInUsingGoogle){
startActivity(new Intent(this, SocialLoginActivity.class));
finish();
}
My problem is that, every time I run my app (clean install), my app starts my SocialLoginActivity that is supposed to be checked second. My first check was ignored (hasFinishedIntroduction).
Of course I tried debugging it with Log messages but all works fine (the values at least).
10-06 03:15:09.907 12969-12969/com.sample.foo D/Bar: Has finished introduction: false
10-06 03:15:09.937 12969-12969/com.sample.foo D/Bar: Has logged in using Facebook: false
10-06 03:15:09.937 12969-12969/com.sample.foo D/Bar: Has logged in using Google: false
Clearly, the app can read the false in the hasFinishedIntroduction but it ignores it and refuses to execute what's inside my first if statement.
What's surprising is that after I log in on my app, the user will be brought back to this Activity and then now, my check of hasFinishedIntroduction's value will be executed and will start the Activity I instructed it to start.
Thank you for your help.
EDIT
I forgot to note here that I have also put some Log.d()s in the onCreate of my IntroductionActivity and SocialLoginActivity but it really shows that it doesn't really call IntroductionActivity at all.
I think u need to return from the method in the hasFinishedIntroduction block because the code after the block is getting executed and SociaLoginActivity is being launched on top of the IntroductionActivity.
try this:
if(!hasFinishedIntroduction){
startActivity(new Intent(this, IntroductionActivity.class));
finish();
return;
}
I have a strange issue I'm experiencing when developing an app for Android. I'm trying to debug my application using my phone (a Oneplus One), Android Studio and ADB. Everything works as normal except that when I start an activity that already has a breakpoint set in Android Studio, it crashes with no log output. This happens both when the activity is the launch activity and when I'm starting one with an intent.
As you can imagine, this is incredibly irritating since I have a bug in my onCreate() method that I want to break in.
I have tried adding the line Debug.waitForDebugger() to the bit of code above the breakpoints but this doesn't help.
I haven't added any code to this question because this error is independent of the code. It happens with multiple projects and Activities. I don't have another Android phone to test it on so can't check that. Has anyone else experienced this and/or found a fix?
Thanks in advance.
EDIT:
Added an example of code. This code does not crash when a breakpoint is not set, neither does the breakpoint need to be in this bit of code for the crash to occur. This is just the code I'm trying to debug, behaviour of which would be impossible to fix without knowledge of my server back-end, so I'm not asking for help with that.
protected void onCreate(Bundle savedInstanceState) {
//Create activity
getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Check for play services
if (!checkPlayServices()){
//Exit and notify user that play services are required
Toast.makeText(this, "Google Play Services must be installed for Insty to work", Toast.LENGTH_LONG).show();
System.exit(1);
}
//Get token. If null, push to login screen
SharedPreferences sp = getBaseContext().getSharedPreferences(NetService.SP_APP, Context.MODE_PRIVATE);
if (!sp.contains(NetService.SP_TOKEN)){
//Token doesn't exist - push to login screen
startActivity(new Intent(MainActivity.this, LoginActivity.class));
MainActivity.this.finish();
return;
}
//Setup action bar
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
//Populate navigation drawer
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
mDrawerList = (ListView)findViewById(R.id.left_drawer);
String[] menuItems = getResources().getStringArray(R.array.menu_items);
mDrawerList.setAdapter(new ArrayAdapter<>(this, R.layout.drawer_list_item, menuItems));
//Set an on click listener
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
//Add to action bar
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open_drawer, R.string.close_drawer){
#Override
public void onDrawerClosed(View view){
invalidateOptionsMenu();
}
#Override
public void onDrawerOpened(View view){
invalidateOptionsMenu();
}
};
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
//Start a token verification
ResultReceiver receiver = new ResultReceiver(new Handler()){
#Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
VerifyResult result = VerifyResult.values()[resultData.getInt(NetService.RESULT_VERIFY)];
switch (result){
case VALID:
//Do nothing
break;
case INVALID:
//Push back to login screen
startActivity(new Intent(MainActivity.this, LoginActivity.class));
MainActivity.this.finish();
break;
case BAD_NETWORK:
//Toast to let user know network is down
Toast.makeText(MainActivity.this, R.string.bad_network, Toast.LENGTH_LONG).show();
break;
case ERROR:
//Toast to show error
Toast.makeText(MainActivity.this, R.string.generic_error, Toast.LENGTH_LONG).show();
break;
}
}
};
//Start verify
NetService.startActionVerify(this, receiver, sp.getString(NetService.SP_TOKEN, ""));
//Open on chats fragment
FragmentManager fragMgr = getFragmentManager();
fragMgr.beginTransaction().replace(R.id.content_frame, new ChatsFragment()).commit();
}
Last versions(1.1-1.2) of Android Studio have some debugging bugs probably cause of new inline debugging features. There is an issue topic and a solution inside it. Give it a try, it solved my debugging problems.
Test on another device with newer SDK. Had the same problem on Nexus 5X API 27 while on Pixel XL API 32 works fine.
If I create an app that depends on another app or apps (eg: the Facebook and Twitter apps), yet they are not installed, is there a method of checking for those dependencies and installing them at the same time as my own app?
I did this in my application which requires the zxing scanner app to be installed.
You will want this inside your onclick or ontouch:
try{
Intent intent = new Intent("com.google.zxing.client.android.SCAN");
intent.setPackage("com.google.zxing.client.android");
startActivityForResult(intent, 0);
} catch (Exception e) {
createAlert("Barcode Scanner not installed!", "This application uses " +
"the open source barcode scanner by ZXing Team, you need to install " +
"this before you can use this software!", true);
}
which calls
public void createAlert(String title, String message, Boolean button) {
// http://androidideasblog.blogspot.com/2010/02/how-to-add-messagebox-in-android.html
AlertDialog alertDialog;
alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle(title);
alertDialog.setMessage(message);
if ((button == true)) {
alertDialog.setButton("Download Now",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
Intent browserIntent = new Intent(
Intent.ACTION_VIEW,
Uri.parse("market://search?q=pname:com.google.zxing.client.android"));
startActivity(browserIntent);
}
});
}
alertDialog.show();
}
Then after sorting out all that code out I realise you asked for it to be installed at the same time as your app. Not sure if i should post this code, but it may be helpful
Short answer: No, you cannot automatically install other applications as dependencies.
Longer answer:
Android Market does not let you declare other applications to install as a dependency. As a system, Market appears to be designed for single application installs -- not Linux distro style mega dependency graphs.
At runtime, you can test for installed apps and punt your user over to the Market if so. See the techniques suggested by #QuickNick (testing if an app is installed) and #TerryProbert (punting to market) if that's what you want.
Your best bet is probably to design your app to gracefully degrade if dependencies are not available, and suggest (or insist) that they head over to market to install them.
Start from this:
Intent mediaIntent = new Intent("com.example.intent.action.NAME");
// add needed categories
List<ResolveInfo> listResolveInfo = getPackageManager().queryIntentServices(mediaIntent, 0);
if (listResolveInfo.size() != 0) {
//normal behavior
} else {
//install what you need
}
I give you example of querying services. If you want to check activities, then you will call queryIntentActivities().
I think following the pattern outlined in this post on the Android Developer Blog will help you.
http://android-developers.blogspot.com/2009/01/can-i-use-this-intent.html
As TerryProbert points out if you know that the Intent is not available prompt the user to install the missing app.
Here's what I use to return the first mission activity that exists:
try {
Class<?> missionClass = Class.forName(mPackageName+".Mission"+mission);
Method missionDescription;
missionDescription = missionClass.getMethod("missionDescription");
mMissionDescription = (String) missionDescription.invoke(null);
if (mMissionDescription.length() > 0) {
nextMission = mission;
break;
}
} catch (Exception e) {
//DEBUG*/Log.v(this.getClass().getName(), "onResume: Mission no "+mission+" not found: "+e.getMessage());
}
Each mission is held in a separate class, derived from a Mission base class. Derived classes are called Mission1, Mission24 etc.
Not all missions are defined.
The base class has an abstract class missionDescription which returns a string describing the mission.
This code is inside a loop so tests mission=1 to 99, trying to call missionDescription. It returns when the Description for the first mission found is returned.
I'm trying to set up a dialog that will popup after the users updates or installs the application for the first time. I can't figure out how to exactly do this. Currently I have tried to use the package manager to get the users version and compare it to see if its the most recent. I'm uncertain if this will work as its hard to test for something that relies on a package update. Here is my code:
public void firstrun() {
String version = "";
String currenver = "3.9";
// update function
try {
PackageInfo manager = getPackageManager().getPackageInfo(
getPackageName(), 0);
version = manager.versionName;
} catch (NameNotFoundException e) {
// Handle exception
}
getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit()
.putString(version, version).commit();
boolean firstrun = getSharedPreferences("PREFERENCE", MODE_PRIVATE)
.getBoolean("firstrun", true);
if (version.matches(currenver)) {
// Save the state
getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit()
.putBoolean("firstrun", false).commit();
} else {
// Save the state
getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit()
.putBoolean("firstrun", true).commit();
}
if (firstrun == true) {
new AlertDialog.Builder(this)
.setTitle("Welcome!")
.setIcon(R.drawable.icondialog)
.setMessage("UpdateText")
.setNeutralButton("OK", null).show();
}
}
I think you are on the right track, there are many solutions here and here that may give you ideas.
In addition you could create a database table that contains a flag to prompt or not. By default it would be set to a value to prompt, and then once the user launches and acknowledges the dialog you could change the flag. Then in your onUpgrade() method of your SQLiteOpenHelper you could flip the flag again, and thus your application would prompt on installation of a new version.