When I set an activity to be the launcher it works fine, however when I launch this activity from another activity, it will open fine displaywise, some of the functionality works and some of it does not?! Very confusing for me.
Basically if I open it as the Launcher data can be sent and received over serial. But if I open it from another activity instead absolute crap gets sent over serial and nothing is coming back. However some parts work such as establishing the serial connection?!
In the launching activity this is the code to open the activity I want:
public void openTextTerminal(View view)
{
Intent intent = new Intent(this, TextBoxActivity.class);
startActivity(intent);
}
This is the manifest:
(I don't think I even need the intent filter?!)
<activity
android:name="com.example.TextBoxActivity"
android:label="#string/title_activity_text_box" >
<intent-filter>
<action android:name="android.intent.action.TextBoxActivity" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
Full Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example"
android:installLocation="auto"
android:versionCode="49"
android:versionName="1.0.48" >
<uses-sdk
android:minSdkVersion="12"
android:targetSdkVersion="12" />
<uses-feature
android:name="android.hardware.touchscreen"
android:required="false" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<permission
android:name="com.example.permission.RUN_SCRIPT"
android:description="#string/permdesc_run_script"
android:label="#string/perm_run_script"
android:permissionGroup="android.permission-group.SYSTEM_TOOLS"
android:protectionLevel="dangerous" />
<permission
android:name="com.example.permission.APPEND_TO_PATH"
android:description="#string/permdesc_append_to_path"
android:label="#string/perm_append_to_path"
android:permissionGroup="android.permission-group.SYSTEM_TOOLS"
android:protectionLevel="dangerous" />
<permission
android:name="com.example.permission.PREPEND_TO_PATH"
android:description="#string/permdesc_prepend_to_path"
android:label="#string/perm_prepend_to_path"
android:permissionGroup="android.permission-group.SYSTEM_TOOLS"
android:protectionLevel="dangerous" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/application_terminal" >
<activity
android:name="com.example.Term"
android:configChanges="keyboard|keyboardHidden|orientation"
android:launchMode="singleTask"
android:theme="#style/Theme"
android:windowSoftInputMode="adjustResize|stateAlwaysVisible" >
<intent-filter>
<action android:name="android.intent.action.TERM" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity-alias
android:name="com.example.TermInternal"
android:exported="false"
android:targetActivity="Term" >
<intent-filter>
<action android:name="com.example.private.OPEN_NEW_WINDOW" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
<intent-filter>
<action android:name="com.example.private.SWITCH_WINDOW" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity-alias>
<activity
android:name="com.example.RemoteInterface"
android:excludeFromRecents="true" >
<intent-filter>
<action android:name="com.example.OPEN_NEW_WINDOW" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity-alias
android:name="com.example.RunScript"
android:permission="com.example.permission.RUN_SCRIPT"
android:targetActivity="RemoteInterface" >
<intent-filter>
<action android:name="com.example.RUN_SCRIPT" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity-alias>
<activity
android:name="com.example.TermPreferences"
android:label="#string/preferences" />
<activity
android:name="com.example.WindowList"
android:label="#string/window_list" />
<service android:name="com.example.TermService" />
<activity
android:name="com.example.MainActivity"
android:label="#string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.example.TextBoxActivity"
android:label="#string/title_activity_text_box" >
<intent-filter>
<action android:name="android.intent.action.TextBoxActivity" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name="com.example.SerialTerminalActivity"
android:label="#string/title_activity_serial_terminal"
android:screenOrientation="landscape" >
</activity>
</application>
</manifest>
I replicated the code in a program on it's own (ie using an activity to launch the second activity without my other unrelated classes) and it works fine. I just copied and pasted. I did a diff on all the files and there is practically nothing different, just unrelated things in the manifest as far as I can see. I'll just go through the whole manifest tomorrow (I spent a whole day debugging just to find this bug) and rewrite it or something.
I was just curious as to how it can appear that everything is working normally but that it is not. I would have thought once I launch the activity everything is exactly the same no matter how I launch it (as I am passing nothing).
May be passing wrong context, here is full code:
public class MainActivity extends Activity implements OnClickListener, OnItemSelectedListener, AdapterConnectionListener, DataListener{
private Spinner mBaudSpinner;
private Spinner mDataSpinner;
private Spinner mParitySpinner;
private Spinner mStopSpinner;
private Spinner mDeviceSpinner;
private Button mConnect;
private ArrayList<String> mDeviceOutputs;
private ArrayList<USB2SerialAdapter> mDeviceAdapters;
private ArrayAdapter<CharSequence> mDeviceSpinnerAdapter;
private USB2SerialAdapter mSelectedAdapter;
private TextView mCurrentSettings;
private Button mUpdateSettings;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
mConnect = (Button)findViewById(R.id.deviceConnect);
mConnect.setOnClickListener(this);
mUpdateSettings = (Button)findViewById(R.id.updateSettings);
mUpdateSettings.setOnClickListener(this);
mBaudSpinner = (Spinner)findViewById(R.id.baudSpinner);
ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mBaudSpinner.setAdapter(adapter);
String[] tempArray = SlickUSB2Serial.BAUD_RATES;
for(int i=0;i<tempArray.length;i++)
{
adapter.add(tempArray[i]);
}
mBaudSpinner.setSelection(SlickUSB2Serial.BaudRate.BAUD_9600.ordinal());
mDataSpinner = (Spinner)findViewById(R.id.dataSpinner);
adapter = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mDataSpinner.setAdapter(adapter);
tempArray = SlickUSB2Serial.DATA_BITS;
for(int i=0;i<tempArray.length;i++)
{
adapter.add(tempArray[i]);
}
mDataSpinner.setSelection(SlickUSB2Serial.DataBits.DATA_8_BIT.ordinal());
mParitySpinner = (Spinner)findViewById(R.id.paritySpinner);
adapter = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mParitySpinner.setAdapter(adapter);
tempArray = SlickUSB2Serial.PARITY_OPTIONS;
for(int i=0;i<tempArray.length;i++)
{
adapter.add(tempArray[i]);
}
mParitySpinner.setSelection(SlickUSB2Serial.ParityOption.PARITY_NONE.ordinal());
mStopSpinner = (Spinner)findViewById(R.id.stopSpinner);
adapter = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mStopSpinner.setAdapter(adapter);
tempArray = SlickUSB2Serial.STOP_BITS;
for(int i=0;i<tempArray.length;i++)
{
adapter.add(tempArray[i]);
}
mStopSpinner.setSelection(SlickUSB2Serial.StopBits.STOP_1_BIT.ordinal());
mDeviceAdapters = new ArrayList<USB2SerialAdapter>();
mDeviceOutputs = new ArrayList<String>();
mDeviceSpinner = (Spinner)findViewById(R.id.deviceSpinner);
mDeviceSpinnerAdapter = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item);
mDeviceSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mDeviceSpinner.setAdapter(mDeviceSpinnerAdapter);
mDeviceSpinner.setOnItemSelectedListener(this);
mCurrentSettings = (TextView)findViewById(R.id.currentSettings);
SlickUSB2Serial.initialize(this);
}
public void openTerminal(View view) {
// Do something in response to button
Intent intent = new Intent(this, Term.class);
startActivity(intent);
}
public void openTextTerminal(View view) {
// Do something in response to button
Intent intent = new Intent(this, TextBoxActivity.class);
startActivity(intent);
}
public void openSerialTerminal(View view) {
// Do something in response to button
Intent intent = new Intent(this, SerialTerminalActivity.class);
startActivity(intent);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
changeSelectedAdapter(mDeviceAdapters.get(position));
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
public void changeSelectedAdapter(USB2SerialAdapter adapter){
Toast.makeText(this, "in changeselectedadapter", Toast.LENGTH_SHORT).show();
//if(mSelectedAdapter!=null){
//mDeviceOutputs.set(mDeviceSpinnerAdapter.getPosition(mSelectedAdapter.getDeviceId()+""),mReceiveBox.getText().toString());
mSelectedAdapter = adapter;
mBaudSpinner.setSelection(adapter.getBaudRate().ordinal());
mDataSpinner.setSelection(adapter.getDataBit().ordinal());
mParitySpinner.setSelection(adapter.getParityOption().ordinal());
mStopSpinner.setSelection(adapter.getStopBit().ordinal());
updateCurrentSettingsText();
//mReceiveBox.setText(mDeviceOutputs.get(mDeviceSpinner.getSelectedItemPosition()));
Toast.makeText(this, "Adapter switched toooo: "+adapter.getDeviceId()+"!", Toast.LENGTH_SHORT).show();
}
#Override
public void onClick(View v) {
if(v==mConnect){
SlickUSB2Serial.autoConnect(this);
if(mSelectedAdapter==null){
Toast.makeText(this, "no adapters detected", Toast.LENGTH_SHORT).show();
return;
//String data = mSendBox.getText().toString() + "\r\n";
// mSelectedAdapter.sendData(data.getBytes());
//mSendBox.setText("");
}
Intent intent = new Intent(this, SerialTerminalActivity.class);
startActivity(intent);
}
else if(v==mUpdateSettings){
if(mSelectedAdapter==null){
return;
}
mSelectedAdapter.setCommSettings(BaudRate.values()[mBaudSpinner.getSelectedItemPosition()],
DataBits.values()[mDataSpinner.getSelectedItemPosition()],
ParityOption.values()[mParitySpinner.getSelectedItemPosition()],
StopBits.values()[mStopSpinner.getSelectedItemPosition()]);
updateCurrentSettingsText();
Toast.makeText(this, "Updated Settings", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onAdapterConnected(USB2SerialAdapter adapter) {
adapter.setDataListener(this);
mDeviceAdapters.add(adapter);
mDeviceOutputs.add("");
mDeviceSpinnerAdapter.add(""+adapter.getDeviceId());
mDeviceSpinner.setSelection(mDeviceSpinnerAdapter.getCount()-1);
Toast.makeText(this, "Adapter: "+adapter.getDeviceId()+" Connected!", Toast.LENGTH_SHORT).show();
//Toast.makeText(this, "Baud: "+adapter.getBaudRate()+" Connected!", Toast.LENGTH_SHORT).show();
}
#Override
public void onAdapterConnectionError(int error, String msg) {
// TODO Auto-generated method stub
if(error==AdapterConnectionListener.ERROR_UNKNOWN_IDS){
final AlertDialog dialog = new AlertDialog.Builder(this)
.setIcon(0)
.setTitle("Choose Adapter Type")
.setItems(new String[]{"Prolific", "FTDI"}, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int optionSelected){
if(optionSelected==0)
{
SlickUSB2Serial.connectProlific(MainActivity.this);
}
else
{
SlickUSB2Serial.connectFTDI(MainActivity.this);
}
}
}).create();
dialog.show();
return;
}
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
private void updateCurrentSettingsText(){
mCurrentSettings.setText("Current Settings Areeee: "+mBaudSpinner.getSelectedItem().toString()
+", "+mDataSpinner.getSelectedItem().toString()
+", "+mParitySpinner.getSelectedItem().toString()
+", "+mStopSpinner.getSelectedItem().toString());
}
#Override
public void onDataReceived(int arg0, byte[] arg1) {
// TODO Auto-generated method stub
Toast.makeText(this, "IN ONDATARECIEVED OHOH", Toast.LENGTH_SHORT).show();
}
public void onDestroy() {
SlickUSB2Serial.cleanup(this);
super.onDestroy();
}
}
Here you have used this for the context, first you should know about the different contexts.
this refers to your current object. In your case you must have implemented the intent in an inner class, or some ClickEvent, and thats what it points to.
Activity.this points to the instance of the Activity you are currently in.
getApplicationContext() refers to the application's context.
Now if the this context is directly under the oncreate() of the activity and not in any other class or some button's onClick() event, then it the same as that of the Activity's context.
But it is preferred to use getApplicationContext(), as the Activity's Context dies, when the same activity finishes.
I found the culprit in onCreate() of the launching activity, it was a library call. All I had to do was move it from the launching activity to the called activity. That will teach me to just follow the API instructions blindly.
So I had SlickUSB2Serial.initialize(this); in the wrong activity.
initialize(android.content.Context context)
initialize must be called when your app first starts up (in onCreate).
Related
I'm currently working on a simple android app. The idea is, it changes the wallpaper automatically after 12 A.M or when the date is changed. It's working on android Oreo and lower versions, however, it doesn't work on android 9(Pie). However, if I change the date manually from the setting of the phone, it calls the broadcast. I have googled a lot, and some suggested to register the broadcast on your java codes instead of Manifest. Unfortunately, it didn't work.
I have tested this question in Stackoverflow.
First of all, changing the date is not part of implicit broadcasts, secondly, I assumed it is. then I changed the codes but it didn't work.
Now I'm gonna provide some codes of my broadcast:
DailyBroadcastReceiverService
public class DailyBroadcastReceiverService extends Service {
private BroadcastReceiver dailyZekrBr;
private Context context;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
registerDailyZekrReceiver();
}
#Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(dailyZekrBr);
dailyZekrBr = null;
}
private void registerDailyZekrReceiver() {
context= this.getApplicationContext();
Log.d("Register", "onStart: Now gonna register the broadcast receiver on Daily Boadcast receiver");
dailyZekrBr = new DailyZekrBroadcastReceiver();
IntentFilter filter = new IntentFilter();
filter.addCategory(Intent.CATEGORY_DEFAULT);
filter.addAction("android.intent.action.ACTION_TIME_CHANGED");
filter.addAction("android.intent.action.TIME_SET");
filter.addAction("android.intent.action.DATE_CHANGED");
filter.addAction("android.intent.action.TIMEZONE_CHANGED");
this.registerReceiver(dailyZekrBr, filter);
}
}
DailyZekrBroadcastReceiver
public class DailyZekrBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.d("DailyZekrBroadcast", "onReceive:The broadcast is called ");
DailyZekrHandler.setTodayImage(context);
}
}
setTodayImage
public static void setTodayImage(Context context) {
int todayImage = DailyZekrHandler.nameOfTheWeek();
DisplayMetrics metrics = new DisplayMetrics();
WindowManager window = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
window.getDefaultDisplay().getMetrics(metrics);
Log.d("DailyZekrBroadCast", "trying to change imge: " + todayImage);
if(todayImage != DailyZekrHandler.getTodayImage(context)) {
DailyZekrHandler.storeTodayImage(context);
Bitmap tempbitMap = BitmapFactory.decodeResource(context.getResources(), todayImage);
Bitmap bitmap = Bitmap.createScaledBitmap(tempbitMap, metrics.widthPixels, metrics.heightPixels, true);
WallpaperManager wallpaperManager = WallpaperManager.getInstance(context);
wallpaperManager.setWallpaperOffsetSteps(1, 1);
wallpaperManager.suggestDesiredDimensions(metrics.widthPixels, metrics.heightPixels);
try {
wallpaperManager.setBitmap(bitmap);
Log.d("DailyZekrBroadCast", "today_image: " + todayImage);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.ellia.dailyzekr">
<uses-permission android:name="android.permission.SET_WALLPAPER" />
<uses-permission android:name="android.permission.SET_WALLPAPER_HINTS" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<meta-data
android:name="com.google.android.gms.ads.APPLICATION_ID"
android:value="ca-app-pub-9778979220370457~9773548477"/>
<receiver android:name=".core.DailyZekrBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.ACTION_TIME_CHANGED"/>
<action android:name="android.intent.action.TIME_SET"/>
<action android:name="android.intent.action.DATE_CHANGED"/>
<action android:name="android.intent.action.TIMEZONE_CHANGED" />
</intent-filter>
</receiver>
<service android:name=".core.DailyBroadcastReceiverService"/>
<activity android:name=".SplashActivity" android:theme="#style/Theme.AppCompat.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
</activity>
</application>
</manifest>
I recently was studying making an AlarmReminder on youtube by this man's tutorial videos: DelaroyStudios.
Anyway... I followed his tutorial and made it work on a separate app. So next I modified it to the way I want my alarmreminder to be and tried to add it to my activity, however when I click the button routing to its activity launcher, it won't go off. By the way here's the repo: https://github.com/delaroy/AlarmReminder
I tried debugging but I can't see errors, so I really don't know where to start in fixing this part. But I suspect its on the dependencies on the gradle perhaps? or some other factor? Anyway please take a look at my code where I suspect the problem might be coming from.
Here's the manifests:
My Manifest
<application
android:name=".FireApp"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name="com.loginpack.splash">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.loginpack.LoginActivity" />
<activity android:name=".MainActivity" />
<activity android:name="com.Welcome.Welcome" />
<activity android:name="com.Welcome.CalendarActivity" />
<activity android:name="com.Welcome.Video" />
<activity android:name=".Profile" />
<activity android:name="com.Welcome.Image">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="image/*" />
</intent-filter>
</activity>
<activity android:name="com.alarmreminder.MainReminder">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity android:name="com.alarmreminder.AddReminderActivity"
android:label="#string/title_activity_add_reminder"
android:parentActivityName="com.alarmreminder.MainReminder"
android:theme="#style/AppTheme">
<!-- Parent activity meta-data to support 4.0 and lower -->
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.alarmreminder.MainReminder"
/>
</activity>
<activity android:name="com.Welcome.Info" />
<activity android:name=".Profile2" />
<activity android:name=".Profile3"/>
I checked the code and I suspect nothing except for some deprecated codes that were usually couldn't have affected the overall performance of the activity to the point that it can't even be opened and debugged. Please help me find a way to make this work. or perhaps if you know any method for me to debug activities without any errors showing. Oh and by the way this is what shows in the Verbose when I click on the activity.
Here's the code of the Activity mentioned:
public class MainReminder extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor> {
private FloatingActionButton mAddReminderButton;
private Toolbar mToolbar;
AlarmCursorAdapter mCursorAdapter;
AlarmReminderDbHelper alarmReminderDbHelper = new AlarmReminderDbHelper(this);
ListView reminderListView;
private static final int VEHICLE_LOADER = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mainalarm);
mToolbar = findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
mToolbar.setTitle(R.string.app_name);
reminderListView = findViewById(R.id.list);
View emptyView = findViewById(R.id.empty_view);
reminderListView.setEmptyView(emptyView);
mCursorAdapter = new AlarmCursorAdapter(this, null);
reminderListView.setAdapter(mCursorAdapter);
reminderListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
Intent intent = new Intent(MainReminder.this, AddReminderActivity.class);
Uri currentVehicleUri = ContentUris.withAppendedId(AlarmReminderContract.AlarmReminderEntry.CONTENT_URI, id);
// Set the URI on the data field of the intent
intent.setData(currentVehicleUri);
startActivity(intent);
}
});
mAddReminderButton = findViewById(R.id.fab);
mAddReminderButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), AddReminderActivity.class);
startActivity(intent);
}
});
getLoaderManager().initLoader(VEHICLE_LOADER, null, this);
}
#Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
String[] projection = {
AlarmReminderContract.AlarmReminderEntry._ID,
AlarmReminderContract.AlarmReminderEntry.KEY_TITLE,
AlarmReminderContract.AlarmReminderEntry.KEY_DATE,
AlarmReminderContract.AlarmReminderEntry.KEY_TIME,
AlarmReminderContract.AlarmReminderEntry.KEY_REPEAT,
AlarmReminderContract.AlarmReminderEntry.KEY_REPEAT_NO,
AlarmReminderContract.AlarmReminderEntry.KEY_REPEAT_TYPE,
AlarmReminderContract.AlarmReminderEntry.KEY_ACTIVE
};
return new CursorLoader(this, // Parent activity context
AlarmReminderContract.AlarmReminderEntry.CONTENT_URI, // Provider content URI to query
projection, // Columns to include in the resulting Cursor
null, // No selection clause
null, // No selection arguments
null); // Default sort order
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
mCursorAdapter.swapCursor(cursor);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
mCursorAdapter.swapCursor(null);
}
}
PS: In the my manifest I didn't make it as the main launcher, since its only an activity after all.
I'm developing screen lock widgets or Lock Screen programmatically. I got some good ideas from Stackoverflow previous questions regarding this, and I did some thing well, but when I run that code, there is No Exception and Error. but when I run it shows nothing.
what I want is when user click on widgets it locks the screen.
Manifest.xml file
`
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
<activity
android:name=".MainActivity"
android:theme="#android:style/Theme.NoDisplay"
android:label="#string/app_name"
android:excludeFromRecents="true" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.LAUNCHER" />
<action android:name="android.intent.action.ASSIST" />
</intent-filter>
</activity>
<receiver android:name=".NewAppWidget"
android:permission="android.permission.BIND_DEVICE_ADMIN">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
<action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="#xml/new_app_widget_info" />
</receiver>
</application>
`
MainActivity.java
public class MainActivity extends Activity {
final static int ENABLE_ADMIN = 1;
final static int SUCESS = -1;
private ComponentName mAdminName = null;
public final void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAdminName = new ComponentName(this, AdminManageReceiver.class);
DevicePolicyManager mDevicePolicyManager = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
if (!mDevicePolicyManager.isAdminActive(mAdminName)) {
showAdminManagement();
}
if (mDevicePolicyManager.isAdminActive(mAdminName)) {
mDevicePolicyManager.lockNow();
}
else {
Log.e("screenlock", "Unable to lock the phone D:");
}
finish();
}
private void showAdminManagement() {
// TODO Auto-generated method stub
Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, mAdminName);
intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION,
R.string.desc_enable_admin);
startActivityForResult(intent, ENABLE_ADMIN);
}
}
Appwidgetprovider.java
public class NewAppWidget extends AppWidgetProvider {
private static final int ADMIN_INTENT = 15;
private static final String description = "Sample Administrator description";
private DevicePolicyManager mDevicePolicyManager;
private ComponentName mComponentName;
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
// There may be multiple widgets active, so update all of them
final int N = appWidgetIds.length;
for (int i = 0; i < N; i++) {
//updateAppWidget(context, appWidgetManager, appWidgetIds[lock]);
Intent intent = new Intent(context,MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
RemoteViews View = new RemoteViews(context.getPackageName(), R.layout.new_app_widget);
View.setOnClickPendingIntent(R.id.imageButton, pendingIntent);
appWidgetManager.updateAppWidget(appWidgetIds, View);
}
}
AdminManageReceiver.java
public class AdminManageReceiver extends DeviceAdminReceiver {
}
First, you may not be able to use a single <receiver> for both a DeviceAdminReceiver and an AppWidgetProvider. The pieces of Android that work with app widgets may not hold the android.permission.BIND_DEVICE_ADMIN permission, blocking them from working with your <receiver>. Use two separate <receiver> elements, one for your DeviceAdminReceiver and one for your AppWidgetProvider.
Second, bear in mind that app widgets on the lockscreen was only supported on Android 4.2 through 4.4. Older and newer versions of Android do not support this feature.
OK, so the problem I'm having occurs when the startGame button is pressed. The app crashes when the button is pressed. The activity is instantiated in the manifest so I'm not sure where the error is. The code for the intent is a copy of the other one (which works) so I have no clue where I went wrong.
Error Log:
02-25 14:46:51.064: E/AndroidRuntime(1261): FATAL EXCEPTION: main
02-25 14:46:51.064: E/AndroidRuntime(1261): Process: com.example.hegemony, PID: 1261
02-25 14:46:51.064: E/AndroidRuntime(1261): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.hegemony/com.example.hegemony.PlayerTurn}: java.lang.NullPointerException
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.hegemony"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.hegemony.SplashScreen"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.example.hegemony.StartScreen" >
<intent-filter>
<action android:name="com.example.hegemony.STARTSCREEN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name="com.example.hegemony.SetupHomeScreen" >
<intent-filter>
<action android:name="com.example.hegemony.SETUPHOMESCREEN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name="com.example.hegemony.SetupPlayer"
android:label="#string/app_name" >
<intent-filter>
<action android:name="com.example.hegemony.SETUPPLAYER" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name="com.example.hegemony.PlayerTurn"
android:label="#string/app_name" >
<intent-filter>
<action android:name="com.example.hegemony.PLAYERTURN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
Java Code of sending activity:
public class SetupHomeScreen extends Activity{
private ArrayList<Player> p = GameMaster.players;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setup_home_screen);
getActionBar().hide();
updatePlayers();
Button gotoInput = (Button) findViewById(R.id.btnSetupPlayer);
gotoInput.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent toInput = new Intent("com.example.hegemony.SETUPPLAYER");
startActivity(toInput);
}
});
Button startGame = (Button) findViewById(R.id.btnStartGame);
startGame.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent toStart = new Intent("com.example.hegemony.PLAYERTURN");
startActivity(toStart);
}
});
}
public void updatePlayers(){
TextView playerList = (TextView) findViewById(R.id.playerList);
String msg = "";
for(int i=0;i < p.size();i++)
msg = msg + "\n - "+p.get(i).getName();
playerList.setText(msg);
if(p.size() >=2){
Button enable = (Button) findViewById(R.id.btnStartGame);
enable.setEnabled(true);
}
}
}
Java code of receiving activity:
public class PlayerTurn extends Activity {
final ActionBar actionBar = getActionBar();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player_turn);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.TabListener tabListener = new ActionBar.TabListener() {
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
};
}
}
Button startGame = (Button) findViewById(R.id.btnStartGame);
startGame.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent toStart = new Intent(SendingActivity.this, NewActivity.class);
startActivity(toStart);
}
});
I think this is how you should start an intent. Maybe its missing a context or the "activityname" is not the right way to do it. I tried to start an activity the way you are trying and it gave me an error as well, not the same one, but it didn't work.
I'm sorry if the solution I'm trying to provide doesn't work. This is really the first time I'm trying to help someone. I hope it works.
As per the logcat error message, your activity class is failing to instantiate. Instantiation involves the allocation and assignment of any class member variables. In the case of PlayerTurn, the only one is this:
final ActionBar actionBar = getActionBar();
The call to getActionBar() throws a NullPointerException because the activity's window has not been built yet - you should call getActionBar() after setContentView() has been called in onCreate(). You can resolve this by simply moving that line of code into onCreate().
If you still want to retain this as a class member variable, declare it but don't assign it:
ActionBar actionBar;
...and then do the assignment in onCreate():
actionBar = getActionBar();
I want to force my app to run the LoginActivity if there is no account present.
I've done the following but still when I launch the app in the emulator, I have MainActivityTest coming up.
For now I have no Account for my app on the emulator so I expect to simply see the Login screen. However, what I see seems like the MainActivityTest is running
public class AccountAuthenticator extends AbstractAccountAuthenticator {
private Context context;
private static final String TAG = "AccountAuthenticator";
public AccountAuthenticator(final Context context) {
super(context);
this.context = context;
}
#Override
public Bundle addAccount(final AccountAuthenticatorResponse response,
final String accountType, final String authTokenType,
final String[] requiredFeatures, final Bundle options) throws NetworkErrorException {
final Intent intent = new Intent(context, LoginActivity.class);
final Bundle bundle = new Bundle();
bundle.putParcelable(KEY_INTENT, intent);
return bundle;
}
...
}
public class AccountAuthenticatorService extends Service {
private static AccountAuthenticator AUTHENTICATOR;
public IBinder onBind(Intent intent) {
return intent.getAction().equals(ACTION_AUTHENTICATOR_INTENT) ? getAuthenticator()
.getIBinder() : null;
}
private AccountAuthenticator getAuthenticator() {
if (AUTHENTICATOR == null)
AUTHENTICATOR = new AccountAuthenticator(this);
return AUTHENTICATOR;
}
}
public class LoginActivity extends RoboSherlockAccountAuthenticatorActivity {
#Override
public void startActivity(Intent intent) {
if (intent != null && ACTION_VIEW.equals(intent.getAction()))
intent.addCategory(CATEGORY_BROWSABLE);
super.startActivity(intent);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
}
}
My AndroidManifest.xml is like below
<application
android:icon="#drawable/ic_launcher"
android:label="myapp" >
<activity
android:name=".ui.ui.MainActivityTest"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name="com.myapp.AccountAuthenticatorService"
android:exported="false"
android:process=":auth" >
<intent-filter>
<action android:name="android.accounts.AccountAuthenticator" />
</intent-filter>
<meta-data
android:name="android.accounts.AccountAuthenticator"
android:resource="#xml/authenticator" />
</service>
<activity
android:name="com.myapp.LoginActivity"
android:configChanges="orientation|keyboardHidden|screenSize"
android:excludeFromRecents="true" >
<!--
No intent-filter here! This activity is only ever launched by
someone who explicitly knows the class name
-->
</activity>
</application
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.MANAGE_ACCOUNTS" />
<uses-permission android:name="android.permission.AUTHENTICATE_ACCOUNTS" />
<uses-permission android:name="android.permission.READ_SYNC_SETTINGS" />
<uses-permission android:name="android.permission.READ_SYNC_STATS" />
<uses-permission android:name="android.permission.USE_CREDENTIALS" />
<uses-permission android:name="android.permission.WRITE_SYNC_SETTINGS" />
It would be simple if you put value in shared preference once if you complete login process.
and every time when you launch application, once check the sharedpreference value and navigate to activities
Boolean mobile_register_flag = sharedpref.getBoolean("mobile_register_flag", false);
if (!mobile_register_flag) {
Intent intent = new Intent(FlashView.this,
RegisterActivity.class);
startActivity(intent);
} else {
Intent intent = new Intent(FlashView.this,
ActivityTwo.class);
startActivity(intent);
}
When you launch the app in the emulator, MainActivityTest coming up because your AndroidManifest has:
<activity
android:name=".ui.ui.MainActivityTest"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
If you want to launch LoginActivity by default, use
<activity
android:name="com.myapp.LoginActivity"
android:configChanges="orientation|keyboardHidden|screenSize"
android:excludeFromRecents="true" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
Else, if you want to display LoginActivity as the first activity based on some conditions, then
In android manifest, keep MainActivityTest as the default
activity
In MainActivityTest->onCreate, check the condition
and if condition is true, launch LoginActivity