I am making my first android launcher based on a stock launcher. I am trying to add widgets onto my main linear layout. But that doesn't work. It doesn't get furter than the onActivityResult() method. Please help me and thanks so much in advance! My code:
private static final int REQUEST_CREATE_SHORTCUT = 1;
private static final int REQUEST_CREATE_LIVE_FOLDER = 4;
private static final int REQUEST_CREATE_APPWIDGET = 5;
private static final int REQUEST_PICK_APPLICATION = 6;
private static final int REQUEST_PICK_SHORTCUT = 7;
private static final int REQUEST_PICK_LIVE_FOLDER = 8;
private static final int REQUEST_PICK_APPWIDGET = 9;
private static final int REQUEST_PICK_ANYCUT=10;
private static final int REQUEST_SHOW_APP_LIST = 11;
private static final int REQUEST_EDIT_SHIRTCUT = 12;
mAppWidgetManager = AppWidgetManager.getInstance(this);
mAppWidgetHost = new AppWidgetHost(this, R.id.linearLayout);
//Add widgets
void selectWidget() {
int appWidgetId = this.mAppWidgetHost.allocateAppWidgetId();
Intent pickIntent = new Intent(AppWidgetManager.ACTION_APPWIDGET_PICK);
pickIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
addEmptyData(pickIntent);
Log.d("addWidgetProcedure", "Starting activity to pick widget");
startActivityForResult(pickIntent, REQUEST_PICK_APPWIDGET);
}
void addEmptyData(Intent pickIntent) {
ArrayList<AppWidgetProviderInfo> customInfo =
new ArrayList<AppWidgetProviderInfo>();
pickIntent.putParcelableArrayListExtra(
AppWidgetManager.EXTRA_CUSTOM_INFO, customInfo);
ArrayList<Bundle> customExtras = new ArrayList<Bundle>();
pickIntent.putParcelableArrayListExtra(
AppWidgetManager.EXTRA_CUSTOM_EXTRAS, customExtras);
Log.d("addWidgetProcedure", "AddEmptyData");
};
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
Log.d("addWidgetProcedure", "inside onActivityResult");
if (resultCode == RESULT_OK ) {
Log.d("addWidgetProcedure", "RESULT_OK");
if (requestCode == REQUEST_PICK_APPWIDGET) {
Log.d("addWidgetProcedure", "calling configureWidget(data)");
configureWidget(data);
}
else if (requestCode == REQUEST_CREATE_APPWIDGET) {
Log.d("addWidgetProcedure", "calling createWidget(data)");
createWidget(data);
}
}
else if (resultCode == RESULT_CANCELED && data != null) {
Log.d("addWidgetProcedure", "RESULT_CANCELED");
int appWidgetId =
data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
if (appWidgetId != -1) {
mAppWidgetHost.deleteAppWidgetId(appWidgetId);
}
}
}
private void configureWidget(Intent data) {
Bundle extras = data.getExtras();
int appWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
AppWidgetProviderInfo appWidgetInfo =
mAppWidgetManager.getAppWidgetInfo(appWidgetId);
if (appWidgetInfo.configure != null) {
Intent intent =
new Intent(AppWidgetManager.ACTION_APPWIDGET_CONFIGURE);
intent.setComponent(appWidgetInfo.configure);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
startActivityForResult(intent, REQUEST_CREATE_APPWIDGET);
} else {
createWidget(data);
}
}
public void createWidget(Intent data) {
Bundle extras = data.getExtras();
int appWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
AppWidgetProviderInfo appWidgetInfo =
mAppWidgetManager.getAppWidgetInfo(appWidgetId);
AppWidgetHostView hostView =
mAppWidgetHost.createView(this, appWidgetId, appWidgetInfo);
hostView.setAppWidget(appWidgetId, appWidgetInfo);
linearLayout.addView(hostView);
Toast.makeText(getApplicationContext(), "Adding widget", 15).show();
}
When i press menu->add widget, it calls the selectWidget() method.
All the logcat output from when i press menu->add widget to i have selected one.
07-11 14:38:27.178: W/KeyCharacterMap(1751): Bad keycharmap - filesize=32
07-11 14:38:27.178: W/KeyCharacterMap(1751): Error loading keycharmap file '/system/usr/keychars/bravo-keypad.kcm.bin'. hw.keyboards.0.devname='bravo-keypad'
07-11 14:38:27.178: W/KeyCharacterMap(1751): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
07-11 14:38:28.348: D/addWidgetProcedure(1751): AddEmptyData
07-11 14:38:28.348: D/addWidgetProcedure(1751): Starting activity to pick widget
07-11 14:38:28.428: D/addWidgetProcedure(1751): inside onActivityResult
Try replacing your:
private static final int REQUEST_PICK_APPWIDGET = 9;
With:
private static final int REQUEST_PICK_APPWIDGET = 0;
Related
Im trying to make a service that would provide data of usagestat every x second. However i always getting the same value after x second. I already clear the map to include new data set from usagemanager. below is my service class thank you in advance.
I do know that in order to retrieve queries every x time, we may use queryevent. However, the total time in foreground for this fit my project, and i already tested using the code for adapter. In the adapter, it do retrieve usage time, however it only provide new value on restarting the activity where the adapter used.
public class PushService extends Service {
private static final int NOTIF_ID = 1;
private static final String NOTIF_CHANNEL_ID = "Channel_Id_1";
private static final String NOTIF_CHANNEL_ID2 = "Channel_Id_2";
private static final int _DISPLAY_ORDER_USAGE_TIME = 0;
private static final int _DISPLAY_ORDER_LAST_TIME_USED = 1;
private static final int _DISPLAY_ORDER_APP_NAME = 2;
private static final boolean localLOGV = false;
private int mDisplayOrder = _DISPLAY_ORDER_USAGE_TIME;
private AppNameComparator mAppLabelComparator;
private LastTimeUsedComparator mLastTimeUsedComparator;
private UsageTimeComparator mUsageTimeComparator;
private PackageManager mPm;
private UsageStatsManager mUsageStatsManager;
public HashMap<String, Long> mapToFirebase = new HashMap<>();;
public ArrayList<UsageStats> mPackageStats;
public ArrayMap<String, String> mAppLabelMap;
public List<UsageStats> stats;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId){
/*notice*/
startForeground();
if (intent != null){
String uid = intent.getStringExtra("parentUID");
if (!uid.equals("")){
Toast.makeText(this, uid, Toast.LENGTH_SHORT).show();
Handler ha=new Handler();
ha.postDelayed(new Runnable() {
#Override
public void run() {
//call function
pushAppList();
mapToFirebase.clear();
loadDataToMapForFirebase();
Log.d("mapservice", mapToFirebase.toString());
ha.postDelayed(this, 5000);
}
}, 10000);
}
}
return super.onStartCommand(intent, flags, startId);
}
public static class AppNameComparator implements Comparator<UsageStats> {
private Map<String, String> mAppLabelList;
AppNameComparator(Map<String, String> appList) {
mAppLabelList = appList;
}
#Override
public final int compare(UsageStats a, UsageStats b) {
String alabel = mAppLabelList.get(a.getPackageName());
String blabel = mAppLabelList.get(b.getPackageName());
return alabel.compareTo(blabel);
}
}
public void pushAppList(){
mAppLabelMap = new ArrayMap<>();
mPackageStats = new ArrayList<>();
mPm = getPackageManager();
mUsageStatsManager = (UsageStatsManager) getSystemService(Context.USAGE_STATS_SERVICE);
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_YEAR, -5);
mLastTimeUsedComparator = new LastTimeUsedComparator();
mUsageTimeComparator = new UsageTimeComparator();
stats = mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, cal.getTimeInMillis(), System.currentTimeMillis());
if (stats == null) {
return;
}
ArrayMap<String, UsageStats> map = new ArrayMap<>();
int statCount = stats.size();
for (int i = 0; i < statCount; i++) {
Log.d("", String.valueOf(stats.get(i).getTotalTimeInForeground()));
android.app.usage.UsageStats pkgStats = stats.get(i);
// load application labels for each application
try {
ApplicationInfo appInfo = mPm.getApplicationInfo(pkgStats.getPackageName(), 0);
String label = appInfo.loadLabel(mPm).toString();
mAppLabelMap.put(pkgStats.getPackageName(), label);
UsageStats existingStats =
map.get(pkgStats.getPackageName());
if (existingStats == null) {
map.put(pkgStats.getPackageName(), pkgStats);
} else {
existingStats.add(pkgStats);
}
} catch (PackageManager.NameNotFoundException e) {
// This package may be gone.
}
}
mPackageStats.addAll(map.values());
// Sort list
mAppLabelComparator = new AppNameComparator(mAppLabelMap);
sortList();
}
public static class LastTimeUsedComparator implements Comparator<UsageStats> {
#Override
public final int compare(UsageStats a, UsageStats b) {
// return by descending order
return (int)(b.getLastTimeUsed() - a.getLastTimeUsed());
}
}
public static class UsageTimeComparator implements Comparator<UsageStats> {
#Override
public final int compare(UsageStats a, UsageStats b) {
return (int)(b.getTotalTimeInForeground() - a.getTotalTimeInForeground());
}
}
private void sortList() {
if (mDisplayOrder == _DISPLAY_ORDER_USAGE_TIME) {
if (localLOGV) Log.i(TAG, "Sorting by usage time");
Collections.sort(mPackageStats, mUsageTimeComparator);
} else if (mDisplayOrder == _DISPLAY_ORDER_LAST_TIME_USED) {
if (localLOGV) Log.i(TAG, "Sorting by last time used");
Collections.sort(mPackageStats, mLastTimeUsedComparator);
} else if (mDisplayOrder == _DISPLAY_ORDER_APP_NAME) {
if (localLOGV) Log.i(TAG, "Sorting by application name");
Collections.sort(mPackageStats, mAppLabelComparator);
}
}
public void loadDataToMapForFirebase(){
/*TODO UPDATE DATA ONBACKGROUND*/
String system_sign = "android";
PackageManager pm = getPackageManager();
if (mPackageStats.size() != 0){
for (int i = 0; i < mPackageStats.size(); i++){
if (pm.checkSignatures(system_sign, mPackageStats.get(i).getPackageName()) == PackageManager.SIGNATURE_MATCH) {
Log.d("CheckAppSys", mPackageStats.get(i).getPackageName() + " is sys.");
} else {
String usagetime = DateUtils.formatElapsedTime(mPackageStats.get(i).getTotalTimeInForeground() / 1000);
Pattern special= Pattern.compile("[^a-z0-9 ]", Pattern.CASE_INSENSITIVE);
Matcher matcher = special.matcher(Objects.requireNonNull(mAppLabelMap.get(mPackageStats.get(i).getPackageName())));
boolean constainsSymbols = matcher.find();
if(!constainsSymbols){
mapToFirebase.put(mAppLabelMap.get(mPackageStats.get(i).getPackageName()), mPackageStats.get(i).getTotalTimeInForeground());
}
Log.d("maptofirebase", mapToFirebase.toString());
Log.d("CheckApp", mPackageStats.get(i).getPackageName() + " is not sys.");
}
}
}
}
private void startForeground() {
Intent notificationIntent = new Intent(this, UsageStatsActivity.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel1 = new NotificationChannel(
NOTIF_CHANNEL_ID,
"Channel 1",
NotificationManager.IMPORTANCE_HIGH
);
channel1.setDescription("This is channel 1");
NotificationChannel channel2 = new NotificationChannel(
NOTIF_CHANNEL_ID2,
"Channel 2",
NotificationManager.IMPORTANCE_LOW
);
channel2.setDescription("This is channel 2");
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel1);
manager.createNotificationChannel(channel2);
}
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
startForeground(NOTIF_ID, new NotificationCompat.Builder(this,
NOTIF_CHANNEL_ID) // don't forget create a notification channel first
.setOngoing(true)
.setSmallIcon(R.drawable.logo)
.setContentTitle(getString(R.string.app_name))
.setContentText("Monitoring apps.")
.setContentIntent(pendingIntent)
.build());
}
}
I have a problem, I wonder how I can send data from BroadcastReceiver(it is in Service) to widget and update widget after click button.
Specifically, I mean how to send this title song to my widget
Below is my BroadcastReciver:
private final BroadcastReceiver mWidgetEventsReceiver = new BroadcastReceiver() {
private Bundle extras;
private MediaService mService;
AppWidgetManager appWidgetManager;
private static final String TAG = "MediaMusicWidgetProvider";
#Override
public void onReceive(Context context, Intent intent) {
extras = intent.getExtras();
Log.d(TAG, extras.getString("EVENT"));
if (extras.getString("EVENT") == "NEXT") {
Log.d(TAG, "onReceive: switch");
if (mPlaybackModel != null) {
MediaItemMetadata mediaItemMetadata = mPlaybackModel.getMetadata();
if (mediaItemMetadata != null) {
MediaPlayerSong song = new MediaPlayerSong();
song.setTitle(mediaItemMetadata.getTitle() + "");
song.setDurationSec((int) (mPlaybackModel.getMaxProgress() / 1000));
song.setArtist(mediaItemMetadata.getSubtitle() + "");
song.setAlbum(mediaItemMetadata.getDescription() + "");
String title = mediaItemMetadata.getTitle()+"";
Log.d(TAG, "onReceive: "+title);
}
}
onNextTrack();
}
and there is my Provider
protected PendingIntent getPendingSelfIntent(Context context, String action) {
Intent intent = new Intent(context, MediaMusicWidgetProvider.class);
intent.setAction(action);
return PendingIntent.getBroadcast(context, 0, intent, 0);
}
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
log("onUpdate");
for (int appWidgetId : appWidgetIds) {
mViews = new RemoteViews(context.getPackageName(), R.layout.media_widget_blue);
appWidgetManager.updateAppWidget(appWidgetId, mViews);
}
}
#Override
public void onReceive(Context context, Intent intent) {
log("onReceive");
super.onReceive(context, intent);
if (intent.getAction() == NEXT_BUTTON) {
Toast.makeText(context, "Button next", Toast.LENGTH_SHORT).show();
Intent eventIntent = new Intent("com.mobica.widget.action.TEST");
eventIntent.putExtra("EVENT", NEXT_BUTTON);
LocalBroadcastManager.getInstance(context).sendBroadcast(eventIntent);;
} else if (intent.getAction() == PREV_BUTTON) {
Toast.makeText(context, "Button prev", Toast.LENGTH_SHORT).show();
Intent eventIntent = new Intent("com.mobica.widget.action.TEST");
eventIntent.putExtra("EVENT", PREV_BUTTON);
LocalBroadcastManager.getInstance(context).sendBroadcast(eventIntent);
} else if (intent.getAction() == PAUSE_BUTTON) {
Toast.makeText(context, "Button pause", Toast.LENGTH_SHORT).show();
Intent eventIntent = new Intent("com.mobica.widget.action.TEST");
eventIntent.putExtra("EVENT", PAUSE_BUTTON);
LocalBroadcastManager.getInstance(context).sendBroadcast(eventIntent);
}
}
#Override
public void onAppWidgetOptionsChanged(Context context, AppWidgetManager appWidgetManager, int appWidgetId, Bundle newOptions) {
log("onAppWidgetOptionsChanged");
mViews = new RemoteViews(context.getPackageName(), getProperLayout(context, newOptions));
mViews.setOnClickPendingIntent(mNextBtnId, getPendingSelfIntent(context, NEXT_BUTTON));
mViews.setOnClickPendingIntent(mPrevBtnId, getPendingSelfIntent(context, PREV_BUTTON));
mViews.setOnClickPendingIntent(mPauseBtnId, getPendingSelfIntent(context, PAUSE_BUTTON));
appWidgetManager.updateAppWidget(appWidgetId, mViews);
}
private int getProperLayout(Context context, Bundle newOptions) {
int maxWidth = newOptions.getInt(AppWidgetManager.OPTION_APPWIDGET_MAX_WIDTH);
int maxHeight = newOptions.getInt(AppWidgetManager.OPTION_APPWIDGET_MAX_HEIGHT);
int minHeight = newOptions.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_HEIGHT);
int minWidth = newOptions.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH);
log("Min width: " + minWidth + "\nMax width: " + maxWidth + "\nMin height: " + minHeight + "\nMaxHeight: " + maxHeight);
boolean isLongWidget = minWidth > 460;
String currentTheme = Settings.Global.getString(context.getContentResolver(), THEME_KEY);
int properLayoutId = isLongWidget ? R.layout.media_widget_blue_long : R.layout.media_widget_blue;
if (currentTheme == null) {
return properLayoutId;
}
switch (currentTheme) {
case THEME_BLUE:
properLayoutId = isLongWidget ? R.layout.media_widget_blue_long : R.layout.media_widget_blue;
break;
case THEME_GREEN:
properLayoutId = isLongWidget ? R.layout.media_widget_green_long : R.layout.media_widget_green;
break;
case THEME_PURPLE:
properLayoutId = isLongWidget ? R.layout.media_widget_purple_long : R.layout.media_widget_purple;
break;
}
return properLayoutId;
}
}
I try do it like here https://stackoverflow.com/a/4412949/11766578 but I have problem with this line of code:
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_2x1);
like u can see above I switch layout in dependencies which color of theme user select. Please for help! :)
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
public class MainActivity extends Activity {
private static final String TAG = "MainActivity";
ProductDatabase.ProductDatabaseHelper controller = new ProductDatabase.ProductDatabaseHelper(this);
EditText mBarcodeEdit;
EditText mFormatEdit;
EditText mTitleEdit;
EditText mPriceEdit;
private static final int ZBAR_SCANNER_REQUEST = 0;
private static final int ZBAR_QR_SCANNER_REQUEST = 1;
private static final ProductData mProductData = new ProductData();
Button mScanButton;
Button mAddButton;
Button mSelectButton;
Button mExportButton;
Button btnimport;
ProductDatabase mProductDb;
ListView ls;
TextView infotext;
File file = null;
// DatabaseHelper dbhelper = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ls = (ListView) findViewById(R.id.placeslist);
mBarcodeEdit = (EditText) findViewById(R.id.barcodeEdit);
mFormatEdit = (EditText) findViewById(R.id.codeFormatEdit);
mTitleEdit = (EditText) findViewById(R.id.titleEdit);
mPriceEdit = (EditText) findViewById(R.id.priceEdit);
mScanButton = (Button) findViewById(R.id.scan_btn);
mAddButton = (Button) findViewById(R.id.addButton);
mSelectButton = (Button) findViewById(R.id.selelctButton);
mProductDb = new ProductDatabase(this); // not yet shown
infotext = (TextView) findViewById(R.id.txtresulttext);
mExportButton = (Button) findViewById(R.id.exportbtn);
mSelectButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, product_list.class);
startActivity(i);
}
});
mAddButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String barcode = mBarcodeEdit.getText().toString();
String format = mFormatEdit.getText().toString();
String title = mTitleEdit.getText().toString();
String price = mPriceEdit.getText().toString();
String errors = validateFields(barcode, format, title, price);
if (errors.length() > 0) {
showInfoDialog(MainActivity.this, "Please fix errors", errors);
} else {
mProductData.barcode = barcode;
mProductData.format = format;
mProductData.title = title;
mProductData.price = new BigDecimal(price);
mProductDb.insert(mProductData);
showInfoDialog(MainActivity.this, "Success", "Product saved successfully");
resetForm();
}
}
});
mExportButton.setOnClickListener(new View.OnClickListener() {
SQLiteDatabase sqldb = controller.getReadableDatabase(); //My Database class
Cursor c =null;
#Override
public void onClick(View view) { //main code begins here
try {
c = sqldb.rawQuery("select * from spot_pay.db", null);
int rowcount = 0;
int colcount = 0;
File sdCardDir = Environment.getExternalStorageDirectory();
String filename = "MyBackUp.csv";
// the name of the file to export with
File saveFile = new File(sdCardDir, filename);
FileWriter fw = new FileWriter(saveFile);
BufferedWriter bw = new BufferedWriter(fw);
rowcount = c.getCount();
colcount = c.getColumnCount();
if (rowcount > 0) {
c.moveToFirst();
for (int i = 0; i < colcount; i++) {
if (i != colcount - 1) {
bw.write(c.getColumnName(i) + ",");
} else {
bw.write(c.getColumnName(i));
}
}
bw.newLine();
for (int i = 0; i < rowcount; i++) {
c.moveToPosition(i);
for (int j = 0; j < colcount; j++) {
if (j != colcount - 1)
bw.write(c.getString(j) + ",");
else
bw.write(c.getString(j));
}
bw.newLine();
}
bw.flush();
infotext.setText("Exported Successfully.");
}
} catch (Exception ex) {
if (sqldb.isOpen()) {
sqldb.close();
infotext.setText(ex.getMessage().toString());
}
} finally {
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
private void showInfoDialog(Context context, String title, String information) {
new AlertDialog.Builder(context)
.setMessage(information)
.setTitle(title)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).show();
}
private void resetForm() {
// TODO Auto-generated method stub
mBarcodeEdit.getText().clear();
mFormatEdit.getText().clear();
mTitleEdit.getText().clear();
mPriceEdit.getText().clear();
}
public void launchScanner(View v) {
if (isCameraAvailable()) {
Intent intent = new Intent(this, ZBarScannerActivity.class);
startActivityForResult(intent, ZBAR_SCANNER_REQUEST);
} else {
Toast.makeText(this, "Rear Facing Camera Unavailable", Toast.LENGTH_SHORT).show();
}
}
public void launchQRScanner(View v) {
if (isCameraAvailable()) {
Intent intent = new Intent(this, ZBarScannerActivity.class);
intent.putExtra(ZBarConstants.SCAN_MODES, new int[]{Symbol.QRCODE});
startActivityForResult(intent, ZBAR_SCANNER_REQUEST);
} else {
Toast.makeText(this, "Rear Facing Camera Unavailable", Toast.LENGTH_SHORT).show();
}
}
public boolean isCameraAvailable() {
PackageManager pm = getPackageManager();
return pm.hasSystemFeature(PackageManager.FEATURE_CAMERA);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case ZBAR_SCANNER_REQUEST:
case ZBAR_QR_SCANNER_REQUEST:
if (resultCode == RESULT_OK) {
mBarcodeEdit.setText(data.getStringExtra(ZBarConstants.SCAN_RESULT));
// Toast.makeText(this, "Scan Result = " + data.getStringExtra(ZBarConstants.SCAN_RESULT), Toast.LENGTH_SHORT).show();
} else if (resultCode == RESULT_CANCELED && data != null) {
String error = data.getStringExtra(ZBarConstants.ERROR_INFO);
if (!TextUtils.isEmpty(error)) {
Toast.makeText(this, error, Toast.LENGTH_SHORT).show();
}
}
break;
}
}
private static String validateFields(String barcode, String format,
String title, String price) {
StringBuilder errors = new StringBuilder();
if (barcode.matches("^\\s*$")) {
errors.append("Barcode required\n");
}
if (format.matches("^\\s*$")) {
errors.append("Format required\n");
}
if (title.matches("^\\s*$")) {
errors.append("Title required\n");
}
if (!price.matches("^-?\\d+(.\\d+)?$")) {
errors.append("Need numeric price\n");
}
return errors.toString();
}
}
I think string may be null somewhere. Please type something in textfield or check for null string.
I am having trouble carrying over a user selected image/gif to the main LWP service. I start off by prompting the user to select a gif through this PreferenceActivity (some of this was borrowed from members here and tutorials on Vogella)
public class GifPreference extends PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener{
#SuppressWarnings("deprecation")
//SharedPreferences SHARED_PREF;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getPreferenceManager().setSharedPreferencesName("custom_gif");
addPreferencesFromResource(R.xml.prefsettings);
getPreferenceManager().getSharedPreferences().registerOnSharedPreferenceChangeListener(
this);
getPreferenceManager().findPreference("custom_gif").setOnPreferenceClickListener(new OnPreferenceClickListener()
{
public boolean onPreferenceClick(Preference preference)
{
Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();
Toast.makeText(getBaseContext(), "Select a GIF - " + (width) + " x " + height , Toast.LENGTH_LONG).show();
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, 1);
return true;
}
});
}
public String getRealPathFromURI(Uri contentUri) {
String [] proj={MediaColumns.DATA};
Cursor cursor = managedQuery( contentUri,
proj, // Which columns to return
null, // WHERE clause; which rows to return (all rows)
null, // WHERE clause selection arguments (none)
null); // Order-by clause (ascending by name)
int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if (resultCode == Activity.RESULT_OK) {
Uri selectedImage = data.getData();
String RealPath;
SharedPreferences customSharedPreference = getSharedPreferences("custom_gif", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = customSharedPreference.edit ();
RealPath = getRealPathFromURI (selectedImage);
editor.putString("custom_gif", RealPath);
editor.commit();
ComponentName component = new ComponentName(getPackageName(), getPackageName() + ".LWPEngine");
Intent intent = new Intent(WallpaperManager.ACTION_CHANGE_LIVE_WALLPAPER);
intent.putExtra(WallpaperManager.EXTRA_LIVE_WALLPAPER_COMPONENT, component);
startActivity(intent);
}}
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onDestroy() {
getPreferenceManager().getSharedPreferences().
unregisterOnSharedPreferenceChangeListener(this);
super.onDestroy();
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
}
}
And this is the main LWPService:
public class LWPEngine extends WallpaperService {
private static int RESULT_LOAD_IMAGE1 = 1;
static final Handler mGIFHandler = new Handler();
//public String gifBG;
public Engine onCreateEngine() {
try {
LWPEngine.GIFEngine var1 = new LWPEngine.GIFEngine();
return var1;
} catch (IOException var3) {
return null;
}
}
class GIFEngine extends Engine {
private LWPEngineHelper lWPEngineHelper = new LWPEngineHelper(LWPEngine.this.getApplicationContext(), LWPEngine.this.getResources());
private final Movie mGIF;
private final int mGIFDuration;
private final int mGIFHeight;
private final Runnable mGIFRunnable;
private final int mGIFWidth;
private String mImageScale = "Stretch to screen";
private long mStart;
private int mWhen;
#SuppressWarnings("unused")
public GIFEngine() throws IOException {
//decodes and plays the gif - if no gif is found, throw an error.
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(LWPEngine.this);
String gifBG = prefs.getString("custom_gif", "This file does not work");
InputStream var2 = new FileInputStream(gifBG);
//InputStream var2 = LWPEngine.this.getResources().openRawResource(R.drawable.dogegif);
if(var2 != null) {
try {
this.mGIF = Movie.decodeStream(var2);
this.mGIFDuration = this.mGIF.duration();
} finally {
var2.close();
}
this.mGIFWidth = this.mGIF.width();
this.mGIFHeight = this.mGIF.height();
this.mWhen = -1;
this.mGIFRunnable = new Runnable() {
public void run() {
GIFEngine.this.animGIF();
}
};
} else {
throw new IOException("Can't open GIF");
}
}
void animGIF()
{
tick();
SurfaceHolder localSurfaceHolder = getSurfaceHolder();
Canvas localCanvas = null;
/* try
{*/
localCanvas = localSurfaceHolder.lockCanvas();
if (localCanvas != null)
animGIFDraw(localCanvas);
if (localCanvas != null)
localSurfaceHolder.unlockCanvasAndPost(localCanvas);
LWPEngine.mGIFHandler.removeCallbacks(this.mGIFRunnable);
if (isVisible())
LWPEngine.mGIFHandler.postDelayed(this.mGIFRunnable, 40L);
return;
/* }
finally
{
if (localCanvas != null)
localSurfaceHolder.unlockCanvasAndPost(localCanvas);
}*/
}
void animGIFDraw(Canvas var1) {
this.lWPEngineHelper.setBackground(var1);
var1.save();
PointF var3 = this.lWPEngineHelper.getCanvasScale(this.mImageScale, this.mGIFWidth, this.mGIFHeight);
var1.scale(var3.x, var3.y);
this.mGIF.setTime(this.mWhen);
Point var5 = this.lWPEngineHelper.getImagePos(var3, this.mGIFWidth, this.mGIFHeight);
this.mGIF.draw(var1, (float)var5.x, (float)var5.y);
var1.restore();
}
public void onDestroy() {
super.onDestroy();
LWPEngine.mGIFHandler.removeCallbacks(this.mGIFRunnable);
}
public void onOffsetsChanged(float var1, float var2, float var3, float var4, int var5, int var6) {
super.onOffsetsChanged(var1, var2, var3, var4, var5, var6);
this.animGIF();
}
public void onSurfaceChanged(SurfaceHolder var1, int var2, int var3, int var4) {
super.onSurfaceChanged(var1, var2, var3, var4);
this.animGIF();
}
public void onVisibilityChanged(boolean var1) {
super.onVisibilityChanged(var1);
if(var1) {
this.animGIF();
} else {
LWPEngine.mGIFHandler.removeCallbacks(this.mGIFRunnable);
}
}
public void onSharedPreferenceChanged(SharedPreferences prefs,
String key) {
String gifBG = prefs.getString("custom_gif", "This file does not work");
//gifBG = prefs.getString("custom_gif", "Bad Image");
}
void tick() {
if((long)this.mWhen == -1L) {
this.mWhen = 0;
this.mStart = SystemClock.uptimeMillis();
} else {
if(this.mGIFDuration!=0) {
this.mWhen = (int)((SystemClock.uptimeMillis() - this.mStart) % (long)this.mGIFDuration);
}
}
}
}
}
I keep getting a null pointer exception - I'm guess because there's nothing there - so I'm obviously not setting the shared preferences right - or it's the inputstream...
Any help in getting a user selected image to the inputstream of the main LWPservice would be very helpful!
**Edit I should mention everything works up until I start the LWPService after selecting the GIF. It's when loading the lwp I get the error. using a static GIF in the drawable does work.
Thanks in advanced,
Marc
I figured out the answer in case anyone is curious.
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(LWPEngine.this);
String gifBG = prefs.getString("custom_gif", "This file does not work");
needs to be:
SharedPreferences prefs = getApplicationContext().getSharedPreferences("custom_gif",MODE_PRIVATE);
String gifBG = prefs.getString("custom_gif", "This file does not work");
Also needed to change this in my SharedPreference class as well.
getSharedPreference needs context, and the way I had it before for was limiting the scope of the "global" capabilities of the SharedPreference method.
I hope that helps people!
I have this code to put sound in as a contact but when I insert the second case java recognize me if a duplicate any ideas? I've lightened the code so as not to confuse thanks in advance:
code:
static final int PICK_CONTACT1 = 1;
static final int PICK_CONTACT2 = 1;
// first Intent intent = new Intent(Intent.ACTION_PICK,
ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT1);
// second
Intent intent = new Intent(Intent.ACTION_PICK,
ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT2);
#Override
public void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
switch (reqCode) {
case (PICK_CONTACT1):
if (resultCode == Activity.RESULT_OK) {
Uri contactData = data.getData();
Cursor c = managedQuery(contactData, null, null, null, null);
if (c.moveToFirst()) { //ecc...
case (PICK_CONTACT2):
if (resultCode == Activity.RESULT_OK) {
Uri contactData = data.getData();
Cursor c = managedQuery(contactData, null, null, null, null);
if (c.moveToFirst()) {
String id = c
.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts._ID));
here is the problem
static final int PICK_CONTACT1 = 1;
static final int PICK_CONTACT2 = 1;
that's why java sees is as duplicate, here is the correct one
static final int PICK_CONTACT1 = 1;
static final int PICK_CONTACT2 = 2;
You have both PICK_CONTACT1 and PICK_CONTACT2 equal to 1:
static final int PICK_CONTACT1 = 1;
static final int PICK_CONTACT2 = 1;
So you're effectively doing:
switch(reqCode) {
case 1:
//stuff
case 1:
//stuff
}
You'll need to make those different values. Also, make sure you add a break at the end of each case.